-
Notifications
You must be signed in to change notification settings - Fork 4
/
bridge_test.go
99 lines (94 loc) · 2.21 KB
/
bridge_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
92
93
94
95
96
97
98
99
package hue
import (
"encoding/json"
"net/http"
"reflect"
"testing"
)
// addrTestsuite is a suite of tests for the internal addr function.
var addrTestsuite = map[string]struct {
In []string
Out string
}{
"no-tokens": {
In: []string{},
Out: "http://1.2.3.4/api",
},
"one-token": {
In: []string{"a"},
Out: "http://1.2.3.4/api/user/a",
},
"three-tokens": {
In: []string{"a", "b", "c"},
Out: "http://1.2.3.4/api/user/a/b/c",
},
}
func TestAddr(t *testing.T) {
b := Bridge{
bridgeID: bridgeID{IP: "http://1.2.3.4/"},
username: "user",
}
for name, tt := range addrTestsuite {
t.Run(name, func(t *testing.T) {
if got := b.addr(tt.In...); got != tt.Out {
t.Fatalf("expected %v, got %v", tt.Out, got)
}
})
}
}
// callTestsuite is a test suite for the internal call function.
var callTestsuite = map[string]struct {
Response []byte
Result []byte
Error error
}{
// simple JSON response
"success": {
Response: []byte(`{"some": "message"}`),
Result: []byte(`{"some": "message"}`),
},
// array response
"success-array": {
Response: []byte(`[{"some": "message"},{"some": "message"}]`),
Result: []byte(`[{"some": "message"},{"some": "message"}]`),
},
// invalid JSON
"invalid-json": {
Response: []byte(`not json`),
Error: &json.SyntaxError{Offset: 2},
},
// should return parsed error
"failure": {
Response: []byte(`[{"error": {"type":101,"address":"a/b/c","description":"blah"}}]`),
Error: APIError{Code: 101, URL: "a/b/c", Msg: "blah"},
},
}
func TestCall(t *testing.T) {
for name, tt := range callTestsuite {
t.Run(name, func(t *testing.T) {
srv := serverWithResponse(string(tt.Response))
defer srv.Close()
msg, err := (Bridge{
bridgeID: bridgeID{IP: srv.URL + "/"},
}).call(http.MethodGet, "some body")
if tt.Error != nil {
if err == nil {
t.Fatalf("expected error")
}
if _, ok := tt.Error.(APIError); ok {
if !reflect.DeepEqual(tt.Error, err) {
t.Fatalf("expected error %v, got %v", tt.Error, err)
}
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
return
}
if !reflect.DeepEqual(tt.Response, msg) {
t.Fatalf("expected %s, got %s", tt.Response, msg)
}
})
}
}