-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_key_test.go
More file actions
89 lines (82 loc) · 2.23 KB
/
api_key_test.go
File metadata and controls
89 lines (82 loc) · 2.23 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
package loops
import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestGetAPIKey(t *testing.T) {
tests := []struct {
name string
statusCode int
body string
wantAPIErr *APIError
wantErrMsg string
wantTeam string
}{
{
name: "success",
statusCode: http.StatusOK,
body: `{"teamName":"Acme"}`,
wantTeam: "Acme",
},
{
name: "unauthorized",
statusCode: http.StatusUnauthorized,
body: `{"success":false,"error":"Invalid API key"}`,
wantAPIErr: &APIError{StatusCode: http.StatusUnauthorized, Message: "Invalid API key"},
},
{
name: "unexpected status",
statusCode: http.StatusInternalServerError,
body: ``,
wantAPIErr: &APIError{StatusCode: http.StatusInternalServerError},
},
{
name: "invalid json",
statusCode: http.StatusOK,
body: `not json`,
wantErrMsg: "failed to decode response",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.statusCode)
w.Write([]byte(tt.body))
}))
defer server.Close()
client := NewClient("test-key", WithBaseURL(server.URL))
result, err := client.GetAPIKey()
if tt.wantAPIErr != nil {
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("expected *APIError, got %T: %v", err, err)
}
if apiErr.StatusCode != tt.wantAPIErr.StatusCode {
t.Errorf("StatusCode = %d, want %d", apiErr.StatusCode, tt.wantAPIErr.StatusCode)
}
if tt.wantAPIErr.Message != "" && apiErr.Message != tt.wantAPIErr.Message {
t.Errorf("Message = %q, want %q", apiErr.Message, tt.wantAPIErr.Message)
}
return
}
if tt.wantErrMsg != "" {
if err == nil {
t.Fatalf("expected error containing %q, got nil", tt.wantErrMsg)
}
if !strings.Contains(err.Error(), tt.wantErrMsg) {
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErrMsg)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.TeamName != tt.wantTeam {
t.Errorf("TeamName = %q, want %q", result.TeamName, tt.wantTeam)
}
})
}
}