78 lines
2.0 KiB
Python
78 lines
2.0 KiB
Python
|
|
"""测试配置和 fixtures"""
|
||
|
|
|
||
|
|
import asyncio
|
||
|
|
import tempfile
|
||
|
|
import uuid
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from app.config import AppConfig, load_config
|
||
|
|
from app.database import close_db, get_db
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture(scope="session")
|
||
|
|
def event_loop():
|
||
|
|
"""创建事件循环"""
|
||
|
|
loop = asyncio.get_event_loop_policy().new_event_loop()
|
||
|
|
yield loop
|
||
|
|
loop.close()
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture
|
||
|
|
async def temp_db():
|
||
|
|
"""临时数据库 fixture"""
|
||
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||
|
|
# 使用唯一的文件名确保每个测试都使用新数据库
|
||
|
|
db_path = Path(tmpdir) / f"test_{uuid.uuid4().hex}.db"
|
||
|
|
# 修改配置使用临时数据库
|
||
|
|
import app.config as config_module
|
||
|
|
original_db_path = config_module.settings.database.path
|
||
|
|
config_module.settings.database.path = str(db_path)
|
||
|
|
|
||
|
|
# 确保使用新的数据库连接
|
||
|
|
import app.database as db_module
|
||
|
|
db_module._db = None
|
||
|
|
|
||
|
|
yield db_path
|
||
|
|
|
||
|
|
# 清理
|
||
|
|
await close_db()
|
||
|
|
config_module.settings.database.path = original_db_path
|
||
|
|
db_module._db = None
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture
|
||
|
|
async def temp_storage():
|
||
|
|
"""临时存储目录 fixture"""
|
||
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||
|
|
import app.config as config_module
|
||
|
|
original_storage_path = config_module.settings.storage.path
|
||
|
|
config_module.settings.storage.path = tmpdir
|
||
|
|
|
||
|
|
yield tmpdir
|
||
|
|
|
||
|
|
config_module.settings.storage.path = original_storage_path
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture
|
||
|
|
async def db(temp_db):
|
||
|
|
"""初始化数据库 fixture"""
|
||
|
|
from app import database as db_module
|
||
|
|
await get_db()
|
||
|
|
return db_module
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture
|
||
|
|
def sample_plan():
|
||
|
|
"""示例 Plan 数据"""
|
||
|
|
return {
|
||
|
|
"name": "Test Plan",
|
||
|
|
"provider_name": "openai",
|
||
|
|
"api_key": "sk-test-key",
|
||
|
|
"api_base": "https://api.openai.com/v1",
|
||
|
|
"plan_type": "coding",
|
||
|
|
"supported_models": ["gpt-4", "gpt-3.5-turbo"],
|
||
|
|
"enabled": True,
|
||
|
|
}
|