test_auth_api.py
11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""F-06 API 认证与用户管理测试"""
import pytest
from unittest.mock import patch, AsyncMock, MagicMock
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime, timedelta
from app.services import auth_service
from app.models.user import User
from app.models.api_token import ApiToken
class TestAuthService:
"""认证服务单元测试"""
def test_hash_and_verify_password(self):
"""测试密码哈希与校验"""
password = "test_password_123"
hashed = auth_service.hash_password(password)
assert hashed != password
assert auth_service.verify_password(password, hashed) is True
assert auth_service.verify_password("wrong_password", hashed) is False
def test_hash_token(self):
"""测试 Token 哈希"""
token = "some-random-refresh-token"
hashed = auth_service.hash_token(token)
assert hashed != token
assert len(hashed) == 64 # SHA256 hex digest
def test_create_access_token(self):
"""测试创建 Access Token"""
data = {"sub": "user-id-123", "username": "testuser"}
token = auth_service.create_access_token(data)
assert token is not None
assert isinstance(token, str)
# 解码验证
payload = auth_service.decode_access_token(token)
assert payload is not None
assert payload["sub"] == "user-id-123"
assert payload["username"] == "testuser"
assert payload["type"] == "access"
def test_decode_invalid_token(self):
"""测试解码无效 Token"""
assert auth_service.decode_access_token("invalid-token") is None
assert auth_service.decode_access_token("") is None
def test_create_refresh_token(self):
"""测试创建 Refresh Token"""
token = auth_service.create_refresh_token()
assert token is not None
assert len(token) > 30
class TestAuthAPI:
"""认证 API 集成测试"""
REGISTER_DATA = {
"username": "testuser",
"password": "test123456",
"email": "test@example.com",
"display_name": "测试用户",
}
LOGIN_DATA = {
"username": "testuser",
"password": "test123456",
}
@pytest.mark.asyncio
async def test_register(self, client: AsyncClient):
"""测试用户注册"""
resp = await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
assert resp.status_code == 201
result = resp.json()
assert result["username"] == "testuser"
assert result["email"] == "test@example.com"
assert result["role"] == "user"
assert "id" in result
@pytest.mark.asyncio
async def test_register_duplicate_username(self, client: AsyncClient):
"""测试重复用户名注册返回 409"""
await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
resp = await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
assert resp.status_code == 409
@pytest.mark.asyncio
async def test_register_missing_fields(self, client: AsyncClient):
"""测试缺少必填字段返回 422"""
resp = await client.post("/api/v1/auth/register", json={"username": "test"})
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_login(self, client: AsyncClient):
"""测试登录返回 JWT Token"""
await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
resp = await client.post("/api/v1/auth/login", json=self.LOGIN_DATA)
assert resp.status_code == 200
result = resp.json()
assert "access_token" in result
assert "refresh_token" in result
assert result["token_type"] == "bearer"
@pytest.mark.asyncio
async def test_login_wrong_password(self, client: AsyncClient):
"""测试错误密码登录返回 401"""
await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
resp = await client.post("/api/v1/auth/login", json={
"username": "testuser",
"password": "wrong-password",
})
assert resp.status_code == 401
@pytest.mark.asyncio
async def test_login_nonexistent_user(self, client: AsyncClient):
"""测试不存在的用户登录返回 401"""
resp = await client.post("/api/v1/auth/login", json=self.LOGIN_DATA)
assert resp.status_code == 401
@pytest.mark.asyncio
async def test_me_with_valid_token(self, client: AsyncClient):
"""测试带有效 Token 访问 /me"""
await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
login_resp = await client.post("/api/v1/auth/login", json=self.LOGIN_DATA)
token = login_resp.json()["access_token"]
resp = await client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})
assert resp.status_code == 200
me = resp.json()
assert me["username"] == "testuser"
assert me["display_name"] == "测试用户"
@pytest.mark.asyncio
async def test_me_without_token(self, client: AsyncClient):
"""测试无 Token 访问 /me 返回 401"""
resp = await client.get("/api/v1/auth/me")
assert resp.status_code == 401
@pytest.mark.asyncio
async def test_me_with_invalid_token(self, client: AsyncClient):
"""测试无效 Token 访问 /me 返回 401"""
resp = await client.get("/api/v1/auth/me", headers={"Authorization": "Bearer invalid-token"})
assert resp.status_code == 401
@pytest.mark.asyncio
async def test_refresh_token(self, client: AsyncClient):
"""测试刷新 Token"""
await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
login_resp = await client.post("/api/v1/auth/login", json=self.LOGIN_DATA)
refresh_token = login_resp.json()["refresh_token"]
resp = await client.post("/api/v1/auth/refresh", json={"refresh_token": refresh_token})
assert resp.status_code == 200
result = resp.json()
assert "access_token" in result
assert result["token_type"] == "bearer"
@pytest.mark.asyncio
async def test_refresh_invalid_token(self, client: AsyncClient):
"""测试无效 Refresh Token 刷新返回 401"""
resp = await client.post("/api/v1/auth/refresh", json={"refresh_token": "invalid-token"})
assert resp.status_code == 401
@pytest.mark.asyncio
async def test_admin_list_users(self, client: AsyncClient, db_session: AsyncSession):
"""测试管理员查询用户列表"""
# 注册普通用户
await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
# 使用不同的用户名注册 admin
admin_reg_data = {
"username": "admin_user",
"password": "admin123456",
"email": "admin@example.com",
"display_name": "管理员",
}
admin_resp = await client.post("/api/v1/auth/register", json=admin_reg_data)
admin_id = admin_resp.json()["id"]
# 在同一个测试 session 中更新用户角色为 admin
from sqlalchemy import update
from app.models.user import User
await db_session.execute(
update(User).where(User.id == admin_id).values(role="admin")
)
await db_session.flush()
# 用 admin 账号登录
login_resp = await client.post("/api/v1/auth/login", json={
"username": "admin_user",
"password": "admin123456",
})
access_token = login_resp.json()["access_token"]
# 查询用户列表
resp = await client.get(
"/api/v1/auth/users",
headers={"Authorization": f"Bearer {access_token}"},
)
assert resp.status_code == 200
result = resp.json()
assert result["total"] >= 2
assert "items" in result
@pytest.mark.asyncio
async def test_non_admin_cannot_list_users(self, client: AsyncClient):
"""测试非管理员查询用户列表返回 403"""
await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
login_resp = await client.post("/api/v1/auth/login", json=self.LOGIN_DATA)
token = login_resp.json()["access_token"]
resp = await client.get(
"/api/v1/auth/users",
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 403
@pytest.mark.asyncio
async def test_admin_update_user(self, client: AsyncClient, db_session: AsyncSession):
"""测试管理员编辑用户"""
# 注册普通用户
reg = await client.post("/api/v1/auth/register", json=self.REGISTER_DATA)
user_id = reg.json()["id"]
# 注册 admin 用户
admin_reg = await client.post("/api/v1/auth/register", json={
"username": "admin_update",
"password": "admin123456",
"email": "admin-update@example.com",
"display_name": "管理员",
})
admin_id = admin_reg.json()["id"]
# 在同一个测试 session 中提升为 admin
from sqlalchemy import update
from app.models.user import User
await db_session.execute(
update(User).where(User.id == admin_id).values(role="admin")
)
await db_session.flush()
# 登录 admin
login_resp = await client.post("/api/v1/auth/login", json={
"username": "admin_update",
"password": "admin123456",
})
access_token = login_resp.json()["access_token"]
# 更新用户
resp = await client.put(
f"/api/v1/auth/users/{user_id}",
json={"display_name": "更新后的名称", "role": "admin"},
headers={"Authorization": f"Bearer {access_token}"},
)
assert resp.status_code == 200
result = resp.json()
assert result["display_name"] == "更新后的名称"
assert result["role"] == "admin"
@pytest.mark.asyncio
async def test_update_nonexistent_user(self, client: AsyncClient, db_session: AsyncSession):
"""测试更新不存在的用户返回 404"""
# 注册并登录 admin
admin_reg = await client.post("/api/v1/auth/register", json={
"username": "admin_non_exist",
"password": "admin123456",
"email": "admin-ne@example.com",
"display_name": "管理员",
})
admin_id = admin_reg.json()["id"]
from sqlalchemy import update
from app.models.user import User
await db_session.execute(
update(User).where(User.id == admin_id).values(role="admin")
)
await db_session.flush()
login_resp = await client.post("/api/v1/auth/login", json={
"username": "admin_non_exist",
"password": "admin123456",
})
access_token = login_resp.json()["access_token"]
resp = await client.put(
"/api/v1/auth/users/nonexistent-id",
json={"display_name": "test"},
headers={"Authorization": f"Bearer {access_token}"},
)
assert resp.status_code == 404