diff --git a/internal/handlers/handlers_internal_test.go b/internal/handlers/handlers_internal_test.go index bfcb01a..1ee7fc4 100644 --- a/internal/handlers/handlers_internal_test.go +++ b/internal/handlers/handlers_internal_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "database/sql" + "encoding/json" "image" "image/color" "image/jpeg" @@ -291,3 +292,54 @@ func TestHandleImage_InvalidFitMode_Returns400(t *testing.T) { t.Fatalf("status = %d, want %d", status, http.StatusBadRequest) } } + +// TestHandleImage_InvalidQuality_Returns400 verifies that the plain image +// route answers a q that is not a whole number from 1 to 100 with 400 naming +// q and the value, instead of serving the image at the default quality 85. +func TestHandleImage_InvalidQuality_Returns400(t *testing.T) { + t.Parallel() + + tests := []struct { + q, wantError string + }{ + {"banana", `invalid q: not a number, got "banana"`}, + {"0", `invalid q: must be from 1 to 100, got "0"`}, + {"101", `invalid q: must be from 1 to 100, got "101"`}, + } + + for _, tt := range tests { + t.Run("q="+tt.q, func(t *testing.T) { + t.Parallel() + + fix := setupTestHandler(t) + + r := chi.NewRouter() + r.Get("/v1/image/*", fix.handler.HandleImage()) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, + "/v1/image/"+fix.goodHost+"/images/photo.jpg/50x50.jpeg?q="+tt.q, nil) + rec := httptest.NewRecorder() + + r.ServeHTTP(rec, req) + + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest) + } + + t.Logf("GET %s: %d %s", req.URL, rec.Code, rec.Body) + + var body struct { + Error string `json:"error"` + } + + err := json.NewDecoder(rec.Body).Decode(&body) + if err != nil { + t.Fatalf("decoding response body: %v", err) + } + + if body.Error != tt.wantError { + t.Errorf("error = %q, want %q", body.Error, tt.wantError) + } + }) + } +}