Restore deterministic background lifecycle tests

This commit is contained in:
Nick Sweeting 2026-07-20 01:31:19 -07:00
parent a6684c773d
commit 48bef35706
2 changed files with 34 additions and 0 deletions

View File

@ -66,6 +66,7 @@ def test_cli_run_signal_cleans_background_hook_process_group(initialized_archive
'echo $$ > "$test_dir/daemon.pid"',
'echo $! > "$test_dir/daemon-child.pid"',
'echo ready > "$test_dir/daemon.ready"',
"printf '%s\\n' '{\"type\":\"ProcessReady\"}'",
"trap 'echo cleaned > \"$test_dir/daemon.cleaned\"; exit 0' TERM INT",
"wait",
"",

View File

@ -1,7 +1,10 @@
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
import asyncio
import pytest
from asgiref.sync import sync_to_async
from django.conf import settings
from django.db import connections
@ -17,8 +20,37 @@ def test_archivebox_db_path_accepts_collection_or_database_path(tmp_path: Path)
assert archivebox_db_path(database_path) == database_path
def _reset_thread_sensitive_default_connection() -> None:
"""Discard the default connection owned by asgiref's thread-sensitive worker."""
def reset_connection() -> None:
connections["default"].close()
del connections._connections.default
asyncio.run(sync_to_async(reset_connection, thread_sensitive=True)())
def _thread_sensitive_database_path() -> str:
def database_path() -> str:
with connections["default"].cursor() as cursor:
return str(cursor.execute("PRAGMA database_list").fetchone()[2])
return asyncio.run(sync_to_async(database_path, thread_sensitive=True)())
@pytest.mark.django_db(transaction=True)
def test_use_archivebox_db_restores_thread_sensitive_connection(tmp_path: Path) -> None:
original_database_path = _thread_sensitive_database_path()
with use_archivebox_db(tmp_path):
assert _thread_sensitive_database_path() == str(tmp_path / "index.sqlite3")
assert _thread_sensitive_database_path() == original_database_path
@contextmanager
def use_archivebox_db(path: str | Path = ".") -> Iterator[None]:
_reset_thread_sensitive_default_connection()
connection = connections["default"]
original_name = connection.settings_dict["NAME"]
original_database_name = connections.databases["default"]["NAME"]
@ -34,6 +66,7 @@ def use_archivebox_db(path: str | Path = ".") -> Iterator[None]:
try:
yield
finally:
_reset_thread_sensitive_default_connection()
connections["default"].close()
connections.databases["default"]["NAME"] = original_database_name
settings.DATABASES["default"]["NAME"] = original_setting_name