package api import ( "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) // #105: every validation path on create returns a machine-readable `code` // alongside the human `error` message, so the new-page JS can map known // codes to plain-language guidance. func decodeErr(t *testing.T, rec *httptest.ResponseRecorder) (status int, errMsg, code string) { t.Helper() var got struct { Error string `json:"error"` Code string `json:"code"` } if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("bad json: %v (%s)", err, rec.Body.String()) } return rec.Code, got.Error, got.Code } func postCreate(h http.Handler, body string) *httptest.ResponseRecorder { req := httptest.NewRequest("POST", "/api/pastes", strings.NewReader(body)) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } func TestErrorCodeContentEmpty(t *testing.T) { h := testServer(t).routes() _, _, code := decodeErr(t, postCreate(h, `{"content":" "}`)) if code != "content_empty" { t.Fatalf("code = %q, want content_empty", code) } } func TestErrorCodeContentTooLarge(t *testing.T) { h := testServer(t).routes() big := strings.Repeat("x", 6*1024*1024) // over the 5MB test cap _, _, code := decodeErr(t, postCreate(h, `{"content":"`+big+`"}`)) if code != "content_too_large" { t.Fatalf("code = %q, want content_too_large", code) } } func TestErrorCodeSlugTaken(t *testing.T) { h := testServer(t).routes() if rec := postCreate(h, `{"content":"a","custom_slug":"taken-slug"}`); rec.Code != 201 { t.Fatalf("seed create: %d %s", rec.Code, rec.Body.String()) } _, _, code := decodeErr(t, postCreate(h, `{"content":"b","custom_slug":"taken-slug"}`)) if code != "slug_taken" { t.Fatalf("code = %q, want slug_taken", code) } } func TestErrorCodeSlugInvalid(t *testing.T) { h := testServer(t).routes() _, _, code := decodeErr(t, postCreate(h, `{"content":"a","custom_slug":"bad slug!"}`)) if code != "slug_invalid" { t.Fatalf("code = %q, want slug_invalid", code) } } func TestErrorCodeExpiryInvalid(t *testing.T) { h := testServer(t).routes() _, _, code := decodeErr(t, postCreate(h, `{"content":"a","expires_in":"2s"}`)) if code != "expiry_invalid" { t.Fatalf("code = %q, want expiry_invalid", code) } } func TestErrorCodeRateLimited(t *testing.T) { h := testServer(t).routes() var code string for i := 0; i < 20; i++ { _, _, code = decodeErr(t, postCreate(h, `{"content":"a"}`)) if code == "rate_limited" { return } } t.Fatalf("never got rate_limited, last code = %q", code) }