Files
mtusi2026lab7-fork/src/backend/tests/json_body_test.go
T

62 lines
1.9 KiB
Go

package tests
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/google/uuid"
)
func TestDecodeJSONBodyRequiresExactFieldNames(t *testing.T) {
fixture := newTestFixture(t)
user, _ := createTestUser(t, fixture.users, "json_tester", "JSON tester")
chat := createTestChat(t, fixture.chats, "JSON body tests", []string{user.ID})
path := "/api/v1/chats/" + chat.ID + "/messages"
for _, test := range []struct {
name string
body string
valid bool
}{
{"canonical", `{"text":"first","attachment_ids":[]}`, true},
{"escaped canonical name", `{"te\u0078t":"first"}`, true},
{"uppercase extra", `{"text":"first","TEXT":"second"}`, false},
{"uppercase extra first", `{"TEXT":"second","text":"first"}`, false},
{"mixed case", `{"Text":"second"}`, false},
{"uppercase attachments", `{"text":"first","ATTACHMENT_IDS":[]}`, false},
{"escaped uppercase", `{"text":"first","\u0054EXT":"second"}`, false},
{"unknown field", `{"text":"first","sender_id":"other"}`, false},
{"wrong type", `{"text":123}`, false},
{"null", `null`, false},
{"array", `[]`, false},
{"trailing object", `{"text":"first"}{}`, false},
} {
t.Run(test.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(test.body))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", uuid.NewString())
authorizeTestRequest(t, fixture, request, user.ID)
response := httptest.NewRecorder()
fixture.router.ServeHTTP(response, request)
want := http.StatusBadRequest
if test.valid {
want = http.StatusCreated
}
if response.Code != want {
t.Fatalf("want %d, got %d: %s", want, response.Code, response.Body.String())
}
if test.valid {
var value map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &value); err != nil {
t.Fatal(err)
}
if value["text"] != "first" {
t.Fatal("text changed")
}
}
})
}
}