package web import ( "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "strings" "testing" "expenses/internal/expense" "expenses/internal/store" ) // memoryStore keeps expenses in a slice. It has the methods of Store, so the // tests need no file. It is used by one test at a time, so it needs no mutex. type memoryStore struct { nextID int expenses []expense.Expense } func (m *memoryStore) List() []expense.Expense { return append([]expense.Expense{}, m.expenses...) } func (m *memoryStore) Get(id int) (expense.Expense, error) { for _, e := range m.expenses { if e.ID == id { return e, nil } } return expense.Expense{}, store.ErrNotFound } func (m *memoryStore) Add(e expense.Expense) (expense.Expense, error) { m.nextID = m.nextID + 1 e.ID = m.nextID m.expenses = append(m.expenses, e) return e, nil } func (m *memoryStore) Delete(id int) error { for i, e := range m.expenses { if e.ID == id { m.expenses = append(m.expenses[:i], m.expenses[i+1:]...) return nil } } return store.ErrNotFound } // newTestApp returns the routes of an App with an empty memory store, and a // logger that throws its lines away. func newTestApp(t *testing.T) (http.Handler, *memoryStore) { t.Helper() memory := &memoryStore{} logger := slog.New(slog.NewTextHandler(io.Discard, nil)) app, err := New(memory, logger, "test") if err != nil { t.Fatalf("New gave error %v", err) } return app.Handler(), memory } // send runs one request through the 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 TestCreateAndGet(t *testing.T) { handler, _ := newTestApp(t) body := `{"date":"2026-11-03","category":"Food","note":"lunch","cents":1250}` response := send(handler, "POST", "/api/expenses", body) if response.Code != http.StatusCreated { t.Fatalf("POST gave status %d, want 201. Body: %s", response.Code, response.Body) } if response.Header().Get("Location") != "/api/expenses/1" { t.Errorf("Location is %q, want /api/expenses/1", response.Header().Get("Location")) } if !strings.HasPrefix(response.Header().Get("Content-Type"), "application/json") { t.Errorf("Content-Type is %q", response.Header().Get("Content-Type")) } var added expense.Expense err := json.NewDecoder(response.Body).Decode(&added) if err != nil { t.Fatalf("the reply is not JSON: %v", err) } want := expense.Expense{ID: 1, Date: "2026-11-03", Category: "food", Note: "lunch", Cents: 1250} if added != want { t.Errorf("POST returned %+v, want %+v", added, want) } response = send(handler, "GET", "/api/expenses/1", "") if response.Code != http.StatusOK { t.Errorf("GET gave status %d, want 200", response.Code) } } func TestCreateBadInput(t *testing.T) { tests := []struct { name string body string want int }{ {"not JSON", `hello`, http.StatusBadRequest}, {"unknown field", `{"date":"2026-11-03","category":"food","cents":1250,"price":3}`, http.StatusBadRequest}, {"two objects", `{"date":"2026-11-03","category":"food","cents":1250}{}`, http.StatusBadRequest}, {"bad date", `{"date":"yesterday","category":"food","cents":1250}`, http.StatusBadRequest}, {"no amount", `{"date":"2026-11-03","category":"food"}`, http.StatusBadRequest}, {"too big", `{"note":"` + strings.Repeat("x", maxBodyBytes) + `"}`, http.StatusRequestEntityTooLarge}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { handler, memory := newTestApp(t) response := send(handler, "POST", "/api/expenses", tt.body) if response.Code != tt.want { t.Errorf("status %d, want %d", response.Code, tt.want) } if !strings.Contains(response.Body.String(), `"error"`) { t.Errorf("the body has no error field: %s", response.Body) } if len(memory.expenses) != 0 { t.Errorf("a bad request was saved") } }) } } func TestNotFoundAndDelete(t *testing.T) { handler, memory := newTestApp(t) memory.Add(expense.Expense{Date: "2026-11-03", Category: "food", Cents: 1250}) tests := []struct { method string target string want int }{ {"GET", "/api/expenses/99", http.StatusNotFound}, {"GET", "/api/expenses/abc", http.StatusBadRequest}, {"DELETE", "/api/expenses/1", http.StatusNoContent}, {"DELETE", "/api/expenses/1", http.StatusNotFound}, {"GET", "/api/expenses/1", http.StatusNotFound}, {"PUT", "/api/expenses/1", http.StatusMethodNotAllowed}, } for _, tt := range tests { response := send(handler, tt.method, tt.target, "") if response.Code != tt.want { t.Errorf("%s %s gave status %d, want %d", tt.method, tt.target, response.Code, tt.want) } } } func TestListAndReportByMonth(t *testing.T) { handler, memory := newTestApp(t) memory.Add(expense.Expense{Date: "2026-10-30", Category: "food", Cents: 800}) memory.Add(expense.Expense{Date: "2026-11-03", Category: "food", Cents: 1250}) memory.Add(expense.Expense{Date: "2026-11-04", Category: "transport", Cents: 500}) response := send(handler, "GET", "/api/expenses?month=2026-11", "") var list []expense.Expense err := json.NewDecoder(response.Body).Decode(&list) if err != nil { t.Fatal(err) } if len(list) != 2 { t.Errorf("the list for 2026-11 has %d expenses, want 2", len(list)) } response = send(handler, "GET", "/api/report?month=2026-11", "") var report expense.Report err = json.NewDecoder(response.Body).Decode(&report) if err != nil { t.Fatal(err) } if report.TotalCents != 1750 || report.Count != 2 { t.Errorf("the report is %+v, want a total of 1750 from 2 expenses", report) } response = send(handler, "GET", "/api/report?month=november", "") if response.Code != http.StatusBadRequest { t.Errorf("a bad month gave status %d, want 400", response.Code) } } func TestForm(t *testing.T) { handler, memory := newTestApp(t) good := url.Values{"date": {"2026-11-03"}, "category": {"food"}, "amount": {"12.50"}, "note": {"lunch"}} request := httptest.NewRequest("POST", "/expenses", strings.NewReader(good.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() handler.ServeHTTP(response, request) if response.Code != http.StatusSeeOther { t.Fatalf("a good form gave status %d, want 303", response.Code) } if len(memory.expenses) != 1 || memory.expenses[0].Cents != 1250 { t.Errorf("the store has %+v, want one expense of 1250 cents", memory.expenses) } bad := url.Values{"date": {"2026-11-03"}, "category": {"food"}, "amount": {"lots"}} request = httptest.NewRequest("POST", "/expenses", strings.NewReader(bad.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response = httptest.NewRecorder() handler.ServeHTTP(response, request) if response.Code != http.StatusBadRequest { t.Errorf("a bad form gave status %d, want 400", response.Code) } page := response.Body.String() if !strings.Contains(page, `class="error"`) { t.Errorf("the page shows no error") } if !strings.Contains(page, `value="<b>food</b>"`) { t.Errorf("the typed category is not shown again, escaped") } response = send(handler, "GET", "/", "") if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "lunch") { t.Errorf("the home page does not show the expense") } }