Files
filecodebox/tests/test_startup_single_db_init.py
orion 41519afb6a ✨ feat: 整合 2.8.5 后端存储、安全与运行优化
* 禁用 OSS 非必需校验尾部,改用精确会话前缀逐对象清理
* 保护上传终态与分享事务,清理失败保留会话并支持安全重试
* 统一下载响应头,兼容旧下载器并防止文件名注入
* 限流改用单调时钟并限制 IP 记录,缓存模板与静态资源策略
* 统一 ORM 初始化与异常处理,新增查询索引及 SQLite 性能参数
* 固定 uvloop/httptools,统一 Docker keep-alive 与内存回收配置
* 同步版本与升级文档,补充 OSS、清理、缓存及数据库回归验证
2026-10-29 16:37:14 +08:00

69 lines
2.5 KiB
Python

"""One Tortoise init path; ORM exception mappings still registered."""
import asyncio
import unittest
from pathlib import Path
from unittest import mock
from tortoise.exceptions import DoesNotExist, IntegrityError
import main
async def _idle_task():
# Stand-in for the real background loops; the lifespan cancels it on exit.
await asyncio.sleep(3600)
class StartupSingleInitTests(unittest.TestCase):
def test_orm_exception_handlers_are_registered(self):
# Behavior pinned by test_admin_write_paths: DoesNotExist -> 404 JSON.
# IntegrityError -> 422 must stay available too.
self.assertIn(DoesNotExist, main.app.exception_handlers)
self.assertIn(IntegrityError, main.app.exception_handlers)
def test_register_tortoise_is_not_used(self):
# register_tortoise merges another lifespan that calls Tortoise.init
# before init_db(); batch 4 (SQLite PRAGMAs) needs a single init path.
source = Path("main.py").read_text(encoding="utf-8")
self.assertNotIn("import register_tortoise", source)
self.assertNotIn("register_tortoise(", source)
def test_lifespan_does_not_initialize_tortoise_outside_init_db(self):
async def scenario():
init_db_calls = []
async def fake_init_db():
init_db_calls.append(True)
async def fake_load_config():
return None
with (
mock.patch.object(main, "init_db", fake_init_db),
mock.patch.object(main, "load_config", fake_load_config),
mock.patch.object(main, "delete_expire_files", _idle_task),
mock.patch.object(main, "clean_incomplete_uploads", _idle_task),
mock.patch.object(
main, "clean_expired_presign_sessions", _idle_task
),
mock.patch.object(main.Tortoise, "init") as tortoise_init,
mock.patch.object(
main.Tortoise, "close_connections"
),
):
# FastAPI merges the lifespan of every included router, so use
# the installed context rather than main.lifespan directly.
async with main.app.router.lifespan_context(main.app):
pass
return init_db_calls, tortoise_init
init_db_calls, tortoise_init = asyncio.run(scenario())
self.assertEqual(init_db_calls, [True])
tortoise_init.assert_not_awaited()
if __name__ == "__main__":
unittest.main()