Files
crm_project/server/tests/api/test_auth.py
T
hankin 815cbf9d8c v0.2.0: CRM/ERP 系统升级 - 清理 .gitignore 并移除误提交的 venv/env/db 文件
- 更新 .gitignore:全面覆盖环境变量、数据库、日志、缓存、上传文件
- 移除误跟踪的 server/venv/、crm_data.db、.env 文件
- 新增 server/.env.example 模板
- 新增合同管理、利润核算、AI教练等功能模块
- 新增 Playwright e2e 测试套件
- 前后端多项功能升级和 bug 修复
2026-05-11 07:24:19 +00:00

90 lines
3.2 KiB
Python

"""
鉴权模块测试 —— /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