package http import ( "bytes" "io" "net/http" "strings" "testing" "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" ) func TestValidation_InvalidJSON(t *testing.T) { r := newTestRig(t) alice, _, _, chat := bootstrap(r) path := "/api/v1/chats/" + chat.ID + "/messages" bad := [][]byte{ []byte(`{"text":`), []byte(`not json at all`), []byte(`{"text": 123,}`), []byte(``), []byte(`{"text": "ok"}{"text":"bonus"}`), []byte(`{"text": "ok"}}`), []byte(`{"text": "ok"}]`), []byte(`{"text": "ok"} }`), []byte(`{"text": "ok"} x`), []byte("{\"text\":\"\xff\xfe bad utf8\"}"), } for _, payload := range bad { resp := r.do(http.MethodPost, path, alice.ID, map[string]string{"Content-Type": "application/json"}, bytes.NewReader(payload)) if resp.StatusCode != http.StatusBadRequest { data, _ := io.ReadAll(resp.Body) resp.Body.Close() t.Fatalf("payload %q: expected 400, got %d; body=%s", payload, resp.StatusCode, string(data)) } e := readError(t, resp) if e.Error.Code != CodeInvalidRequest { t.Fatalf("payload %q: expected code %q, got %q", payload, CodeInvalidRequest, e.Error.Code) } if e.Error.RequestID == "" { t.Fatalf("payload %q: missing request_id in body", payload) } } } func TestValidation_InvalidUTF8(t *testing.T) { r := newTestRig(t) alice, bob, _, _ := bootstrap(r) cases := []struct { path, actor string payload []byte }{ {"/api/v1/users", "", []byte("{\"username\":\"u_" + randomSuffix()[:8] + "\",\"display_name\":\"\xc3\x28\"}")}, {"/api/v1/chats", alice.ID, []byte("{\"title\":\"\xe2\x82\",\"member_ids\":[\"" + alice.ID + "\",\"" + bob.ID + "\"]}")}, } for _, tc := range cases { resp := r.do(http.MethodPost, tc.path, tc.actor, map[string]string{"Content-Type": "application/json"}, bytes.NewReader(tc.payload)) if resp.StatusCode != http.StatusBadRequest { data, _ := io.ReadAll(resp.Body) resp.Body.Close() t.Fatalf("%s %q: expected 400, got %d; body=%s", tc.path, tc.payload, resp.StatusCode, string(data)) } e := readError(t, resp) if e.Error.Code != CodeInvalidRequest { t.Fatalf("%s: expected code %q, got %q", tc.path, CodeInvalidRequest, e.Error.Code) } } } func TestValidation_JSONKeysAreCaseSensitive(t *testing.T) { r := newTestRig(t) resp := r.do(http.MethodPost, "/api/v1/users", "", map[string]string{"Content-Type": "application/json"}, strings.NewReader(`{"USERNAME":"case_bob","Display_Name":"B"}`)) expectStatus(t, resp, http.StatusBadRequest) resp.Body.Close() } func TestValidation_ErrorMessages(t *testing.T) { r := newTestRig(t) alice, bob, _, chat := bootstrap(r) msgs := "/api/v1/chats/" + chat.ID + "/messages" cases := []struct { method, path, actor, body, message string }{ {http.MethodPost, "/api/v1/users", "", `{"username":"ab","display_name":"x"}`, "username: must match [a-z0-9_]{3,32}"}, {http.MethodPost, "/api/v1/users", "", `{"username":"abc_` + randomSuffix()[:6] + `","display_name":" "}`, "display_name: must not be empty or whitespace only"}, {http.MethodPost, "/api/v1/users", "", `{"username":123,"display_name":"x"}`, `body: field "username": invalid type`}, {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"p"}`, "password: length must be in [12, 128] code points"}, {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}`, "password: must not be empty or whitespace only"}, {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"` + strings.Repeat("я", 129) + `"}`, "password: length must be in [12, 128] code points"}, {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"long-enough-pw","password_hash":"h"}`, `body: unknown field "password_hash"`}, {http.MethodPost, "/api/v1/users", "", `{"username":`, "body: invalid JSON"}, {http.MethodPost, "/api/v1/users", "", ``, "body: empty body"}, {http.MethodPost, "/api/v1/users", "", `[]`, "body: expected a JSON object"}, {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"} {}`, "body: unexpected data after JSON object"}, {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}}`, "body: unexpected data after JSON object"}, {http.MethodPost, "/api/v1/users", "", "{\"username\":\"abc\",\"display_name\":\"\xff\"}", "body: invalid UTF-8"}, {http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + bob.ID + `"]}`, "member_ids: must contain caller"}, {http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + alice.ID + `","x"]}`, "member_ids[1]: must be a valid UUID"}, {http.MethodPost, msgs, alice.ID, `{"text":" "}`, "text: must not be empty or whitespace only"}, {http.MethodGet, msgs + "?limit=abc", alice.ID, "", "limit: must be an integer"}, {http.MethodGet, msgs + "?limit=0", alice.ID, "", "limit: must be in [1, 100]"}, {http.MethodGet, msgs + "?limit=", alice.ID, "", "limit: must be an integer"}, {http.MethodGet, msgs + "?cursor=", alice.ID, "", "cursor: must not be empty"}, {http.MethodGet, msgs + "?limit=10&cursor=", alice.ID, "", "cursor: must not be empty"}, {http.MethodGet, "/api/v1/chats?limit=", alice.ID, "", "limit: must be an integer"}, {http.MethodGet, "/api/v1/chats?cursor=", alice.ID, "", "cursor: must not be empty"}, } for _, tc := range cases { headers := map[string]string{} var body io.Reader if tc.method == http.MethodPost { headers["Content-Type"] = "application/json" body = bytes.NewReader([]byte(tc.body)) } resp := r.do(tc.method, tc.path, tc.actor, headers, body) if resp.StatusCode != http.StatusBadRequest { data, _ := io.ReadAll(resp.Body) resp.Body.Close() t.Fatalf("%s %s %q: expected 400, got %d; body=%s", tc.method, tc.path, tc.body, resp.StatusCode, string(data)) } e := readError(t, resp) if e.Error.Message != tc.message { t.Fatalf("%s %s %q:\n want %q\n got %q", tc.method, tc.path, tc.body, tc.message, e.Error.Message) } } } func TestValidation_EmptyMessage(t *testing.T) { r := newTestRig(t) alice, _, _, chat := bootstrap(r) path := "/api/v1/chats/" + chat.ID + "/messages" for _, text := range []string{"", " ", "\n\t "} { resp := r.doJSON(http.MethodPost, path, alice.ID, dto.CreateMessageRequest{Text: text}) if resp.StatusCode != http.StatusBadRequest { data, _ := io.ReadAll(resp.Body) resp.Body.Close() t.Fatalf("text %q: expected 400, got %d; body=%s", text, resp.StatusCode, string(data)) } e := readError(t, resp) if e.Error.Code != CodeInvalidRequest { t.Fatalf("text %q: expected code %q, got %q", text, CodeInvalidRequest, e.Error.Code) } } } func TestValidation_DuplicateUsername(t *testing.T) { r := newTestRig(t) username := "own_dup_" + randomSuffix() first := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ Username: username, DisplayName: "Первый", Password: testPassword, }) expectStatus(t, first, http.StatusCreated) first.Body.Close() second := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ Username: username, DisplayName: "Второй", Password: testPassword, }) if second.StatusCode != http.StatusConflict { data, _ := io.ReadAll(second.Body) second.Body.Close() t.Fatalf("second POST same username: expected 409, got %d; body=%s", second.StatusCode, string(data)) } e := readError(t, second) if e.Error.Code != CodeConflict { t.Fatalf("expected code %q, got %q", CodeConflict, e.Error.Code) } third := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ Username: username, DisplayName: "Первый", Password: testPassword, }) if third.StatusCode != http.StatusConflict { data, _ := io.ReadAll(third.Body) third.Body.Close() t.Fatalf("third POST same username/display_name: expected 409, got %d; body=%s", third.StatusCode, string(data)) } third.Body.Close() } func TestValidation_UUIDForms(t *testing.T) { r := newTestRig(t) alice, bob, _, chat := bootstrap(r) upper := strings.ToUpper(alice.ID) resp := r.do(http.MethodGet, "/api/v1/users/me", upper, nil, nil) expectStatus(t, resp, http.StatusOK) resp.Body.Close() resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ToUpper(chat.ID), alice.ID, nil, nil) expectStatus(t, resp, http.StatusOK) resp.Body.Close() resp = r.do(http.MethodGet, "/api/v1/users/me", "{"+alice.ID+"}", nil, nil) expectStatus(t, resp, http.StatusUnauthorized) resp.Body.Close() resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ReplaceAll(chat.ID, "-", ""), alice.ID, nil, nil) expectStatus(t, resp, http.StatusBadRequest) resp.Body.Close() resp = r.doJSON(http.MethodPost, "/api/v1/chats", alice.ID, map[string]any{ "title": "dup", "member_ids": []string{alice.ID, upper, bob.ID}, }) expectStatus(t, resp, http.StatusBadRequest) resp.Body.Close() }