64 lines
2.0 KiB
Python
64 lines
2.0 KiB
Python
"""测试公共配置"""
|
|
import os
|
|
import json
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
# 使用临时数据库,避免污染开发数据库
|
|
_test_db = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
|
|
_test_db.close()
|
|
os.environ["DATABASE_URL"] = f"sqlite:///{_test_db.name}"
|
|
|
|
from backend.main import app
|
|
from backend.database import init_db, engine, Base
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def setup_db():
|
|
"""每个测试前重建数据库"""
|
|
Base.metadata.drop_all(bind=engine)
|
|
init_db()
|
|
yield
|
|
Base.metadata.drop_all(bind=engine)
|
|
|
|
|
|
@pytest.fixture
|
|
def client():
|
|
"""已登录的 FastAPI 测试客户端"""
|
|
test_client = TestClient(app)
|
|
response = test_client.post("/api/auth/login", json={"username": "admin", "password": "admin123"})
|
|
test_client.headers.update({"Authorization": f"Bearer {response.json()['token']}"})
|
|
return test_client
|
|
|
|
|
|
@pytest.fixture
|
|
def tmp_config(tmp_path, monkeypatch):
|
|
"""使用临时 config.json"""
|
|
config_path = tmp_path / "config.json"
|
|
config_path.write_text(json.dumps({
|
|
"apps": {
|
|
"1": {
|
|
"name": "测试App",
|
|
"server": "测试环境",
|
|
"AppGuid": "test-guid",
|
|
"API": "https://test.api.com",
|
|
"certificates": {
|
|
"Ad_Hoc": {"name": "com.test.app", "cer": "test-cert", "pro": "test-pro", "theme": "test"}
|
|
}
|
|
}
|
|
},
|
|
"schemes": {
|
|
"1": {"name": "readoor31", "ossFloder": "test"}
|
|
},
|
|
"servers": {
|
|
"测试环境": {"api": "https://test.api.com", "assDom": "applinks:test.com", "universalLink": "https://test.com"},
|
|
"正式环境": {"api": "https://prod.api.com", "assDom": "applinks:prod.com", "universalLink": "https://prod.com"}
|
|
},
|
|
"branches": ["main", "dev"],
|
|
}))
|
|
monkeypatch.setattr("backend.routers.config.CONFIG_JSON_PATH", config_path)
|
|
return config_path
|