|
| 1 | +"""One Tortoise init path; ORM exception mappings still registered.""" |
| 2 | +import asyncio |
| 3 | +import unittest |
| 4 | +from pathlib import Path |
| 5 | +from unittest import mock |
| 6 | + |
| 7 | +from tortoise.exceptions import DoesNotExist, IntegrityError |
| 8 | + |
| 9 | +import main |
| 10 | + |
| 11 | + |
| 12 | +async def _idle_task(): |
| 13 | + # Stand-in for the real background loops; the lifespan cancels it on exit. |
| 14 | + await asyncio.sleep(3600) |
| 15 | + |
| 16 | + |
| 17 | +class StartupSingleInitTests(unittest.TestCase): |
| 18 | + def test_orm_exception_handlers_are_registered(self): |
| 19 | + # Behavior pinned by test_admin_write_paths: DoesNotExist -> 404 JSON. |
| 20 | + # IntegrityError -> 422 must stay available too. |
| 21 | + self.assertIn(DoesNotExist, main.app.exception_handlers) |
| 22 | + self.assertIn(IntegrityError, main.app.exception_handlers) |
| 23 | + |
| 24 | + def test_register_tortoise_is_not_used(self): |
| 25 | + # register_tortoise merges another lifespan that calls Tortoise.init |
| 26 | + # before init_db(); batch 4 (SQLite PRAGMAs) needs a single init path. |
| 27 | + source = Path("main.py").read_text(encoding="utf-8") |
| 28 | + self.assertNotIn("import register_tortoise", source) |
| 29 | + self.assertNotIn("register_tortoise(", source) |
| 30 | + |
| 31 | + def test_lifespan_does_not_initialize_tortoise_outside_init_db(self): |
| 32 | + async def scenario(): |
| 33 | + init_db_calls = [] |
| 34 | + |
| 35 | + async def fake_init_db(): |
| 36 | + init_db_calls.append(True) |
| 37 | + |
| 38 | + async def fake_load_config(): |
| 39 | + return None |
| 40 | + |
| 41 | + with ( |
| 42 | + mock.patch.object(main, "init_db", fake_init_db), |
| 43 | + mock.patch.object(main, "load_config", fake_load_config), |
| 44 | + mock.patch.object(main, "delete_expire_files", _idle_task), |
| 45 | + mock.patch.object(main, "clean_incomplete_uploads", _idle_task), |
| 46 | + mock.patch.object( |
| 47 | + main, "clean_expired_presign_sessions", _idle_task |
| 48 | + ), |
| 49 | + mock.patch.object(main.Tortoise, "init") as tortoise_init, |
| 50 | + mock.patch.object( |
| 51 | + main.Tortoise, "close_connections" |
| 52 | + ), |
| 53 | + ): |
| 54 | + # FastAPI merges the lifespan of every included router, so use |
| 55 | + # the installed context rather than main.lifespan directly. |
| 56 | + async with main.app.router.lifespan_context(main.app): |
| 57 | + pass |
| 58 | + |
| 59 | + return init_db_calls, tortoise_init |
| 60 | + |
| 61 | + init_db_calls, tortoise_init = asyncio.run(scenario()) |
| 62 | + |
| 63 | + self.assertEqual(init_db_calls, [True]) |
| 64 | + tortoise_init.assert_not_awaited() |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + unittest.main() |
0 commit comments