Files
cma-management/backend/tests/test_auth.py
T
Hermes CI Fix a13a080381 test: CMA自动化测试补覆盖 226→452用例, 覆盖率36%→60%
- 新增8个测试文件(bot_bridge/kpi_causality/cash/predict/reports/tax_compliance/expenses/probe_cost)
- 增强 budget/auth/users + conftest账套模式适配
- 测试驱动修复: bot_bridge导入batch_id→source_batch; cash_forecast extra空dict
- 全量: 451 passed, 1 xfailed; 报告 docs/cma-test-coverage-report.md
2026-08-20 06:57:24 +08:00

97 lines
2.9 KiB
Python

"""
认证模块测试
"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from tests.conftest import create_test_user, get_token_for_user, auth_header
class TestAuth:
"""用户认证测试"""
def test_login_success(self, client: TestClient, db: Session):
"""登录成功"""
create_test_user(db)
resp = client.post("/api/cma/auth/login", json={
"username": "testadmin",
"password": "admin123",
"entity_id": 1,
})
assert resp.status_code == 200
data = resp.json()
assert "token" in data
assert data["user"]["username"] == "testadmin"
assert data["user"]["role"] == "ceo"
def test_login_wrong_password(self, client: TestClient, db: Session):
"""密码错误"""
create_test_user(db)
resp = client.post("/api/cma/auth/login", json={
"username": "testadmin",
"password": "wrongpass",
})
assert resp.status_code == 401
def test_login_nonexistent_user(self, client: TestClient):
"""用户不存在"""
resp = client.post("/api/cma/auth/login", json={
"username": "nobody",
"password": "admin123",
})
assert resp.status_code == 401
def test_me_with_valid_token(self, client: TestClient, db: Session):
"""有效token获取用户信息"""
create_test_user(db)
token = get_token_for_user(client)
resp = client.get("/api/cma/auth/me", headers={
"Authorization": f"Bearer {token}"
})
assert resp.status_code == 200
assert resp.json()["username"] == "testadmin"
def test_me_without_token(self, client: TestClient):
"""无token访问需要认证的接口"""
resp = client.get("/api/cma/auth/me")
assert resp.status_code == 403 # HTTPBearer auto_error
def test_register(self, client: TestClient, db: Session):
"""注册新用户"""
resp = client.post("/api/cma/auth/register", json={
"username": "newuser",
"password": "newpass123",
"name": "新用户",
"role": "business",
})
assert resp.status_code == 200
assert resp.json()["message"] == "注册成功"
# 验证可以登录
login_resp = client.post("/api/cma/auth/login", json={
"username": "newuser",
"password": "newpass123",
"entity_id": 1,
})
assert login_resp.status_code == 200
def test_register_duplicate(self, client: TestClient, db: Session):
"""重复用户名注册"""
create_test_user(db)
resp = client.post("/api/cma/auth/register", json={
"username": "testadmin",
"password": "admin123",
"name": "重复用户",
})
assert resp.status_code == 400