package main import ( "bytes" "encoding/json" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "testing" "git.runcible.io/learning/pulley/internal/assert" ) func newTestApplication() application { cfg := config{env: "test"} return application{config: cfg, logger: slog.New(slog.NewTextHandler(io.Discard, nil))} } func TestHealthRoute(t *testing.T) { respRec := httptest.NewRecorder() r, err := http.NewRequest(http.MethodGet, "/v1/healthcheck", nil) if err != nil { t.Fatal(err) } app := newTestApplication() app.routes().ServeHTTP(respRec, r) resp := respRec.Result() if resp.StatusCode != http.StatusOK { t.Fatalf("Got status code %q, wanted status code %q", resp.StatusCode, http.StatusOK) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) assert.NilError(t, err) jsonContent := make(map[string]string) json.Unmarshal(body, &jsonContent) assert.Equal(t, jsonContent["environment"], "test") } func TestCreateMovieHandler(t *testing.T) { respRec := httptest.NewRecorder() want := "Resource created" r, err := http.NewRequest(http.MethodPost, "/v1/movies", nil) if err != nil { t.Fatal(err) } app := newTestApplication() app.routes().ServeHTTP(respRec, r) resp := respRec.Result() if resp.StatusCode != http.StatusAccepted { t.Fatalf("Got status code %q, wanted status code %q", resp.StatusCode, http.StatusOK) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) assert.NilError(t, err) body = bytes.TrimSpace(body) assert.StringContains(t, string(body), want) } func TestGetAllMoviesHandler(t *testing.T) { testTable := []struct { name string id string wantCode int useID bool }{ { name: "Get Movie By ID", id: "1337", wantCode: 200, }, { name: "No ID provided", id: "", wantCode: 404, }, { name: "Negative ID", id: "-1", wantCode: 404, }, } for _, test := range testTable { t.Run(test.name, func(t *testing.T) { respRec := httptest.NewRecorder() r, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/movies/%s", test.id), nil) t.Logf("Path: %s, Method: %s", r.URL.Path, r.Method) assert.NilError(t, err) app := newTestApplication() // want to test with httprouter since we use it to parse context app.routes().ServeHTTP(respRec, r) resp := respRec.Result() t.Logf("Code: %d", resp.StatusCode) assert.Equal(t, resp.StatusCode, test.wantCode) }) } }