forked from amenzhinsky/iothub
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient_module_test.go
91 lines (78 loc) · 1.89 KB
/
client_module_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package iotdevice
import (
"context"
"encoding/json"
"testing"
"time"
"gitlab.com/michaeljohn/iothub/iotdevice/iotdevicetest"
"gitlab.com/michaeljohn/iothub/iotdevice/transport/mqtt"
"gitlab.com/michaeljohn/iothub/iotservice"
)
func newModuleClient(t *testing.T, sc *iotservice.Client) *ModuleClient {
t.Helper()
device := iotdevicetest.NewDevice(t, sc)
module := iotdevicetest.NewModule(t, sc, device.DeviceID)
mcs, err := sc.ModuleConnectionString(module, false)
if err != nil {
t.Fatal(err)
}
creds, err := ParseModuleConnectionString(mcs)
if err != nil {
t.Fatal(err)
}
tr := mqtt.NewModuleTransport()
c, err := NewModule(tr, creds)
if err != nil {
t.Fatal(err)
}
if err := c.Connect(context.Background()); err != nil {
t.Fatal(err)
}
return c
}
func getDesiredState(twin []byte) map[string]any {
var v struct {
Desired map[string]any `json:"desired"`
}
json.Unmarshal(twin, &v)
return v.Desired
}
func TestSubscribeTwinUpdates(t *testing.T) {
sc := iotdevicetest.NewServiceClient(t)
mc := newModuleClient(t, sc)
twinStateSub, err := mc.SubscribeTwinUpdates(context.Background())
if err != nil {
t.Fatal(err)
}
twin, err := sc.UpdateModuleTwin(context.Background(), &iotservice.ModuleTwin{
DeviceID: mc.creds.GetDeviceID(),
ModuleID: mc.creds.GetModuleID(),
Properties: &iotservice.Properties{
Desired: map[string]interface{}{
"hw": "1.12",
},
},
})
if err != nil {
t.Fatal(err)
}
stateChan := twinStateSub.C()
select {
case ret := <-stateChan:
retDesire := getDesiredState(ret)
for k, v := range twin.Properties.Desired {
if k == "$metadata" {
continue
}
retVal, ok := retDesire[k]
if !ok {
t.Errorf("twin desired property %s not received", k)
}
if retVal != v {
t.Errorf("twin desired property %s = %s, want %s", k, retVal, v)
}
}
case <-time.After(1 * time.Second):
t.Error("twin update not received")
}
}