package main import ( "bytes" "context" "io" "log/slog" "net/http/httptest" "path/filepath" "strings" "testing" "expenses/internal/store" "expenses/internal/web" ) // startServer runs the real routes on a test server with a store in a temporary // folder, and returns the address to give to -addr. func startServer(t *testing.T) string { t.Helper() expenses, err := store.Open(filepath.Join(t.TempDir(), "expenses.json")) if err != nil { t.Fatal(err) } logger := slog.New(slog.NewTextHandler(io.Discard, nil)) app, err := web.New(expenses, logger, "test") if err != nil { t.Fatal(err) } server := httptest.NewServer(app.Handler()) t.Cleanup(server.Close) return strings.TrimPrefix(server.URL, "http://") } // runCommand runs one command and returns what it printed. func runCommand(t *testing.T, args ...string) (string, error) { t.Helper() var out bytes.Buffer err := run(context.Background(), args, &out) return out.String(), err } func TestAddListReport(t *testing.T) { addr := startServer(t) steps := [][]string{ {"add", "-addr", addr, "-date", "2026-11-03", "-category", "food", "-note", "lunch", "12.50"}, {"add", "-addr", addr, "-date", "2026-11-04", "-category", "transport", "5"}, {"add", "-addr", addr, "-date", "2026-10-30", "-category", "food", "8"}, } for _, args := range steps { _, err := runCommand(t, args...) if err != nil { t.Fatalf("%v gave error %v", args, err) } } out, err := runCommand(t, "list", "-addr", addr, "-month", "2026-11") if err != nil { t.Fatal(err) } if !strings.Contains(out, "lunch") || strings.Contains(out, "2026-10-30") { t.Errorf("list -month 2026-11 printed:\n%s", out) } out, err = runCommand(t, "report", "-addr", addr) if err != nil { t.Fatal(err) } for _, want := range []string{"3 expenses in total", "food", "20.50", "Total", "25.50"} { if !strings.Contains(out, want) { t.Errorf("report does not contain %q:\n%s", want, out) } } } func TestErrors(t *testing.T) { addr := startServer(t) tests := [][]string{ {}, {"fly"}, {"add", "-addr", addr, "-category", "food"}, {"add", "-addr", addr, "-category", "food", "lots"}, {"add", "-addr", addr, "-category", "", "5"}, {"list", "-addr", addr, "-month", "november"}, {"delete", "-addr", addr, "99"}, {"delete", "-addr", addr, "abc"}, } for _, args := range tests { _, err := runCommand(t, args...) if err == nil { t.Errorf("%v gave no error", args) } } } func TestServerNotRunning(t *testing.T) { // Start a server and stop it, so that nothing listens on its address. server := httptest.NewServer(nil) addr := strings.TrimPrefix(server.URL, "http://") server.Close() _, err := runCommand(t, "list", "-addr", addr) if err == nil || !strings.Contains(err.Error(), "could not reach the server") { t.Errorf("got error %v, want one that says the server could not be reached", err) } }