From 177a212c0fde3739b0968d474ddb07639bcc25f8 Mon Sep 17 00:00:00 2001 From: Marrrrrrrrry <34876935+Marrrrrrrrry@users.noreply.github.com> Date: Tue, 8 Sep 2026 17:47:21 +0800 Subject: [PATCH] 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 --- pyproject.toml | 2 + tests/__init__.py | 0 tests/conftest.py | 64 +++++++++++++++++++++++++ tests/helpers.py | 47 ++++++++++++++++++ tests/test_admin_security.py | 7 +-- tests/test_issue_461_s3_addressing.py | 8 +--- tests/test_issue_464_admin_file_list.py | 7 +-- tests/test_issue_465_file_type.py | 7 +-- tests/test_issue_476_theme_assets.py | 9 +--- tests/test_issue_482_share_usage.py | 24 ++-------- tests/test_issue_486_storage_quota.py | 24 ++-------- tests/test_pr494_security_patches.py | 39 ++------------- tests/test_security_gaps.py | 7 +-- tests/test_security_hardening.py | 21 +------- 14 files changed, 130 insertions(+), 136 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/helpers.py diff --git a/pyproject.toml b/pyproject.toml index 5087b12..e1e48de 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 = [ diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..62b82d9 --- /dev/null +++ b/tests/conftest.py @@ -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 /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) diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..8b679b8 --- /dev/null +++ b/tests/helpers.py @@ -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() diff --git a/tests/test_admin_security.py b/tests/test_admin_security.py index b7a0f95..290bc51 100644 --- a/tests/test_admin_security.py +++ b/tests/test_admin_security.py @@ -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): diff --git a/tests/test_issue_461_s3_addressing.py b/tests/test_issue_461_s3_addressing.py index 9ff6ecd..d8a7116 100644 --- a/tests/test_issue_461_s3_addressing.py +++ b/tests/test_issue_461_s3_addressing.py @@ -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): diff --git a/tests/test_issue_464_admin_file_list.py b/tests/test_issue_464_admin_file_list.py index 38d21c9..1fc0e71 100644 --- a/tests/test_issue_464_admin_file_list.py +++ b/tests/test_issue_464_admin_file_list.py @@ -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: diff --git a/tests/test_issue_465_file_type.py b/tests/test_issue_465_file_type.py index d2bee8d..5d15f9b 100644 --- a/tests/test_issue_465_file_type.py +++ b/tests/test_issue_465_file_type.py @@ -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): diff --git a/tests/test_issue_476_theme_assets.py b/tests/test_issue_476_theme_assets.py index 4449554..4c5c5f7 100644 --- a/tests/test_issue_476_theme_assets.py +++ b/tests/test_issue_476_theme_assets.py @@ -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")) diff --git a/tests/test_issue_482_share_usage.py b/tests/test_issue_482_share_usage.py index f2ca237..50b2aee 100644 --- a/tests/test_issue_482_share_usage.py +++ b/tests/test_issue_482_share_usage.py @@ -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( diff --git a/tests/test_issue_486_storage_quota.py b/tests/test_issue_486_storage_quota.py index 57e4c3f..721c640 100644 --- a/tests/test_issue_486_storage_quota.py +++ b/tests/test_issue_486_storage_quota.py @@ -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__": diff --git a/tests/test_pr494_security_patches.py b/tests/test_pr494_security_patches.py index aec50b3..0425633 100644 --- a/tests/test_pr494_security_patches.py +++ b/tests/test_pr494_security_patches.py @@ -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( diff --git a/tests/test_security_gaps.py b/tests/test_security_gaps.py index b2986a4..4e3aade 100644 --- a/tests/test_security_gaps.py +++ b/tests/test_security_gaps.py @@ -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): diff --git a/tests/test_security_hardening.py b/tests/test_security_hardening.py index 11fb307..4feab37 100644 --- a/tests/test_security_hardening.py +++ b/tests/test_security_hardening.py @@ -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"