-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpclient_test.go
79 lines (72 loc) · 1.68 KB
/
httpclient_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
// SPDX-FileCopyrightText: 2023 Winni Neessen <wn@neessen.dev>
//
// SPDX-License-Identifier: MIT
package meteologix
import (
"context"
"encoding/json"
"errors"
"fmt"
"testing"
)
// BaseURL is the HTTP Status test base URL
const BaseURL = "https://httpstat.us"
// HTTPStatus is the HTTP Status response type
type HTTPStatus struct {
Code int `json:"code"`
Description string `json:"description"`
}
func TestNewHTTPClient(t *testing.T) {
c := New()
hc := NewHTTPClient(c.config)
if hc == nil {
t.Errorf("NewHTTPClient failed, expected HTTPClieht, got nil")
}
}
func TestHTTPClient_Get(t *testing.T) {
tt := []struct {
// Test name
n string
// Status
s int
// Expected message
em string
// Should fail
sf bool
}{
{"HTTP 200", 200, "OK", false},
{"HTTP 400", 400, "Bad Request", true},
{"HTTP 500", 500, "Internal Server Error", true},
}
c := New()
hc := NewHTTPClient(c.config)
for _, tc := range tt {
t.Run(tc.n, func(t *testing.T) {
u := fmt.Sprintf("%s/%d", BaseURL, tc.s)
r, err := hc.Get(u)
if err != nil && !tc.sf {
if errors.Is(err, context.DeadlineExceeded) {
t.Skipf("HTTP timed out, website probably not reachable")
}
t.Errorf("HTTPClient Get request failed: %s", err)
return
}
if tc.sf {
return
}
var ro HTTPStatus
if err := json.Unmarshal(r, &ro); err != nil && !tc.sf {
t.Errorf("HTTP response unmarshal failed: %s", err)
return
}
if ro.Code != tc.s {
t.Errorf("HTTPClient Get failed, expected code: %d, got: %d",
tc.s, ro.Code)
}
if ro.Description != tc.em {
t.Errorf("HTTPClient Get failed, expected message: %s, got: %s",
tc.em, ro.Description)
}
})
}
}