-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_test.go
66 lines (62 loc) · 1.76 KB
/
client_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
package mistclient
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
)
func TestNewClient(t *testing.T) {
testURL := "https://test.url.com"
testKey := "xxKEYxx"
c := NewClient(&Config{
BaseURL: testURL,
APIKey: testKey,
})
if c.config.BaseURL != testURL {
t.Errorf("NewClient: expected BaseURL: %s, got: %s", testURL, c.config.BaseURL)
}
if c.config.APIKey != testKey {
t.Errorf("NewClient: expected APIKey: %s, got: %s", testKey, c.config.APIKey)
}
if c.client.Timeout != time.Duration(10)*time.Second {
t.Errorf("NewClient: expected Timeout: 10, got: %d", c.client.Timeout)
}
}
func testAPIServer(t *testing.T) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authorized := false
if values, ok := r.Header["Authorization"]; ok {
for _, value := range values {
if value == "Token testAPIKey" {
authorized = true
}
}
}
if !authorized {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("Test API server: missing or invalid authorization token"))
return
}
respDataPath := "testdata" + r.URL.Path
respData, err := os.ReadFile(respDataPath)
if err != nil {
if os.IsNotExist(err) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(fmt.Sprintf("Test API server: response data not found at: %s", respDataPath)))
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Test API server: error reading response data: %s", err)))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(respData)
}))
}