-
Notifications
You must be signed in to change notification settings - Fork 2
/
api_test.go
624 lines (533 loc) · 18.1 KB
/
api_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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"runtime"
"sync"
"testing"
"time"
"github.com/imup-io/client/speedtesting"
"github.com/matryer/is"
)
// imup.APIPostConnectionData = getEnv("IMUP_ADDRESS", "https://api.imup.io/v1/data/connectivity")
// imup.SpeedTestStatusUpdateAddress = getEnv("IMUP_SPEED_TEST_STATUS_ADDRESS", "https://api.imup.io/v1/realtime/speedTestStatusUpdate")
func TestApi_PostSpeedTestStatus(t *testing.T) {
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Payload interface{}
RetCode int
Type string
}{
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "realtime/speedTestStatusUpdate", Type: "org", RetCode: http.StatusOK, Payload: "running", GroupID: "1234"},
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "realtime/speedTestStatusUpdate", Type: "org", RetCode: http.StatusInternalServerError, Payload: "error"},
{Email: "test@example.com", EndPoint: "realtime/speedTestStatusUpdate", Type: "user", RetCode: http.StatusOK, Payload: "running"},
{Email: "test@example.com", EndPoint: "realtime/speedTestStatusUpdate", Type: "user", RetCode: http.StatusInternalServerError, Payload: "error"},
}
for _, c := range cases {
data := &realtimeApiPayload{
ID: c.HostID, Key: c.ApiKey, Email: c.Email, Data: c.Payload,
}
s := apiTestServer(c.EndPoint, data, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_SPEED_TEST_STATUS_ADDRESS", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
is := is.New(t)
imup := newApp()
wg := sync.WaitGroup{}
wg.Add(1)
var err error
go func() {
defer wg.Done()
err = imup.postSpeedTestRealtimeStatus(context.Background(), data.Data.(string))
}()
wg.Wait()
if c.RetCode >= 500 {
is.True(err != nil)
} else {
is.NoErr(err)
}
}
}
// imup.SpeedTestResultsAddress = getEnv("IMUP_SPEED_TEST_RESULTS_ADDRESS", "https://api.imup.io/v1/realtime/speedTestResults")
func TestApi_PostSpeedTestResults(t *testing.T) {
payload := struct {
u float64
d float64
data string
}{1.001, 1.001, "complete"}
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Payload interface{}
RetCode int
Type string
}{
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "realtime/speedTestResults", Type: "org", RetCode: http.StatusOK, Payload: payload, GroupID: "1234"},
{Email: "test@example.com", EndPoint: "realtime/speedTestResults", Type: "user", RetCode: http.StatusOK, Payload: payload},
}
for _, c := range cases {
data := &realtimeApiPayload{
ID: c.HostID, Key: c.ApiKey, Email: c.Email, Data: c.Payload,
}
s := apiTestServer(c.EndPoint, data, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_SPEED_TEST_RESULTS_ADDRESS", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
is := is.New(t)
imup := newApp()
wg := sync.WaitGroup{}
wg.Add(1)
var err error
go func() {
defer wg.Done()
err = imup.postSpeedTestRealtimeResults(context.Background(), payload.data, &speedtesting.SpeedTestResult{DownloadedBytes: payload.d, UploadedBytes: payload.u})
}()
wg.Wait()
is.NoErr(err)
}
}
// imup.ShouldRunSpeedTestAddress = getEnv("IMUP_SHOULD_RUN_SPEEDTEST_ADDRESS", "https://api.imup.io/v1/realtime/shouldClientRunSpeedTest")
func TestApi_PostShouldClientRunSpeedTest(t *testing.T) {
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Payload interface{}
RetCode int
Type string
}{
// TODO: need to pass in an extra param to test failure cases here
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "realtime/shouldClientRunSpeedTest", Type: "org", RetCode: http.StatusOK, GroupID: "1234"},
{Email: "test@example.com", EndPoint: "realtime/shouldClientRunSpeedTest", Type: "user", RetCode: http.StatusOK},
}
for _, c := range cases {
senddata := &realtimeApiPayload{ID: c.HostID, Key: c.ApiKey, Email: c.Email}
s := apiTestServer(c.EndPoint, senddata, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_SHOULD_RUN_SPEEDTEST_ADDRESS", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
is := is.New(t)
imup := newApp()
wg := sync.WaitGroup{}
wg.Add(1)
var ok bool
var err error
go func() {
defer wg.Done()
ok, err = imup.shouldRunSpeedtest(context.Background())
}()
wg.Wait()
is.NoErr(err)
is.True(ok)
}
}
// imup.LivenessCheckInAddress = getEnv("IMUP_LIVENESS_CHECKIN_ADDRESS", "https://api.imup.io/v1/realtime/livenesscheckin")
func TestApi_PostLivenesscheckin(t *testing.T) {
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Payload interface{}
RetCode int
Type string
}{
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "realtime/livenesscheckin", Type: "org", RetCode: http.StatusOK, Payload: "", GroupID: "1234"},
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "realtime/livenesscheckin", Type: "org", RetCode: http.StatusInternalServerError, Payload: ""},
{ApiKey: "1234", HostID: "homer", EndPoint: "realtime/livenesscheckin", Type: "org", RetCode: http.StatusOK, Payload: "running"},
{Email: "test@example.com", EndPoint: "realtime/livenesscheckin", Type: "user", RetCode: http.StatusOK, Payload: ""},
{Email: "test@example.com", EndPoint: "realtime/livenesscheckin", Type: "user", RetCode: http.StatusInternalServerError, Payload: ""},
}
for _, c := range cases {
c.Payload = &realtimeApiPayload{ID: c.HostID, Key: c.ApiKey, Email: c.Email}
s := apiTestServer(c.EndPoint, c.Payload, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_LIVENESS_CHECKIN_ADDRESS", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
is := is.New(t)
imup := newApp()
err := imup.sendClientHealthy(context.Background())
if c.RetCode > 499 {
is.True(err != nil)
} else {
is.NoErr(err)
}
}
}
// imup.APIPostSpeedTestData = getEnv("IMUP_ADDRESS_SPEEDTEST", "https://api.imup.io/v1/data/speedtest")
func TestApi_PostSpeedTestData(t *testing.T) {
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Payload interface{}
RetCode int
Type string
}{
// Testing failure cases are tricky since we retry this endpoint forever.
// TODO: Make retries configurable for tests.
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "data/speedtest", Type: "org", RetCode: http.StatusOK, GroupID: "asdf12345"},
{Email: "test@example.com", EndPoint: "data/speedtest", Type: "user", RetCode: http.StatusOK, GroupID: ""},
}
is := is.New(t)
for _, c := range cases {
c.Payload = &imupData{
Email: c.Email,
ID: c.HostID,
Key: c.ApiKey,
GroupID: c.GroupID,
IMUPData: &speedtesting.SpeedTestResult{
DownloadedBytes: 9999999.0,
DownloadMbps: 1.001,
DownloadRetrans: 0.001,
DownloadMinRtt: 0.9,
DownloadRTTVar: 0.01,
UploadedBytes: 10000000.0,
UploadMbps: 0.1001,
UploadRetrans: 1.001,
UploadMinRTT: 1.001,
UploadRTTVar: 1.001,
TimeStampStart: time.Now().Unix(),
TimeStampFinish: time.Now().Unix(),
Metadata: map[string]string{},
ClientVersion: ClientVersion,
OS: runtime.GOOS,
TestServer: "somewhere",
},
}
payload, err := json.Marshal(&c.Payload)
is.NoErr(err)
s := apiTestServer(c.EndPoint, payload, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_ADDRESS_SPEEDTEST", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
imup := newApp()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
sendImupData(context.Background(), sendDataJob{imup.cfg.PostSpeedTestData(), c.Payload})
}()
wg.Wait()
}
}
// imup.APIPostConnectionData = getEnv("IMUP_ADDRESS", "https://api.imup.io/v1/data/connectivity")
func TestApi_PostPingConnectionData(t *testing.T) {
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Payload interface{}
RetCode int
Type string
}{
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "data/connectivity/ping", Type: "org", RetCode: http.StatusOK, GroupID: "1234"},
{Email: "test@example.com", EndPoint: "data/connectivity/ping", Type: "user", RetCode: http.StatusOK},
}
for _, c := range cases {
c.Payload = imupData{
Downtime: 0,
StatusChanged: false,
Email: c.Email,
ID: c.HostID,
Key: c.ApiKey,
IMUPData: []pingStats{},
}
s := apiTestServer(c.EndPoint, c.Payload, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_ADDRESS", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
imup := newApp()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
sendImupData(context.Background(), sendDataJob{imup.cfg.PostConnectionData(), c.Payload})
}()
wg.Wait()
}
}
// imup.APIPostConnectionData = getEnv("IMUP_ADDRESS", "https://api.imup.io/v1/data/connectivity")
func TestApi_PostConnectionData(t *testing.T) {
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Payload interface{}
RetCode int
Type string
}{
{ApiKey: "1234", HostID: "homer", Email: "org-test@example.com", EndPoint: "data/connectivity", Type: "org", RetCode: http.StatusOK, GroupID: "1234"},
{Email: "test@example.com", EndPoint: "data/connectivity", Type: "user", RetCode: http.StatusOK},
}
for _, c := range cases {
c.Payload = imupData{
Downtime: 0,
StatusChanged: false,
Email: c.Email,
ID: c.HostID,
Key: c.ApiKey,
IMUPData: []pingStats{},
}
s := apiTestServer(c.EndPoint, c.Payload, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_ADDRESS", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
imup := newApp()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
sendImupData(context.Background(), sendDataJob{imup.cfg.PostConnectionData(), c.Payload})
}()
wg.Wait()
}
}
// imup.RealtimeConfig = getEnv("IMUP_REALTIME_CONFIG", "https://api.imup.io/v1/realtime/config")
func TestApi_PostConfigReload(t *testing.T) {
cases := []struct {
ApiKey string
Email string
EndPoint string
HostID string
GroupID string
Version string
RetCode int
Type string
}{
{ApiKey: "1234", HostID: "homer", GroupID: "", Version: "dev preview", Email: "org-test@example.com", EndPoint: "realtime/remoteConfigReload", Type: "org", RetCode: http.StatusNoContent},
{ApiKey: "1234", HostID: "homer", GroupID: "uuid", Version: "2023.04.02v1", Email: "org-test1@example.com", EndPoint: "realtime/remoteConfigReload", Type: "org", RetCode: http.StatusOK},
}
for _, c := range cases {
sendData := &realtimeApiPayload{ID: c.HostID, Key: c.ApiKey, Email: c.Email, GroupID: c.GroupID, Version: c.Version}
s := apiTestServer(c.EndPoint, sendData, c.RetCode, t)
defer s.Close()
testURL, _ := url.Parse(s.URL)
os.Setenv("IMUP_REALTIME_CONFIG", testURL.String())
os.Setenv("API_KEY", c.ApiKey)
os.Setenv("EMAIL", c.Email)
os.Setenv("HOST_ID", c.HostID)
os.Setenv("GROUP_ID", c.GroupID)
is := is.New(t)
imup := newApp()
wg := sync.WaitGroup{}
wg.Add(1)
var err error
go func() {
defer wg.Done()
err = imup.remoteConfigReload(context.Background())
}()
wg.Wait()
is.NoErr(err)
if c.RetCode == http.StatusOK {
is.Equal(imup.cfg.Version(), "2023.04.02v2")
} else {
is.Equal(imup.cfg.Version(), "dev-preview")
}
}
}
// loose reflection of imup api endpoints and their expected payloads
func apiTestServer(endpoint string, payload interface{}, retcode int, t *testing.T) *httptest.Server {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(retcode)
if retcode > 499 {
return
}
switch endpoint {
case "data/connectivity":
recvdata := &imupData{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
expected, ok := payload.(imupData)
if !ok {
w.WriteHeader(http.StatusBadRequest)
t.Error("payload is not the expected type")
}
if recvdata.Key != expected.Key {
t.Errorf("Expected: %v, Got: %v", expected.Key, recvdata.Key)
}
case "data/connectivity/ping":
recvdata := &imupData{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
expected, ok := payload.(imupData)
if !ok {
w.WriteHeader(http.StatusBadRequest)
t.Error("payload is not the expected type")
}
if expected.Key != recvdata.Key {
t.Errorf("Expected: %v, Got: %v", expected.Key, recvdata.Key)
}
case "data/speedtest":
type speedtestData struct {
Downtime int `json:"downtime,omitempty"`
StatusChanged bool `json:"statusChanged"`
Email string `json:"email,omitempty"`
ID string `json:"hostId,omitempty"`
Key string `json:"apiKey,omitempty"`
GroupID string `json:"group_id,omitempty"`
IMUPData *speedtesting.SpeedTestResult `json:"data,omitempty"`
}
recvdata := &speedtestData{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
expected := &speedtestData{}
bytes := payload.([]byte)
json.Unmarshal(bytes, &expected)
if recvdata.IMUPData.DownloadMbps != expected.IMUPData.DownloadMbps {
t.Errorf("Expected: %v, Got: %v", expected.IMUPData.DownloadMbps, recvdata.IMUPData.DownloadMbps)
}
if recvdata.IMUPData.DownloadedBytes != expected.IMUPData.DownloadedBytes {
t.Errorf("Expected: %v, Got: %v", expected.IMUPData.DownloadedBytes, recvdata.IMUPData.DownloadedBytes)
}
if recvdata.IMUPData.UploadMbps != expected.IMUPData.UploadMbps {
t.Errorf("Expected: %v, Got: %v", expected.IMUPData.UploadMbps, recvdata.IMUPData.UploadMbps)
}
if recvdata.IMUPData.UploadedBytes != expected.IMUPData.UploadedBytes {
t.Errorf("Expected: %v, Got: %v", expected.IMUPData.UploadedBytes, recvdata.IMUPData.UploadedBytes)
}
case "realtime/livenesscheckin":
recvdata := &realtimeApiPayload{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
m := payload.(*realtimeApiPayload)
if m.Email != recvdata.Email {
t.Errorf("Expected: %v Got: %v", m.Email, recvdata.Email)
}
if m.ID != recvdata.ID {
t.Errorf("Expected: %v Got: %v", m.ID, recvdata.ID)
}
if m.Key != recvdata.Key {
t.Errorf("Expected: %v Got: %v", m.Key, recvdata.Key)
}
// is.Equal(data, payload)
case "realtime/shouldClientRunSpeedTest":
recvdata := &realtimeApiPayload{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
expected, ok := payload.(*realtimeApiPayload)
if !ok {
w.WriteHeader(http.StatusBadRequest)
t.Error("payload is not the expected type")
}
if expected.ID != recvdata.ID {
t.Errorf("Expected: %v Got: %v", expected.ID, recvdata.ID)
}
if expected.Email != recvdata.Email {
t.Errorf("Expected: %v Got: %v", expected.Email, recvdata.Email)
}
if expected.Key != recvdata.Key {
t.Errorf("Expected: %v Got: %v", expected.Key, recvdata.Key)
}
// Api Server Response
w.Header().Set("Content-Type", "application/json")
data := struct {
Success bool `json:"success"`
Data bool `json:"data"`
}{true, true}
if err := json.NewEncoder(w).Encode(data); err != nil {
t.Error(err)
}
case "realtime/speedTestResults":
recvdata := &realtimeApiPayload{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
expected, ok := payload.(*realtimeApiPayload)
if !ok {
w.WriteHeader(http.StatusBadRequest)
t.Error("payload is not the expected type")
}
if expected.ID != recvdata.ID {
t.Errorf("Expected: %v Got: %v", expected.ID, recvdata.ID)
}
if expected.Email != recvdata.Email {
t.Errorf("Expected: %v Got: %v", expected.Email, recvdata.Email)
}
if expected.Key != recvdata.Key {
t.Errorf("Expected: %v Got: %v", expected.Key, recvdata.Key)
}
case "realtime/speedTestStatusUpdate":
recvdata := &realtimeApiPayload{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
apiPayload, ok := payload.(*realtimeApiPayload)
if !ok {
t.Error("payload was not the expected type")
fmt.Fprintf(w, "payload was not the expected type")
}
got := recvdata.Data.(string)
expected := apiPayload.Data.(string)
if got != expected {
t.Errorf("Expected: %v Got: %v", expected, got)
}
case "realtime/remoteConfigReload":
if retcode == http.StatusNoContent {
w.WriteHeader(http.StatusNoContent)
return
}
recvdata := &realtimeApiPayload{}
if err := json.NewDecoder(r.Body).Decode(recvdata); err != nil {
t.Error(err)
}
// Api Server Response
w.Header().Set("Content-Type", "application/json")
data := `{"config": {"version": "2023.04.02v2","verbosity": "debug","fileLogger":true,"group_id": "new-group-id","insecureSpeedTest": false,"noDiscoverGateway": false,"nonvolatile": false,"pingEnabled": false,"realtimeEnabled": false,"speedTestEnabled": false,"allowlisted_ips": null,"blocklisted_ips": null}}`
if _, err := fmt.Fprint(w, data); err != nil {
t.Error(err)
}
default:
t.Errorf("unknown endpoint tested against %s", endpoint)
t.Fail()
}
}))
return s
}