testhub/main_test.go

83 lines
1.5 KiB
Go
Raw Normal View History

2022-05-25 12:04:53 +02:00
package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/remogatto/prettytest"
)
// Start of setup
type testSuite struct {
prettytest.Suite
}
type StubPlayerStore struct {
scores map[string]int
winCalls []string
}
func (store *StubPlayerStore) GetPlayerScore(player string) int {
return store.scores[player]
}
func (s *StubPlayerStore) RecordWin(name string) {
s.winCalls = append(s.winCalls, name)
}
func TestRunner(t *testing.T) {
prettytest.Run(
t,
new(testSuite),
)
}
func (t *testSuite) TestGET() {
tests := []struct {
name string
expectedScore string
expectedHTTPStatus int
}{
{"Pepper", "20", http.StatusOK},
{"Floyd", "10", http.StatusOK},
{"Apollo", "0", http.StatusNotFound},
}
store := &StubPlayerStore{
map[string]int{
"Pepper": 20,
"Floyd": 10,
},
nil,
}
server := &PlayerServer{store}
for _, test := range tests {
request, _ := http.NewRequest(http.MethodGet, "/players/"+test.name, nil)
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
t.Equal(test.expectedScore, response.Body.String())
t.Equal(test.expectedHTTPStatus, response.Code)
}
}
func (t *testSuite) TestPOST() {
store := StubPlayerStore{
map[string]int{},
nil,
}
server := &PlayerServer{&store}
request, _ := http.NewRequest(http.MethodPost, "/players/Pepper", nil)
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
t.Equal(1, len(store.winCalls))
t.Equal(http.StatusAccepted, response.Code)
}