feat(phase6): 测试补全 + 集成测试 + repository 落地示范
- tests/unit/modules/test_repository.py:base_repository 在 SQLite 内存库的 CRUD 测试 - tests/integration/api/test_smoke.py:登录链路 / 只读接口 / 未授权拦截(标记 integration,默认跳过) - conftest 提供 sqlite_db(隔离 DB)与 app/client/admin_headers(集成)fixture - pytest.ini 默认跳过 integration,Makefile test-integration 可显式运行 - 修复 base_repository.get_by_id/get_by_ids 对字符串 ID 的兼容(URL 路径参数) - 示范 modules/system/level service 改用 level_repo,CRUD 全链路实测通过 Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
+32
-1
@@ -1,7 +1,38 @@
|
||||
"""pytest 全局配置:确保项目根目录在 sys.path。"""
|
||||
"""pytest 全局配置:确保项目根目录在 sys.path,并提供 SQLite 内存库 fixture。"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_db():
|
||||
"""SQLite 内存库会话 fixture:隔离的 service/repository 测试环境。
|
||||
|
||||
将独立会话注入 core.database._db_ctx,测试结束后恢复并清理。
|
||||
不触碰真实 MySQL/Redis。
|
||||
"""
|
||||
from core.database import Base, _db_ctx
|
||||
|
||||
engine = create_engine(
|
||||
"sqlite://",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
Base.metadata.create_all(engine)
|
||||
session = sessionmaker(bind=engine)()
|
||||
|
||||
token = _db_ctx.set(session)
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
_db_ctx.reset(token)
|
||||
session.close()
|
||||
engine.dispose()
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""集成冒烟测试:登录链路 + 各模块只读接口(需 MySQL/Redis 运行,默认跳过)。"""
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_flow(client):
|
||||
"""完整登录链路:/captcha → 解析验证码 → /login 获取 token。"""
|
||||
import redis as redis_lib
|
||||
|
||||
from config import REDIS_INDEX
|
||||
|
||||
r = await client.get("/captcha")
|
||||
body = r.json()
|
||||
assert body["code"] == 0
|
||||
idkey = body.get("idkey")
|
||||
assert idkey
|
||||
|
||||
# 从 Redis 读取验证码明文
|
||||
redis_client = redis_lib.Redis(db=REDIS_INDEX)
|
||||
code = redis_client.get(idkey).decode()
|
||||
|
||||
resp = await client.post("/login", json={
|
||||
"username": "admin", "password": "123456",
|
||||
"captcha": code, "idKey": idkey,
|
||||
})
|
||||
login = resp.json()
|
||||
assert login["code"] == 0
|
||||
assert login["data"]["access_token"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_read_endpoints(client, admin_headers):
|
||||
"""管理员 token 可访问代表性只读接口。"""
|
||||
for path in ("/user/page", "/dept/list", "/menu/list", "/index/menu", "/job/page"):
|
||||
resp = await client.get(path, headers=admin_headers)
|
||||
assert resp.json()["code"] == 0, f"{path} failed"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unauthorized_blocked(client):
|
||||
"""无 token 访问受保护接口应返回 401。"""
|
||||
resp = await client.get("/user/page")
|
||||
assert resp.json()["code"] == 401
|
||||
@@ -0,0 +1,32 @@
|
||||
"""集成测试 fixture:真实 FastAPI 应用 + ASGI client(需 MySQL/Redis 运行)。"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from core import jwt as core_jwt
|
||||
from core.app import create_app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
return create_app()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(app):
|
||||
# 手动运行 Redis lifespan(当前 httpx 版本不支持 ASGITransport lifespan 参数)
|
||||
from core.redis_client import redis_lifespan
|
||||
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with redis_lifespan(app):
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers():
|
||||
"""userId=1 管理员 token(绕过 permission_required 权限校验)。"""
|
||||
token = core_jwt.create_token(
|
||||
{"userId": 1, "username": "admin", "realname": "admin"})
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
@@ -0,0 +1,36 @@
|
||||
"""shared/base_repository 与模块 repository 的单元测试(SQLite 内存库)。"""
|
||||
|
||||
from modules.system.level.repository import level_repo
|
||||
from modules.system.position.repository import position_repo
|
||||
|
||||
|
||||
def test_level_repo_crud(sqlite_db):
|
||||
# create
|
||||
obj = level_repo.create(name="高级", status=1, sort=1)
|
||||
assert obj.id is not None
|
||||
sqlite_db.commit()
|
||||
|
||||
# get / exists
|
||||
assert level_repo.get_by_id(obj.id).name == "高级"
|
||||
assert level_repo.exists(obj.id)
|
||||
assert level_repo.get_by_id(0) is None
|
||||
assert not level_repo.exists(999)
|
||||
|
||||
# paginate
|
||||
items, total = level_repo.paginate(1, 10)
|
||||
assert total == 1
|
||||
assert items[0].id == obj.id
|
||||
|
||||
# update
|
||||
assert level_repo.update(obj.id, {"name": "资深"}) == 1
|
||||
assert level_repo.get_by_id(obj.id).name == "资深"
|
||||
|
||||
# soft delete
|
||||
assert level_repo.soft_delete([obj.id])
|
||||
assert level_repo.get_by_id(obj.id) is None
|
||||
|
||||
|
||||
def test_position_repo_paginate_empty(sqlite_db):
|
||||
items, total = position_repo.paginate(1, 10)
|
||||
assert total == 0
|
||||
assert items == []
|
||||
Reference in New Issue
Block a user