Skip to content

Commit de93713

Browse files
authored
add tests for zbusctx (#54)
1 parent 375f072 commit de93713

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

pkg/perf/zbusctx_test.go

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package perf
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
"github.com/stretchr/testify/require"
9+
"github.com/threefoldtech/zbus"
10+
"github.com/threefoldtech/zosbase/pkg/mocks"
11+
"go.uber.org/mock/gomock"
12+
)
13+
14+
func TestWithZbusClient(t *testing.T) {
15+
t.Run("adds client to context", func(t *testing.T) {
16+
ctrl := gomock.NewController(t)
17+
defer ctrl.Finish()
18+
19+
mockClient := mocks.NewMockClient(ctrl)
20+
ctx := WithZbusClient(context.Background(), mockClient)
21+
22+
retrievedClient, ok := ctx.Value(zbusClientKey{}).(zbus.Client)
23+
assert.True(t, ok)
24+
assert.Equal(t, mockClient, retrievedClient)
25+
})
26+
}
27+
28+
func TestMustGetZbusClient(t *testing.T) {
29+
t.Run("successfully retrieves client", func(t *testing.T) {
30+
ctrl := gomock.NewController(t)
31+
defer ctrl.Finish()
32+
33+
mockClient := mocks.NewMockClient(ctrl)
34+
ctx := WithZbusClient(context.Background(), mockClient)
35+
36+
retrievedClient := MustGetZbusClient(ctx)
37+
assert.Equal(t, mockClient, retrievedClient)
38+
})
39+
40+
t.Run("panics when client not in context", func(t *testing.T) {
41+
ctx := context.Background()
42+
43+
assert.Panics(t, func() {
44+
MustGetZbusClient(ctx)
45+
})
46+
})
47+
48+
t.Run("panics when context value is wrong type", func(t *testing.T) {
49+
ctx := context.WithValue(context.Background(), zbusClientKey{}, "not a client")
50+
assert.Panics(t, func() {
51+
MustGetZbusClient(ctx)
52+
})
53+
})
54+
}
55+
56+
func TestTryGetZbusClient(t *testing.T) {
57+
58+
t.Run("successfully retrieves client", func(t *testing.T) {
59+
ctrl := gomock.NewController(t)
60+
defer ctrl.Finish()
61+
62+
mockClient := mocks.NewMockClient(ctrl)
63+
ctx := WithZbusClient(context.Background(), mockClient)
64+
65+
retrievedClient, err := TryGetZbusClient(ctx)
66+
require.NoError(t, err)
67+
assert.Equal(t, mockClient, retrievedClient)
68+
})
69+
70+
t.Run("returns error when client not in context", func(t *testing.T) {
71+
ctx := context.Background()
72+
73+
retrievedClient, err := TryGetZbusClient(ctx)
74+
require.Error(t, err)
75+
assert.Nil(t, retrievedClient)
76+
assert.Contains(t, err.Error(), "context does not have zbus client")
77+
})
78+
79+
t.Run("returns error when context value is wrong type", func(t *testing.T) {
80+
ctx := context.WithValue(context.Background(), zbusClientKey{}, "not a client")
81+
82+
retrievedClient, err := TryGetZbusClient(ctx)
83+
require.Error(t, err)
84+
assert.Nil(t, retrievedClient)
85+
assert.Contains(t, err.Error(), "context does not have zbus client")
86+
})
87+
}

0 commit comments

Comments
 (0)