Files
item_bank/tests/test_auth.py
T
2026-08-01 16:50:55 +08:00

55 lines
1.7 KiB
Python

"""认证与用户隔离。"""
async def test_register_and_login(client):
r = await client.post(
"/api/auth/register", json={"username": "alice", "password": "secret123"}
)
assert r.status_code == 201
assert r.json()["username"] == "alice"
# 密码哈希不应出现在响应里
assert "password" not in r.text and "hash" not in r.text
r = await client.post(
"/api/auth/login", data={"username": "alice", "password": "secret123"}
)
assert r.status_code == 200
assert r.json()["access_token"]
async def test_duplicate_username_rejected(client):
payload = {"username": "alice", "password": "secret123"}
assert (await client.post("/api/auth/register", json=payload)).status_code == 201
assert (await client.post("/api/auth/register", json=payload)).status_code == 409
async def test_login_wrong_password(client):
await client.post(
"/api/auth/register", json={"username": "alice", "password": "secret123"}
)
r = await client.post(
"/api/auth/login", data={"username": "alice", "password": "wrong"}
)
assert r.status_code == 401
async def test_me_requires_token(client, auth_headers):
assert (await client.get("/api/auth/me")).status_code == 401
headers = await auth_headers()
r = await client.get("/api/auth/me", headers=headers)
assert r.status_code == 200
assert r.json()["username"] == "alice"
async def test_invalid_token_rejected(client):
r = await client.get("/api/auth/me", headers={"Authorization": "Bearer garbage"})
assert r.status_code == 401
async def test_short_password_rejected(client):
r = await client.post(
"/api/auth/register", json={"username": "alice", "password": "123"}
)
assert r.status_code == 422