Repository navigation
Expand file tree
/
Copy pathclient_test.go
More file actions
80 lines (66 loc) · 1.95 KB
/
Copy pathclient_test.go
File metadata and controls
80 lines (66 loc) · 1.95 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
package client
import (
"net/http"
"net/http/httptest"
"testing"
)
func newTestClient(t *testing.T, handler http.HandlerFunc) (*Client, *httptest.Server) {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
return NewWithBaseURL("test-api-key", srv.URL), srv
}
func TestDo_SendsAPIKeyHeader(t *testing.T) {
var gotKey string
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
gotKey = r.Header.Get("X-API-KEY")
w.Write([]byte(`{}`))
})
c.get("/test")
if gotKey != "test-api-key" {
t.Errorf("expected X-API-KEY = %q, got %q", "test-api-key", gotKey)
}
}
func TestDo_ReturnsErrorOn4xx(t *testing.T) {
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"message":"unauthorized"}`))
})
_, err := c.get("/test")
if err == nil {
t.Fatal("expected error for 401 response, got nil")
}
}
func TestDo_ReturnsErrorOn5xx(t *testing.T) {
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"message":"internal server error"}`))
})
_, err := c.get("/test")
if err == nil {
t.Fatal("expected error for 500 response, got nil")
}
}
func TestDo_ReturnsBodyOn2xx(t *testing.T) {
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"ok":true}`))
})
body, err := c.get("/test")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(body) != `{"ok":true}` {
t.Errorf("unexpected body: %s", body)
}
}
func TestPost_SetsContentTypeHeader(t *testing.T) {
var gotContentType string
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
gotContentType = r.Header.Get("Content-Type")
w.Write([]byte(`{}`))
})
c.post("/test", map[string]string{"key": "value"})
if gotContentType != "application/json" {
t.Errorf("expected Content-Type = application/json, got %q", gotContentType)
}
}