"""Регистрация, дубликат username и идентификация только через Bearer""" import uuid import httpx import pytest from helpers import ( assert_error, assert_unauthorized, auth, public_user, unique_password, unique_username, ) def test_duplicate_username_is_conflict(api: httpx.Client, make_user) -> None: alice = make_user("dup") body = { "username": alice["username"], "display_name": "B", "password": unique_password(), } assert_error(api.post("/api/v1/users", json=body), 409, "conflict") me = api.get("/api/v1/users/me", headers=auth(alice)) assert me.json()["display_name"] == alice["display_name"] def test_registration_never_returns_password(api: httpx.Client) -> None: password = unique_password() body = { "username": unique_username("pw"), "display_name": "x", "password": password, } response = api.post("/api/v1/users", json=body) assert response.status_code == 201 assert set(response.json()) == {"id", "username", "display_name", "created_at"} assert password not in response.text @pytest.mark.parametrize( "password", [None, "", "короткий", "x" * 11, "x" * 129, 123456789012], ) def test_invalid_password_is_rejected(api: httpx.Client, password: object) -> None: body: dict[str, object] = {"username": unique_username("pw"), "display_name": "x"} if password is not None: body["password"] = password assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request") def test_password_length_is_counted_in_code_points(api: httpx.Client) -> None: for password in ("😀" * 12, "😀" * 128): body = { "username": unique_username("pw"), "display_name": "x", "password": password, } assert api.post("/api/v1/users", json=body).status_code == 201 @pytest.mark.parametrize( "headers", [ {}, {"Authorization": ""}, {"Authorization": "Bearer"}, {"Authorization": "Bearer not-a-real-token"}, {"Authorization": "Bearer " + "x" * 5000}, {"Authorization": "Token abc"}, ], ) def test_missing_or_unknown_token_is_unauthorized( api: httpx.Client, headers: dict ) -> None: assert_unauthorized(api.get("/api/v1/users/me", headers=headers)) assert_unauthorized(api.get("/api/v1/chats", headers=headers)) def test_x_user_id_gives_no_access(api: httpx.Client, make_user) -> None: alice = make_user("alice") eve = make_user("eve") assert_unauthorized(api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})) me = api.get("/api/v1/users/me", headers={**auth(alice), "X-User-Id": eve["id"]}) assert me.json()["id"] == alice["id"] unknown = {"X-User-Id": str(uuid.uuid4())} assert_unauthorized(api.get("/api/v1/chats", headers=unknown)) def test_current_user(api: httpx.Client, make_user) -> None: alice = make_user("alice") me = api.get("/api/v1/users/me", headers=auth(alice)) assert me.status_code == 200 assert me.json() == public_user(alice)