Files
cma-management/backend/tests/test_auth.py
T
Hermes CI Fix 0d90a8e8f3 test: pytest测试框架 + API测试
- 测试框架:SQLite内存数据库,每个测试自动建表/清理
- auth测试:登录/注册/token验证(6个用例)
- kpis测试:增删改查+重复编码检查(6个用例)
- maps测试:创建/编辑/发布/连线/同维度限制(6个用例)
- 后端修复:KPI创建时检查编码唯一性(原为数据库抛500)
2026-05-28 17:42:15 +08:00

95 lines
2.8 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",
})
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",
})
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