package web import ( "errors" "io" "log/slog" "net/http" "net/http/httptest" "slices" "strings" "testing" "scores/internal/score" ) // memoryStore keeps scores in a slice. Each test makes its own, so it needs // no mutex. type memoryStore struct { scores []score.Score } func (m *memoryStore) List() []score.Score { return slices.Clone(m.scores) } func (m *memoryStore) Add(sc score.Score) error { m.scores = append(m.scores, sc) return nil } // failingStore is a store whose Add always fails, like a full disk. type failingStore struct { memoryStore } func (f *failingStore) Add(sc score.Score) error { return errors.New("disk full") } // newTestHandler returns the routes of an App that uses s, with a logger that // throws its lines away. func newTestHandler(s Store) http.Handler { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) return New(s, logger).Handler() } // send runs one request through handler and returns the recorder. func send(handler http.Handler, method string, target string, body string) *httptest.ResponseRecorder { request := httptest.NewRequest(method, target, strings.NewReader(body)) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) return recorder } func TestAddThenList(t *testing.T) { handler := newTestHandler(&memoryStore{}) response := send(handler, "POST", "/api/scores", `{"player": "Keiko", "points": 40}`) if response.Code != http.StatusCreated { t.Fatalf("POST gave status %d, want 201", response.Code) } response = send(handler, "GET", "/api/scores", "") want := `[{"player":"Keiko","points":40}]` if response.Body.String() != want { t.Errorf("GET gave %s, want %s", response.Body, want) } } func TestBadScore(t *testing.T) { memory := &memoryStore{} handler := newTestHandler(memory) response := send(handler, "POST", "/api/scores", `{"player": " ", "points": 40}`) if response.Code != http.StatusBadRequest { t.Errorf("status %d, want 400", response.Code) } if len(memory.scores) != 0 { t.Errorf("a bad score was saved") } } func TestSaveFails(t *testing.T) { handler := newTestHandler(&failingStore{}) response := send(handler, "POST", "/api/scores", `{"player": "Keiko", "points": 40}`) if response.Code != http.StatusInternalServerError { t.Errorf("status %d, want 500", response.Code) } if !strings.Contains(response.Body.String(), "could not be saved") { t.Errorf("the body is %s", response.Body) } }