1. 添加README说明项目结构 2. 配置Python和Node.js的.gitignore 3. 包含认证模块和账号管理的前后端基础代码 4. 开发计划文档记录当前阶段任务
65 lines
2.4 KiB
Python
65 lines
2.4 KiB
Python
import pytest
|
|
from fastapi import status
|
|
from account_manager import AccountManager
|
|
|
|
def test_login_success(client, mocker_fixture):
|
|
"""测试登录成功"""
|
|
# 设置mock返回验证成功的用户
|
|
mock_user = {
|
|
"id": "550e8400-e29b-41d4-a716-446655440000",
|
|
"username": "testuser",
|
|
"password": "mock_hash",
|
|
"password_salt": "mock_salt",
|
|
"email": "test@example.com",
|
|
"status": "active",
|
|
"created_at": "2025-04-27T00:00:00Z",
|
|
"updated_at": "2025-04-27T00:00:00Z",
|
|
"last_active_at": "2025-04-27T00:00:00Z"
|
|
}
|
|
AccountManager.get_user_by_username.return_value = mock_user
|
|
AccountManager.verify_password.return_value = True
|
|
|
|
response = client.post("/api/auth/login", data={
|
|
"username": "testuser",
|
|
"password": "testpass"
|
|
})
|
|
|
|
# 验证mock调用
|
|
AccountManager.get_user_by_username.assert_called_once_with("testuser")
|
|
AccountManager.verify_password.assert_called_once_with(
|
|
"testpass", "mock_hash", "mock_salt"
|
|
)
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert "access_token" in response.json()
|
|
assert response.json()["token_type"] == "bearer"
|
|
|
|
def test_login_failed(client, mocker_fixture):
|
|
"""测试登录失败"""
|
|
# 设置mock抛出认证失败异常
|
|
AccountManager.get_user_by_username.side_effect = Exception("认证失败")
|
|
|
|
response = client.post("/api/auth/login", data={
|
|
"username": "wronguser",
|
|
"password": "wrongpass"
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
assert response.json()["detail"] == "用户名或密码错误"
|
|
|
|
def test_refresh_token(client, auth_headers, mocker_fixture):
|
|
"""测试刷新令牌"""
|
|
response = client.post("/api/auth/refresh", headers=auth_headers)
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert "access_token" in response.json()
|
|
assert response.json()["token_type"] == "bearer"
|
|
|
|
def test_protected_endpoint(client, auth_headers, mocker_fixture):
|
|
"""测试受保护端点"""
|
|
response = client.get("/api/accounts/testuser", headers=auth_headers)
|
|
assert response.status_code == status.HTTP_200_OK
|
|
|
|
def test_unauthenticated_access(client, mocker_fixture):
|
|
"""测试未认证访问"""
|
|
response = client.get("/api/accounts/testuser")
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|