You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.3 KiB
Go

package main
import (
"bytes"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
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()
health := http.HandlerFunc(app.healthCheckHandler)
health.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)
if err != nil {
t.Fatal(err)
}
body = bytes.TrimSpace(body)
if !strings.Contains(string(body), "environment: test") {
t.Fatalf("Did not find: %q in response body", "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()
movie := http.HandlerFunc(app.createMovieHandler)
movie.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)
if err != nil {
t.Fatal(err)
}
body = bytes.TrimSpace(body)
if !strings.Contains(string(body), want) {
t.Fatalf("Did not find: %q in response body", want)
}
}
func TestGetAllMoviesHandler(t *testing.T) {
respRec := httptest.NewRecorder()
want := "Movies List"
r, err := http.NewRequest(http.MethodGet, "/v1/movies", nil)
if err != nil {
t.Fatal(err)
}
app := newTestApplication()
movie := http.HandlerFunc(app.getAllMoviesHandler)
movie.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)
if err != nil {
t.Fatal(err)
}
body = bytes.TrimSpace(body)
if !strings.Contains(string(body), want) {
t.Fatalf("Did not find: %q in response body", want)
}
}