-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
111 lines (87 loc) · 2.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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package pirateweather
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"reflect"
"testing"
)
func TestParseFullForecastResponse(t *testing.T) {
forecast(t, "testdata/sanitized_full_weather.json")
}
func TestParseExcludedForecastResponse(t *testing.T) {
forecast(t, "testdata/sanitized_all_excluded.json")
}
func TestErrorResponse(t *testing.T) {
client := Client{}
server, expected, err := getMockServerWithFileData("testdata/error.json", http.StatusNotFound)
if err != nil {
t.Error(err.Error())
}
defer server.Close()
BaseUrl = server.URL
_, err = client.Forecast(context.TODO(), "", ForecastRequest{})
if err == nil {
t.Errorf("expected request to error")
return
}
restError, ok := err.(*RestError)
if !ok {
t.Errorf("expected error to be of type %s", reflect.TypeOf(RestError{}))
return
}
actual, err := json.Marshal(restError.ErrorResponse)
if err != nil {
t.Errorf(err.Error())
}
assertJsonEqual(t, expected, actual)
}
func forecast(t *testing.T, filename string) {
client := Client{}
server, expected, err := getMockServerWithFileData(filename, http.StatusOK)
if err != nil {
t.Error(err.Error())
}
defer server.Close()
BaseUrl = server.URL
response, err := client.Forecast(context.TODO(), "", ForecastRequest{})
if err != nil {
t.Error(err.Error())
}
actual, err := json.Marshal(response)
if err != nil {
t.Errorf(err.Error())
}
assertJsonEqual(t, expected, actual)
}
func assertJsonEqual(t *testing.T, expected []byte, actual []byte) {
var a, b interface{}
err := json.Unmarshal(expected, &a)
if err != nil {
t.Error(err.Error())
}
err = json.Unmarshal(actual, &b)
if err != nil {
t.Error(err.Error())
}
if !reflect.DeepEqual(a, b) {
t.Errorf("\nexpected: %+v\nactual: %+v", a, b)
}
}
func getMockServerWithFileData(filename string, statusCode int) (*httptest.Server, []byte, error) {
bytes, err := os.ReadFile(filename)
if err != nil {
return nil, bytes, err
}
return getMockServer(bytes, statusCode), bytes, nil
}
func getMockServer(data []byte, statusCode int) *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(statusCode)
fmt.Fprintln(w, string(data))
}))
return server
}