conftest.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import os
  2. import sys
  3. _ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
  4. sys.path.insert(0, _ROOT)
  5. os.environ.setdefault("ENVIRONMENT", "dev")
  6. os.environ["TESTING"] = "1"
  7. os.environ["DATABASE_TYPE"] = "sqlite"
  8. os.environ["DATABASE_NAME"] = os.path.join(_ROOT, "pytest_fastapiadmin")
  9. import pytest
  10. from fastapi.testclient import TestClient
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from main import create_app
  13. from app.core.database import async_engine
  14. from app.core.base_model import MappedBase
  15. from app.plugin.module_payment.enterprise.model import EnterpriseModel
  16. @pytest.fixture(scope="session")
  17. def test_client():
  18. """创建测试客户端"""
  19. app = create_app()
  20. with TestClient(app) as client:
  21. yield client
  22. @pytest.fixture(scope="session", autouse=True)
  23. def setup_database():
  24. """初始化测试数据库表结构"""
  25. import asyncio
  26. async def _setup():
  27. async with async_engine.begin() as coon:
  28. await coon.run_sync(MappedBase.metadata.create_all)
  29. asyncio.get_event_loop().run_until_complete(_setup())
  30. yield
  31. asyncio.get_event_loop().run_until_complete(async_engine.dispose())