Files
FileCodeBox/tests/helpers.py
T
Marrrrrrrrry 177a212c0f test: add shared test helpers and ASGI fixtures, dedupe 10x boilerplate
- tests/helpers.py: SettingsOverrideMixin + init_memory_db()/close_db()
- tests/conftest.py: httpx ASGI client fixtures (db, client, initialized_client)
- enable pytest asyncio_mode=auto
- replace 6 duplicated SettingsOverrideMixin copies and 4 duplicated
  Tortoise.init blocks across the legacy unittest suite
2026-09-08 17:47:21 +08:00

48 lines
1.3 KiB
Python

"""Shared test helpers: settings-override mixin and in-memory Tortoise setup.
Kept unittest-friendly (the legacy suite is unittest-based); pytest fixtures
live in conftest.py and build on top of these helpers.
"""
from tortoise import Tortoise
from core.settings import settings
# Mirrors core.database.get_db_config() but with an in-memory SQLite database
# and no WAL/startup-lock specifics, so tests never touch the real data dir's DB.
MEMORY_DB_CONFIG = {
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
class SettingsOverrideMixin:
"""Snapshot settings.user_config in setUp and restore it in tearDown."""
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
async def init_memory_db():
"""Init Tortoise against an in-memory DB and create all schemas."""
await Tortoise.init(config=MEMORY_DB_CONFIG)
await Tortoise.generate_schemas()
async def close_db():
await Tortoise.close_connections()