| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- """pytest 共享配置与 fixture。"""
- import os
- import sys
- _ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
- sys.path.insert(0, _ROOT)
- os.environ.setdefault("ENVIRONMENT", "dev")
- os.environ["TESTING"] = "1"
- os.environ["DATABASE_TYPE"] = "sqlite"
- os.environ["DATABASE_NAME"] = os.path.join(_ROOT, "pytest_fastapiadmin")
- import pytest
- @pytest.fixture(scope="session")
- def test_client():
- """
- lazy import:仅在 fixture 求值时载入应用模块,避免顶层导入触发缺失的生产依赖。
- 如果依赖不完整,跳过该 fixture 的用例(而非整个 pytest 进程)。
- """
- try:
- from fastapi.testclient import TestClient
- from main import create_app
- app = create_app()
- with TestClient(app) as client:
- yield client
- except ImportError as e:
- pytest.skip(f"测试客户端不可用(缺失依赖: {e})")
- @pytest.fixture(scope="session")
- def setup_database():
- """初始化测试数据库表结构(lazy import)。"""
- try:
- import asyncio
- from app.core.database import async_engine
- from app.core.base_model import MappedBase
- async def _setup():
- async with async_engine.begin() as conn:
- await conn.run_sync(MappedBase.metadata.create_all)
- asyncio.run(_setup())
- yield
- asyncio.run(async_engine.dispose())
- except ImportError as e:
- pytest.skip(f"数据库 fixture 不可用(缺失依赖: {e})")
|