package handlers import ( "encoding/json" "log/slog" "net/http" "testing" "go.uber.org/fx/fxtest" "sneak.berlin/go/pixa/internal/config" "sneak.berlin/go/pixa/internal/globals" "sneak.berlin/go/pixa/internal/healthcheck" "sneak.berlin/go/pixa/internal/logger" ) // TestHandleRobotsTxt checks that /robots.txt asks every crawler to stay off // the whole site. func TestHandleRobotsTxt(t *testing.T) { t.Parallel() h := &Handlers{log: slog.New(slog.DiscardHandler)} rec := sendGet(t, h.HandleRobotsTxt(), "/robots.txt") if rec.Code != http.StatusOK { t.Errorf("status = %d, want %d", rec.Code, http.StatusOK) } if ct := rec.Header().Get("Content-Type"); ct != "text/plain" { t.Errorf("Content-Type = %q, want text/plain", ct) } want := "User-agent: *\nDisallow: /\n" if rec.Body.String() != want { t.Errorf("body = %q, want %q", rec.Body.String(), want) } } // TestHandleHealthCheck checks that the health check answers 200 with status // ok, the app's name and version, now, uptime_seconds, uptime_human and // maintenance_mode, which is true here: the health check stays 200 while // maintenance mode is on. func TestHandleHealthCheck(t *testing.T) { t.Parallel() lc := fxtest.NewLifecycle(t) log, err := logger.New(lc, logger.Params{Globals: &globals.Globals{}}) if err != nil { t.Fatalf("logger.New() error = %v", err) } hc, err := healthcheck.New(lc, healthcheck.Params{ Globals: &globals.Globals{Appname: "pixad", Version: "v1.2.3"}, Config: &config.Config{MaintenanceMode: true}, Logger: log, }) if err != nil { t.Fatalf("healthcheck.New() error = %v", err) } h := &Handlers{hc: hc, log: slog.New(slog.DiscardHandler)} rec := sendGet(t, h.HandleHealthCheck(), "/.well-known/healthcheck.json") if rec.Code != http.StatusOK { t.Errorf("status = %d, want %d", rec.Code, http.StatusOK) } if ct := rec.Header().Get("Content-Type"); ct != "application/json" { t.Errorf("Content-Type = %q, want application/json", ct) } var body map[string]any err = json.NewDecoder(rec.Body).Decode(&body) if err != nil { t.Fatalf("decoding response body: %v", err) } if body["status"] != "ok" || body["appname"] != "pixad" || body["version"] != "v1.2.3" || body["maintenance_mode"] != true { t.Errorf("body = %v, want status ok, appname pixad, version v1.2.3 "+ "and maintenance_mode true", body) } for _, key := range []string{"now", "uptime_seconds", "uptime_human"} { if _, ok := body[key]; !ok { t.Errorf("body = %v, has no %s", body, key) } } }