forked from quii/learn-go-with-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
99 lines (85 loc) · 2.14 KB
/
server_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
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
type StubPlayerStore struct {
scores map[string]int
}
func (s *StubPlayerStore) GetPlayerScore(name string) int {
score := s.scores[name]
return score
}
func TestGETPlayers(t *testing.T) {
store := StubPlayerStore{
map[string]int{
"Pepper": 20,
"Floyd": 10,
},
}
server := &PlayerServer{&store}
tests := []struct {
name string
player string
expectedHTTPStatus int
expectedScore string
}{
{
name: "Returns Pepper's score",
player: "Pepper",
expectedHTTPStatus: http.StatusOK,
expectedScore: "20",
},
{
name: "Returns Floyd's score",
player: "Floyd",
expectedHTTPStatus: http.StatusOK,
expectedScore: "10",
},
{
name: "Returns 404 on missing players",
player: "Apollo",
expectedHTTPStatus: http.StatusNotFound,
expectedScore: "0",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := newGetScoreRequest(tt.player)
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
assertStatus(t, response.Code, tt.expectedHTTPStatus)
assertResponseBody(t, response.Body.String(), tt.expectedScore)
})
}
}
func TestStoreWins(t *testing.T) {
store := StubPlayerStore{
map[string]int{},
}
server := &PlayerServer{&store}
t.Run("it returns accepted on POST", func(t *testing.T) {
request, _ := http.NewRequest(http.MethodPost, "/players/Pepper", nil)
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
assertStatus(t, response.Code, http.StatusAccepted)
})
}
func assertStatus(t testing.TB, got, want int) {
t.Helper()
if got != want {
t.Errorf("did not get correct status, got %d, want %d", got, want)
}
}
func newGetScoreRequest(name string) *http.Request {
req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("/players/%s", name), nil)
return req
}
func assertResponseBody(t testing.TB, got, want string) {
t.Helper()
if got != want {
t.Errorf("response body is wrong, got %q want %q", got, want)
}
}