-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathcall_lifecycle_test.go
More file actions
202 lines (186 loc) · 5.33 KB
/
Copy pathcall_lifecycle_test.go
File metadata and controls
202 lines (186 loc) · 5.33 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package gomeassistant
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/require"
"saml.dev/gome-assistant/internal/services"
)
func TestCallCanceledBeforeSend(t *testing.T) {
app, err := NewApp(context.Background(), NewAppRequest{
URL: "http://127.0.0.1:1",
HAAuthToken: "token",
})
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
cancel()
err = app.Call(ctx, services.BaseServiceRequest{}, nil)
require.ErrorIs(t, err, context.Canceled)
}
func TestCallReturnsWhenCleanupClosesConnection(t *testing.T) {
callSeen := make(chan struct{})
ready := make(chan struct{})
var callOnce sync.Once
upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/states/zone.home" {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"entity_id":"zone.home","state":"zoning","attributes":{"latitude":1,"longitude":2}}`))
return
}
if r.URL.Path != "/api/websocket" {
http.NotFound(w, r)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
_ = conn.WriteJSON(map[string]string{"type": "auth_required"})
if _, _, err := conn.ReadMessage(); err != nil {
return
}
_ = conn.WriteJSON(map[string]string{"type": "auth_ok"})
for {
_, message, err := conn.ReadMessage()
if err != nil {
return
}
var request struct {
ID int64 `json:"id"`
Type string `json:"type"`
}
if json.Unmarshal(message, &request) == nil && request.Type == "call_service" {
callOnce.Do(func() { close(callSeen) })
}
if request.Type == "subscribe_events" {
select {
case <-ready:
default:
close(ready)
}
}
if request.ID != 0 && request.Type != "call_service" {
_ = conn.WriteJSON(map[string]any{"id": request.ID, "type": "result", "success": true, "result": nil})
}
}
}))
t.Cleanup(server.Close)
app := fakeApp(t, server.URL)
runDone := make(chan error, 1)
go func() { runDone <- app.Start(context.Background()) }()
select {
case <-ready:
case <-time.After(time.Second):
t.Fatal("fake server did not authenticate")
}
callDone := make(chan error, 1)
go func() { callDone <- app.Call(context.Background(), services.BaseServiceRequest{}, nil) }()
select {
case <-callSeen:
case <-time.After(time.Second):
t.Fatal("fake server did not receive call")
}
// The observed call is the pending Call's request. Cleaning up the app must
// wake it through the captured connection's terminal channel.
app.Cleanup()
select {
case err := <-callDone:
require.Error(t, err)
case <-time.After(time.Second):
t.Fatal("Call did not return after app cleanup")
}
select {
case <-runDone:
case <-time.After(time.Second):
t.Fatal("Start did not return after app cleanup")
}
}
func TestCallReturnsWhenStartupFailureClosesConnectionBeforeStart(t *testing.T) {
startupLoadStarted := make(chan struct{})
failStartup := make(chan struct{})
callSeen := make(chan struct{})
var startupLoadOnce sync.Once
var failStartupOnce sync.Once
var callOnce sync.Once
upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/states/zone.home" {
startupLoadOnce.Do(func() { close(startupLoadStarted) })
select {
case <-failStartup:
http.Error(w, "startup failed", http.StatusInternalServerError)
case <-r.Context().Done():
}
return
}
if r.URL.Path != "/api/websocket" {
http.NotFound(w, r)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
if err := conn.WriteJSON(map[string]string{"type": "auth_required"}); err != nil {
return
}
if _, _, err := conn.ReadMessage(); err != nil {
return
}
if err := conn.WriteJSON(map[string]string{"type": "auth_ok"}); err != nil {
return
}
for {
_, message, err := conn.ReadMessage()
if err != nil {
return
}
var request struct {
Type string `json:"type"`
}
if json.Unmarshal(message, &request) == nil && request.Type == "call_service" {
callOnce.Do(func() { close(callSeen) })
}
}
}))
t.Cleanup(func() {
failStartupOnce.Do(func() { close(failStartup) })
server.Close()
})
app := fakeApp(t, server.URL)
runDone := make(chan error, 1)
go func() { runDone <- app.Start(context.Background()) }()
select {
case <-startupLoadStarted:
case <-time.After(time.Second):
t.Fatal("Start did not begin loading startup state")
}
callDone := make(chan error, 1)
go func() { callDone <- app.Call(context.Background(), services.BaseServiceRequest{}, nil) }()
select {
case <-callSeen:
case <-time.After(time.Second):
t.Fatal("Call was not admitted during startup")
}
failStartupOnce.Do(func() { close(failStartup) })
select {
case err := <-callDone:
require.ErrorIs(t, err, ErrConnectionClosed)
case <-time.After(time.Second):
t.Fatal("Call did not return after startup closed the connection")
}
select {
case err := <-runDone:
require.Error(t, err)
case <-time.After(time.Second):
t.Fatal("Start did not return after startup failure")
}
}