package compat import ( "context" "encoding/json" "log/slog" "net/http" "net/http/httptest" "reflect" "strings" "sync" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/adapter/primary/http/problem" ) const ( defaultPageLimit = 20 fixtureETag = `"v2"` staleETag = `"v1"` ) var fixtureUpdatedAt = time.Date(2026, time.October, 5, 9, 30, 0, 0, time.UTC) // compatibilityHandler implements the fixture operations. CreateProbeItem keeps // a minimal in-memory idempotency record so the test can show that the // generated types express the contract's retry scenario; it is not product // behavior. type compatibilityHandler struct { mu sync.Mutex requests map[string]string responses map[string]*ProbeItemHeaders lastLimit int32 } func newCompatibilityHandler() *compatibilityHandler { return &compatibilityHandler{requests: map[string]string{}, responses: map[string]*ProbeItemHeaders{}} } func (*compatibilityHandler) GetProbe(context.Context, GetProbeParams) (*NullablePayload, error) { return &NullablePayload{}, nil } func (*compatibilityHandler) PurgeProbe(context.Context) error { return nil } func (handler *compatibilityHandler) ListProbeItems(_ context.Context, params ListProbeItemsParams) (*ProbeItemPage, error) { handler.mu.Lock() handler.lastLimit = params.Limit.Or(0) handler.mu.Unlock() return &ProbeItemPage{Items: []ProbeItem{}, Page: PageInfo{HasMore: false, NextCursor: NilString{Null: true}}}, nil } func (handler *compatibilityHandler) CreateProbeItem(_ context.Context, request *ProbeItemInput, params CreateProbeItemParams) (CreateProbeItemRes, error) { handler.mu.Lock() defer handler.mu.Unlock() if fingerprint, seen := handler.requests[params.IdempotencyKey]; seen { if fingerprint != request.Name { reused := CreateProbeItemUnprocessableEntity(fixtureProblem(http.StatusUnprocessableEntity, ProblemCodeIdempotencyKeyReused)) return &reused, nil } return handler.responses[params.IdempotencyKey], nil } response := &ProbeItemHeaders{ ETag: fixtureETag, Response: ProbeItem{ID: uuid.New(), Name: request.Name, UpdatedAt: Timestamp(fixtureUpdatedAt)}, } handler.requests[params.IdempotencyKey] = request.Name handler.responses[params.IdempotencyKey] = response return response, nil } func (*compatibilityHandler) UpdateProbeItem(_ context.Context, request *ProbeItemInput, params UpdateProbeItemParams) (UpdateProbeItemRes, error) { ifMatch, ok := params.IfMatch.Get() if !ok { required := UpdateProbeItemPreconditionRequired(fixtureProblem(http.StatusPreconditionRequired, ProblemCodePreconditionRequired)) return &required, nil } if ifMatch != fixtureETag { conflict := UpdateProbeItemPreconditionFailed(fixtureProblem(http.StatusPreconditionFailed, ProblemCodeVersionConflict)) return &conflict, nil } return &ProbeItemHeaders{ ETag: `"v3"`, Response: ProbeItem{ID: params.ItemID, Name: request.Name, UpdatedAt: Timestamp(fixtureUpdatedAt)}, }, nil } func (*compatibilityHandler) NewError(context.Context, error) *ProblemStatusCode { return &ProblemStatusCode{StatusCode: http.StatusInternalServerError, Response: fixtureProblem(http.StatusInternalServerError, ProblemCodeInternal)} } func fixtureProblem(status int32, code ProblemCode) Problem { return Problem{Type: "urn:lincodex:problem:" + string(code), Title: "Fixture problem", Status: status, Code: code} } // newServer mounts the fixture with the backend's problem mapping, so decoding // and validation errors produced by real generated code are checked against // the public error contract. func newServer(t *testing.T, handler Handler) *Server { t.Helper() problems := problem.NewResponder(slog.New(slog.DiscardHandler)) server, err := NewServer(handler, WithErrorHandler(problems.HandleServerError), WithNotFound(problems.NotFound), WithMethodNotAllowed(problems.MethodNotAllowed), ) if err != nil { t.Fatalf("NewServer() error = %v", err) } return server } func serve(t *testing.T, server http.Handler, method, target, body string, headers map[string]string) *httptest.ResponseRecorder { t.Helper() request := httptest.NewRequest(method, target, strings.NewReader(body)) if body != "" { request.Header.Set("Content-Type", "application/json") } for name, value := range headers { request.Header.Set(name, value) } response := httptest.NewRecorder() server.ServeHTTP(response, request) return response } func decodeProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code ProblemCode) Problem { t.Helper() if response.Code != status { t.Fatalf("status code = %d, want %d: %s", response.Code, status, response.Body.String()) } if contentType := response.Header().Get("Content-Type"); contentType != problem.MediaType { t.Fatalf("Content-Type = %q, want %q", contentType, problem.MediaType) } var body Problem if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil { t.Fatalf("decode problem %s: %v", response.Body.String(), err) } if err := body.Validate(); err != nil { t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err) } if body.Code != code || int(body.Status) != status { t.Fatalf("problem code/status = %q/%d, want %q/%d", body.Code, body.Status, code, status) } return body } func TestGeneratedServerRejectsInvalidInput(t *testing.T) { server := newServer(t, newCompatibilityHandler()) response := serve(t, server, http.MethodGet, "/probe?state=invalid", "", nil) body := decodeProblem(t, response, http.StatusBadRequest, ProblemCodeValidationFailed) want := []ProblemFieldError{{In: ProblemFieldLocationQuery, Pointer: "/state", Code: "invalid", Message: "The value does not match the contract."}} if !reflect.DeepEqual(body.Errors, want) { t.Fatalf("errors = %+v, want %+v", body.Errors, want) } } func TestNullableTypeArrayPreservesNull(t *testing.T) { var payload NullablePayload if err := json.Unmarshal([]byte(`{"value":null}`), &payload); err != nil { t.Fatalf("decode nullable payload: %v", err) } if !payload.Value.IsNull() { t.Fatal("nullable value was not represented as null") } } func TestAdditionalOperationIsRouted(t *testing.T) { server := newServer(t, newCompatibilityHandler()) response := serve(t, server, "PURGE", "/probe", "", nil) if response.Code != http.StatusNoContent { t.Fatalf("status code = %d, want %d", response.Code, http.StatusNoContent) } } func TestGeneratedValidationErrorsMapToProblemFields(t *testing.T) { validKey := map[string]string{"Idempotency-Key": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"} for _, test := range []struct { name string method string target string body string headers map[string]string field ProblemFieldError }{ {name: "limit below range", method: http.MethodGet, target: "/probe/items?limit=0", field: invalidField(ProblemFieldLocationQuery, "/limit")}, {name: "limit above range", method: http.MethodGet, target: "/probe/items?limit=101", field: invalidField(ProblemFieldLocationQuery, "/limit")}, {name: "cursor too long", method: http.MethodGet, target: "/probe/items?cursor=" + strings.Repeat("a", 513), field: invalidField(ProblemFieldLocationQuery, "/cursor")}, {name: "cursor charset", method: http.MethodGet, target: "/probe/items?cursor=a+b", field: invalidField(ProblemFieldLocationQuery, "/cursor")}, {name: "missing idempotency key", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, field: requiredField(ProblemFieldLocationHeader, "/Idempotency-Key")}, {name: "idempotency key too long", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": strings.Repeat("k", 256)}, field: invalidField(ProblemFieldLocationHeader, "/Idempotency-Key")}, {name: "idempotency key charset", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "key with spaces"}, field: invalidField(ProblemFieldLocationHeader, "/Idempotency-Key")}, {name: "weak if-match", method: http.MethodPatch, target: "/probe/items/" + uuid.NewString(), body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "k1", "If-Match": `W/"v2"`}, field: invalidField(ProblemFieldLocationHeader, "/If-Match")}, {name: "invalid path id", method: http.MethodPatch, target: "/probe/items/not-a-uuid", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "k1"}, field: invalidField(ProblemFieldLocationPath, "/item_id")}, {name: "missing body", method: http.MethodPost, target: "/probe/items", headers: map[string]string{"Idempotency-Key": "k1", "Content-Type": "application/json"}, field: requiredField(ProblemFieldLocationBody, "")}, {name: "missing body field", method: http.MethodPost, target: "/probe/items", body: `{}`, headers: validKey, field: requiredField(ProblemFieldLocationBody, "/name")}, {name: "body field too long", method: http.MethodPost, target: "/probe/items", body: `{"name":"` + strings.Repeat("n", 101) + `"}`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "/name")}, {name: "unknown body field", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe","extra":true}`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "")}, {name: "malformed body", method: http.MethodPost, target: "/probe/items", body: `{"name":`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "")}, } { t.Run(test.name, func(t *testing.T) { server := newServer(t, newCompatibilityHandler()) response := serve(t, server, test.method, test.target, test.body, test.headers) body := decodeProblem(t, response, http.StatusBadRequest, ProblemCodeValidationFailed) if want := []ProblemFieldError{test.field}; !reflect.DeepEqual(body.Errors, want) { t.Fatalf("errors = %+v, want %+v", body.Errors, want) } if strings.Contains(response.Body.String(), "nnnnn") || strings.Contains(response.Body.String(), "spaces") { t.Fatalf("problem echoes the submitted value: %s", response.Body.String()) } }) } } func TestUnsupportedRequestMediaTypeIsRejected(t *testing.T) { server := newServer(t, newCompatibilityHandler()) response := serve(t, server, http.MethodPost, "/probe/items", "name", map[string]string{"Idempotency-Key": "k1", "Content-Type": "text/plain"}) decodeProblem(t, response, http.StatusUnsupportedMediaType, ProblemCodeUnsupportedMediaType) } // A body limit applied with http.MaxBytesReader reaches the problem mapping // through the generated request decoder. func TestBodyOverLimitIsRejected(t *testing.T) { const bodyLimit = 16 server := newServer(t, newCompatibilityHandler()) limited := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, bodyLimit) server.ServeHTTP(w, r) }) request := httptest.NewRequest(http.MethodPost, "/probe/items", strings.NewReader(`{"name":"`+strings.Repeat("n", 64)+`"}`)) request.Header.Set("Content-Type", "application/json") request.Header.Set("Idempotency-Key", "k1") response := httptest.NewRecorder() limited.ServeHTTP(response, request) decodeProblem(t, response, http.StatusRequestEntityTooLarge, ProblemCodePayloadTooLarge) } func TestPaginationAppliesDefaultLimitAndEncodesLastPage(t *testing.T) { handler := newCompatibilityHandler() response := serve(t, newServer(t, handler), http.MethodGet, "/probe/items", "", nil) if response.Code != http.StatusOK { t.Fatalf("status code = %d: %s", response.Code, response.Body.String()) } if handler.lastLimit != defaultPageLimit { t.Fatalf("limit = %d, want the contract default %d", handler.lastLimit, defaultPageLimit) } if !strings.Contains(response.Body.String(), `"page":{"has_more":false,"next_cursor":null}`) { t.Fatalf("last page = %s, want an explicit null cursor", response.Body.String()) } } // The same Idempotency-Key with the same body replays the stored response; the // same key with a different body is rejected with idempotency_key_reused. func TestIdempotencyRetryScenario(t *testing.T) { server := newServer(t, newCompatibilityHandler()) key := map[string]string{"Idempotency-Key": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"} first := serve(t, server, http.MethodPost, "/probe/items", `{"name":"probe"}`, key) if first.Code != http.StatusCreated || first.Header().Get("ETag") != fixtureETag { t.Fatalf("first response = %d ETag %q: %s", first.Code, first.Header().Get("ETag"), first.Body.String()) } if !strings.Contains(first.Body.String(), `"updated_at":"2026-10-05T09:30:00Z"`) { t.Fatalf("timestamp is not UTC RFC 3339: %s", first.Body.String()) } replay := serve(t, server, http.MethodPost, "/probe/items", `{"name":"probe"}`, key) if replay.Code != http.StatusCreated || replay.Body.String() != first.Body.String() { t.Fatalf("replay = %d %s, want the stored response %s", replay.Code, replay.Body.String(), first.Body.String()) } reused := serve(t, server, http.MethodPost, "/probe/items", `{"name":"other"}`, key) decodeProblem(t, reused, http.StatusUnprocessableEntity, ProblemCodeIdempotencyKeyReused) } func TestIfMatchPreconditions(t *testing.T) { server := newServer(t, newCompatibilityHandler()) target := "/probe/items/" + uuid.NewString() missing := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k1"}) decodeProblem(t, missing, http.StatusPreconditionRequired, ProblemCodePreconditionRequired) stale := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k2", "If-Match": staleETag}) decodeProblem(t, stale, http.StatusPreconditionFailed, ProblemCodeVersionConflict) current := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k3", "If-Match": fixtureETag}) if current.Code != http.StatusOK || current.Header().Get("ETag") != `"v3"` { t.Fatalf("update = %d ETag %q: %s", current.Code, current.Header().Get("ETag"), current.Body.String()) } } func invalidField(in ProblemFieldLocation, pointer string) ProblemFieldError { return ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: "The value does not match the contract."} } func requiredField(in ProblemFieldLocation, pointer string) ProblemFieldError { return ProblemFieldError{In: in, Pointer: pointer, Code: "required", Message: "The value is required."} }