-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
91 lines (81 loc) · 2.28 KB
/
main_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
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
)
type mockDB struct {
aggregateFeeByHour func() ([]AggregatedFee, error)
}
func (m mockDB) AggregateFeeByHour() ([]AggregatedFee, error) {
return m.aggregateFeeByHour()
}
func TestHandler(t *testing.T) {
successExample := []AggregatedFee{
{time.Now().Unix(), 10.5},
{time.Now().Unix(), 9.3},
}
successB, err := json.MarshalIndent(&successExample, "", " ")
if err != nil {
t.Fatal("error initializing testdata", err)
}
successStr := string(successB) + "\n"
tt := []struct {
description string
httpMethod string
expectedStatus int
expectedResponse string
aggregateFunc func() ([]AggregatedFee, error)
}{
{
description: "should return method not allowed for method not GET",
httpMethod: http.MethodPost,
expectedStatus: http.StatusMethodNotAllowed,
expectedResponse: "Invalid HTTP Method, only HTTP GET is allowed\n",
},
{
description: "should return internal server error for db err",
httpMethod: http.MethodGet,
expectedStatus: http.StatusInternalServerError,
expectedResponse: "Error communicating with datasource\n",
aggregateFunc: func() ([]AggregatedFee, error) {
return []AggregatedFee{}, errors.New("db error")
},
},
{
description: "should return OK and data",
httpMethod: http.MethodGet,
expectedStatus: http.StatusOK,
expectedResponse: successStr,
aggregateFunc: func() ([]AggregatedFee, error) {
return successExample, nil
},
},
}
for _, tc := range tt {
t.Run(tc.description, func(t *testing.T) {
req, err := http.NewRequest(tc.httpMethod, "", nil)
if err != nil {
t.Fatal("error building request", err)
}
db := mockDB{tc.aggregateFunc}
rr := httptest.NewRecorder()
h := handler{db}
h.ServeHTTP(rr, req)
if rr.Result().StatusCode != tc.expectedStatus {
t.Fatalf("wrong status code, want: %v, got: %v", tc.expectedStatus, rr.Result().StatusCode)
}
gotData, err := ioutil.ReadAll(rr.Body)
if err != nil {
t.Fatal("error reading response", err)
}
if string(gotData) != tc.expectedResponse {
t.Fatalf("wrong response body\nwant: %v\ngot: %v", tc.expectedResponse, string(gotData))
}
})
}
}