""" 鉴权模块测试 —— /api/auth 覆盖: 登录 / me / 改密 / Token 校验 / 错误场景 """ import pytest from httpx import AsyncClient from tests.conftest import make_auth_headers, ADMIN_USER_ID, SALES_USER_ID class TestLogin: """POST /api/auth/login""" async def test_login_success(self, client: AsyncClient, seed_data): """正确账密 → 200 + access_token""" resp = await client.post("/api/auth/login", json={ "username": "admin", "password": "admin123" }) assert resp.status_code == 200 body = resp.json() assert body["code"] == 200 assert "access_token" in body["data"] assert body["message"] == "登录成功" async def test_login_wrong_password(self, client: AsyncClient, seed_data): """错误密码 → 401""" resp = await client.post("/api/auth/login", json={ "username": "admin", "password": "wrongpass" }) assert resp.status_code == 401 assert "密码错误" in resp.json()["message"] async def test_login_nonexistent_user(self, client: AsyncClient, seed_data): """不存在的用户 → 401""" resp = await client.post("/api/auth/login", json={ "username": "nobody", "password": "123456" }) assert resp.status_code == 401 async def test_login_empty_fields(self, client: AsyncClient, seed_data): """空字段 → 422 参数校验失败""" resp = await client.post("/api/auth/login", json={ "username": "", "password": "" }) assert resp.status_code == 422 class TestGetMe: """GET /api/auth/me""" async def test_me_success(self, client: AsyncClient, admin_headers): """合法 Token → 200 + 用户信息""" resp = await client.get("/api/auth/me", headers=admin_headers) assert resp.status_code == 200 data = resp.json()["data"] assert data["username"] == "admin" assert data["data_scope"] == "all" async def test_me_no_token(self, client: AsyncClient, seed_data): """无 Token → 422 (Header 缺失)""" resp = await client.get("/api/auth/me") assert resp.status_code == 422 async def test_me_invalid_token(self, client: AsyncClient, seed_data): """伪造 Token → 401""" resp = await client.get("/api/auth/me", headers={ "Authorization": "Bearer fake-token-xxx" }) assert resp.status_code == 401 class TestChangePassword: """PUT /api/auth/password""" async def test_change_password_success(self, client: AsyncClient, admin_headers): """正确旧密码 + 合法新密码 → 200""" resp = await client.put("/api/auth/password", headers=admin_headers, json={ "old_password": "admin123", "new_password": "newpass999" }) assert resp.status_code == 200 assert "密码修改成功" in resp.json()["message"] async def test_change_password_wrong_old(self, client: AsyncClient, admin_headers): """旧密码错误 → 400""" resp = await client.put("/api/auth/password", headers=admin_headers, json={ "old_password": "wrongold", "new_password": "newpass999" }) assert resp.status_code == 400