conftest.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """pytest 共享配置与 fixture。"""
  2. import os
  3. import sys
  4. _ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
  5. sys.path.insert(0, _ROOT)
  6. os.environ.setdefault("ENVIRONMENT", "dev")
  7. os.environ["TESTING"] = "1"
  8. os.environ["DATABASE_TYPE"] = "sqlite"
  9. os.environ["DATABASE_NAME"] = os.path.join(_ROOT, "pytest_fastapiadmin")
  10. import pytest
  11. @pytest.fixture(scope="session")
  12. def test_client():
  13. """
  14. lazy import:仅在 fixture 求值时载入应用模块,避免顶层导入触发缺失的生产依赖。
  15. 如果依赖不完整,跳过该 fixture 的用例(而非整个 pytest 进程)。
  16. """
  17. try:
  18. from fastapi.testclient import TestClient
  19. from main import create_app
  20. app = create_app()
  21. with TestClient(app) as client:
  22. yield client
  23. except ImportError as e:
  24. pytest.skip(f"测试客户端不可用(缺失依赖: {e})")
  25. @pytest.fixture(scope="session")
  26. def setup_database():
  27. """初始化测试数据库表结构(lazy import)。"""
  28. try:
  29. import asyncio
  30. from app.core.database import async_engine
  31. from app.core.base_model import MappedBase
  32. async def _setup():
  33. async with async_engine.begin() as conn:
  34. await conn.run_sync(MappedBase.metadata.create_all)
  35. asyncio.run(_setup())
  36. yield
  37. asyncio.run(async_engine.dispose())
  38. except ImportError as e:
  39. pytest.skip(f"数据库 fixture 不可用(缺失依赖: {e})")