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
This commit is contained in:
Marrrrrrrrry committed 2026-09-08 17:47:21 +08:00
1 parent d701c6e00e
commit 177a212c0f
14 files changed
+130 -136

No files matched your search

+2
View File
@@ -8,6 +8,8 @@ testpaths = ["tests"]
# Tests import top-level packages (core/apps) directly; put the repo root on
# sys.path so bare `pytest` collects without `python -m pytest`.
pythonpath = ["."]
# Async tests/fixtures without per-test decorators.
asyncio_mode = "auto"
[dependency-groups]
dev = [
View File
Whitespace-only changes.
+64
View File
@@ -0,0 +1,64 @@
"""Pytest fixtures for integration tests (real ASGI chain via httpx).
The legacy unittest suite keeps its own style (helpers.SettingsOverrideMixin);
these fixtures are for new pytest-style tests. Lifespan is intentionally NOT
run: it would init the real file DB and start background tasks. Instead the
``db`` fixture inits an in-memory DB, which the per-request middleware and the
handlers then use normally.
"""
import shutil
import httpx
import pytest_asyncio
import main
from core.settings import data_root
from tests.helpers import close_db, init_memory_db
TEST_ADMIN_PASSWORD = "Integration-Test-12345"
@pytest_asyncio.fixture
async def db():
await init_memory_db()
try:
yield
finally:
await close_db()
@pytest_asyncio.fixture
async def client(db):
transport = httpx.ASGITransport(app=main.app)
async with httpx.AsyncClient(
transport=transport, base_url="http://test", follow_redirects=True
) as c:
yield c
@pytest_asyncio.fixture
async def initialized_client(client):
"""App with the system set up via POST /setup (admin password known)."""
response = await client.post(
"/setup",
json={
"admin_password": TEST_ADMIN_PASSWORD,
"confirm_password": TEST_ADMIN_PASSWORD,
"site_name": "integration-tests",
"expireStyle": ["day", "forever", "count"],
},
headers={"Accept": "application/json"},
)
assert response.status_code == 200, response.text
# initialize_system wrote config into the in-memory DB; restore the
# process-global settings snapshot afterwards so other tests see defaults.
from core.settings import settings
original_user_config = dict(settings.user_config)
try:
yield client
finally:
settings.user_config = original_user_config
# Uploads in tests land under <repo>/data/share; remove them so the
# working tree stays clean (the DB itself is in-memory).
shutil.rmtree(f"{data_root}/share", ignore_errors=True)
+47
View File
@@ -0,0 +1,47 @@
"""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()
+1 -6
View File
@@ -20,12 +20,7 @@ from core.settings import DEFAULT_CONFIG, settings
from core.utils import hash_password, verify_password
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
from tests.helpers import SettingsOverrideMixin
class SecurityConfigTests(unittest.TestCase):
+1 -7
View File
@@ -1,15 +1,9 @@
import unittest
from core.settings import settings
from core.storage import S3FileStorage
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
from tests.helpers import SettingsOverrideMixin
class S3StorageConfigTests(SettingsOverrideMixin, unittest.TestCase):
+1 -6
View File
@@ -6,12 +6,7 @@ from apps.admin.services import FileService
from core.settings import settings
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
from tests.helpers import SettingsOverrideMixin
class FakeFileCode:
+1 -6
View File
@@ -6,12 +6,7 @@ from apps.base.views import validate_file_type
from core.settings import settings
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
from tests.helpers import SettingsOverrideMixin
class FileTypeValidationTests(SettingsOverrideMixin, unittest.TestCase):
+1 -8
View File
@@ -5,19 +5,12 @@ from fastapi import HTTPException
from core.settings import BASE_DIR, settings
from main import index, resolve_theme_file
from tests.helpers import SettingsOverrideMixin
# themes/ is produced by the Dockerfile frontend build (see .gitignore); a bare checkout has no such directory
THEMES_BUILT = BASE_DIR.joinpath("themes/2024/assets").is_dir()
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
def get_theme_index_asset(self, theme: str) -> str:
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
+3 -21
View File
@@ -3,10 +3,10 @@ import datetime
import unittest
from unittest.mock import patch
from tortoise import Tortoise
from apps.base.models import FileCodes
from apps.base import views
from tests.helpers import close_db, init_memory_db
from core.settings import DEFAULT_CONFIG, settings
from core.utils import get_now, get_select_token
from main import build_setup_page, parse_setup_options
@@ -48,25 +48,7 @@ class ShareUsageSecurityTests(unittest.TestCase):
original_metadata_limit = views.ip_limit["metadata"]
settings.file_storage = "local"
settings.jwt_secret = "test-download-secret"
await Tortoise.init(
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",
}
)
await Tortoise.generate_schemas()
await init_memory_db()
try:
await self._assert_count_consumption_is_atomic()
await self._assert_time_expiration_and_usage_are_atomic()
@@ -77,7 +59,7 @@ class ShareUsageSecurityTests(unittest.TestCase):
finally:
views.ip_limit["metadata"] = original_metadata_limit
settings.user_config = original_config
await Tortoise.close_connections()
await close_db()
async def _assert_count_consumption_is_atomic(self):
record = await FileCodes.create(
+3 -21
View File
@@ -2,10 +2,10 @@ import asyncio
import unittest
from fastapi import HTTPException
from tortoise import Tortoise
from apps.base.models import FileCodes, StorageReservation
from apps.base.quota import get_storage_usage, release_storage, reserve_storage
from tests.helpers import close_db, init_memory_db
from core.settings import settings
from core.utils import get_now
@@ -17,25 +17,7 @@ class StorageQuotaTests(unittest.TestCase):
async def _run_scenario(self):
original_config = dict(settings.user_config)
settings.storageLimit = 100
await Tortoise.init(
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",
}
)
await Tortoise.generate_schemas()
await init_memory_db()
try:
await FileCodes.create(code="existing", size=60, expired_count=-1)
@@ -84,7 +66,7 @@ class StorageQuotaTests(unittest.TestCase):
)
finally:
settings.user_config = original_config
await Tortoise.close_connections()
await close_db()
if __name__ == "__main__":
+3 -36
View File
@@ -10,6 +10,7 @@ from apps.base import views
from apps.base.models import FileCodes
from apps.base.quota import _detect_sql_dialect, _sql_placeholders, reserve_storage
from apps.base.utils import validate_expire_style
from tests.helpers import init_memory_db
from core.settings import settings
from core.utils import get_select_token
@@ -38,24 +39,7 @@ class SecurityPatchTests(unittest.TestCase):
asyncio.run(self._assert_sql_placeholders())
async def _assert_sql_placeholders(self):
await Tortoise.init(
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",
}
)
await init_memory_db()
try:
self.assertEqual(_detect_sql_dialect(), "sqlite")
self.assertEqual(_sql_placeholders(3), ["?", "?", "?"])
@@ -96,24 +80,7 @@ class SecurityPatchTests(unittest.TestCase):
self.assertEqual(current, expected_current)
self.assertEqual(previous, expected_previous)
await Tortoise.init(
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",
}
)
await init_memory_db()
await Tortoise.generate_schemas()
try:
await FileCodes.create(
+1 -6
View File
@@ -13,12 +13,7 @@ from core.settings import settings
from core.utils import hash_password
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
from tests.helpers import SettingsOverrideMixin
class MagicBytesTests(SettingsOverrideMixin, unittest.TestCase):
+2 -19
View File
@@ -15,6 +15,7 @@ from apps.admin.services import LocalFileClass
from apps.base.models import FileCodes, UploadChunk
from apps.base.schemas import CompleteUploadModel, InitChunkUploadModel
from apps.base.utils import get_chunk_file_path_name
from tests.helpers import init_memory_db
from core.settings import settings
from core.storage import SystemFileStorage
from core.utils import hash_password, verify_password
@@ -125,25 +126,7 @@ class ChunkUploadMetadataTests(unittest.TestCase):
settings.file_storage = "local"
settings.allowed_file_types = ["*"]
with patch("core.storage.data_root", Path(tmpdir.name)):
await Tortoise.init(
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",
}
)
await Tortoise.generate_schemas()
await init_memory_db()
try:
raw_name = "../../../../../../filecodebox.db"
payload = b"chunk payload"