-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient_test.go
53 lines (47 loc) · 1.24 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
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestFetch(t *testing.T) {
tests := map[string]struct {
apiResponse string
expectedError bool
statusCode int
}{
"successful fetch": {
apiResponse: `{"query": {"search": [{"title": "Go"}]}}`,
expectedError: false,
statusCode: http.StatusOK,
},
"bad status code": {
apiResponse: `{"query": {"search": [{"title": "Go"}]}}`,
expectedError: true,
statusCode: http.StatusInternalServerError,
},
"malformed JSON response": {
apiResponse: `{"query": {"search": [`,
expectedError: true,
statusCode: http.StatusOK,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(test.statusCode)
w.Write([]byte(test.apiResponse))
}))
defer ts.Close()
client := &Client{}
var result WikipediaPageQueryJSON
err := client.fetch(&result, ts.URL)
if (err != nil) != test.expectedError {
t.Fatalf("fetch() error = %v, expectedError %v", err, test.expectedError)
}
if !test.expectedError && len(result.Query.Search) == 0 {
t.Fatalf("fetch() result is empty, expected data")
}
})
}
}