From 29b09e63909e0c67df6b56b74a613ba2311574b2 Mon Sep 17 00:00:00 2001 From: codeasier Date: Sat, 3 Oct 2026 11:04:28 +0800 Subject: [PATCH] fix(resources): close completion and test-owned database handles --- pyproject.toml | 4 +++ src/pt_snap_cli/completion.py | 3 +- tests/conftest.py | 35 +++++++++++++++++++++ tests/core/test_context_cache.py | 18 +++++++---- tests/core/test_import_metadata.py | 11 ++++--- tests/core/test_import_service.py | 5 +-- tests/core/test_overview_service.py | 2 ++ tests/core/test_query_service.py | 2 ++ tests/core/test_report_service.py | 2 ++ tests/query/test_callstack_schema_compat.py | 7 +++-- tests/query/test_executor.py | 7 +++-- tests/query/test_memory_peak_cte.py | 5 ++- tests/query/test_query_completeness.py | 2 ++ tests/query/test_query_max_rows_pushdown.py | 5 ++- tests/skills/test_preflight_contract.py | 7 +++-- tests/snapshot/test_snapshot2db_runtime.py | 25 ++++++++------- tests/test_completion.py | 25 +++++++++++++++ tests/test_context.py | 3 +- tests/test_contract_cli_api.py | 5 ++- tests/test_leak_query_window.py | 5 ++- 20 files changed, 139 insertions(+), 39 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 3c05a93..a999f7f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -93,6 +93,10 @@ testpaths = ["tests"] python_files = ["test_*.py"] python_functions = ["test_*"] addopts = "-v --tb=short" +filterwarnings = [ + "error::ResourceWarning", + "error::pytest.PytestUnraisableExceptionWarning", +] [tool.basedpyright] pythonVersion = "3.13" diff --git a/src/pt_snap_cli/completion.py b/src/pt_snap_cli/completion.py index 1462b46..abbd9cc 100644 --- a/src/pt_snap_cli/completion.py +++ b/src/pt_snap_cli/completion.py @@ -4,6 +4,7 @@ import json import os +from contextlib import closing from pathlib import Path from pt_snap_cli.config import DB_PATH_KEY, Config @@ -75,7 +76,7 @@ def complete_device_ids() -> list[str]: try: uri = f"file:{db_path}?mode=ro" - with sqlite3.connect(uri, uri=True) as conn: + with closing(sqlite3.connect(uri, uri=True)) as conn: cursor = conn.cursor() cursor.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'trace_entry_%'" diff --git a/tests/conftest.py b/tests/conftest.py index 5e9767a..587bc27 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,8 @@ """Test configuration.""" +import gc +from functools import wraps + import pytest from tests._fixture_provenance import FixtureProvenanceError, verify_snapshot_fixtures @@ -16,3 +19,35 @@ def pytest_sessionstart(session: pytest.Session) -> None: def pytest_configure(config: pytest.Config) -> None: """Configure pytest.""" config.addinivalue_line("markers", "slow: mark test as slow") + + +@pytest.fixture +def owned_service_instances(request, monkeypatch): + """Own services constructed directly by an opted-in test module. + + Only replace that test module's imported constructor bindings. Production + constructors (including CLI-owned services) and lifecycle tests are untouched. + Each successful construction registers its public close method immediately, + including when the test later raises. Do not use in resource-lifetime tests. + """ + + def managed_factory(constructor): + @wraps(constructor) + def create(*args, **kwargs): + instance = constructor(*args, **kwargs) + request.addfinalizer(instance.close) + return instance + + return create + + for name in ("SnapshotAnalyzer", "QueryService", "OverviewService", "ReportService"): + constructor = getattr(request.module, name, None) + if constructor is not None: + monkeypatch.setattr(request.module, name, managed_factory(constructor)) + + +@pytest.fixture(autouse=True) +def collect_test_resources(): + """Attribute cyclic-resource warnings to their owning test, not a later one.""" + yield + gc.collect() diff --git a/tests/core/test_context_cache.py b/tests/core/test_context_cache.py index c87b105..0214dd2 100644 --- a/tests/core/test_context_cache.py +++ b/tests/core/test_context_cache.py @@ -33,9 +33,10 @@ def _make_invalid_db(tmp_path: Path, name: str = "invalid.db") -> Path: class TestContextCache: - def test_get_creates_context(self, tmp_path: Path) -> None: + def test_get_creates_context(self, tmp_path: Path, request) -> None: db_path = _make_db(tmp_path) cache = ContextCache(maxsize=4) + request.addfinalizer(cache.close) ctx = cache.get(db_path) @@ -44,9 +45,10 @@ def test_get_creates_context(self, tmp_path: Path) -> None: assert ctx.device_ids == [0] assert len(cache) == 1 - def test_get_returns_cached_context_on_second_call(self, tmp_path: Path) -> None: + def test_get_returns_cached_context_on_second_call(self, tmp_path: Path, request) -> None: db_path = _make_db(tmp_path) cache = ContextCache(maxsize=4) + request.addfinalizer(cache.close) first = cache.get(db_path) second = cache.get(db_path) @@ -71,10 +73,11 @@ def test_get_propagates_schema_errors(self, tmp_path: Path) -> None: with pytest.raises(SchemaVersionError): cache.get(bad_db) - def test_same_mtime_replacement_refreshes_cached_context(self, tmp_path: Path) -> None: + def test_same_mtime_replacement_refreshes_cached_context(self, tmp_path: Path, request) -> None: """Replacing a database with the same mtime must refresh its context.""" db_path = _make_db(tmp_path) cache = ContextCache(maxsize=4) + request.addfinalizer(cache.close) first = cache.get(db_path) original_stat = db_path.stat() @@ -94,7 +97,7 @@ def test_same_mtime_replacement_refreshes_cached_context(self, tmp_path: Path) - assert second is not first assert second.device_ids == [1] - def test_replaced_database_redetects_callstack_layout(self, tmp_path: Path) -> None: + def test_replaced_database_redetects_callstack_layout(self, tmp_path: Path, request) -> None: db_path = tmp_path / "layout.db" conn = sqlite3.connect(str(db_path)) conn.execute( @@ -105,6 +108,7 @@ def test_replaced_database_redetects_callstack_layout(self, tmp_path: Path) -> N conn.close() cache = ContextCache(maxsize=4) + request.addfinalizer(cache.close) first = cache.get(db_path) assert first.callstack_layout == "v1" @@ -123,9 +127,10 @@ def test_replaced_database_redetects_callstack_layout(self, tmp_path: Path) -> N assert second is not first assert second.callstack_layout == "v2" - def test_invalidate_path_drops_entry(self, tmp_path: Path) -> None: + def test_invalidate_path_drops_entry(self, tmp_path: Path, request) -> None: db_path = _make_db(tmp_path) cache = ContextCache(maxsize=4) + request.addfinalizer(cache.close) ctx = cache.get(db_path) assert len(cache) == 1 @@ -147,8 +152,9 @@ def test_invalidate_all_drops_every_entry(self, tmp_path: Path) -> None: cache.invalidate() assert len(cache) == 0 - def test_lru_eviction(self, tmp_path: Path) -> None: + def test_lru_eviction(self, tmp_path: Path, request) -> None: cache = ContextCache(maxsize=2) + request.addfinalizer(cache.close) db_a = _make_db(tmp_path, "a.db") db_b = _make_db(tmp_path, "b.db") db_c = _make_db(tmp_path, "c.db") diff --git a/tests/core/test_import_metadata.py b/tests/core/test_import_metadata.py index a116017..3a1f0fc 100644 --- a/tests/core/test_import_metadata.py +++ b/tests/core/test_import_metadata.py @@ -1,6 +1,7 @@ from __future__ import annotations import sqlite3 +from contextlib import closing from dataclasses import FrozenInstanceError from pathlib import Path @@ -15,7 +16,7 @@ def _create_snapshot_db(path: Path) -> Path: - with sqlite3.connect(path) as conn: + with closing(sqlite3.connect(path)) as conn, conn: conn.execute( "CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)" ) @@ -96,7 +97,7 @@ def test_inspect_reports_missing_metadata(tmp_path: Path) -> None: def test_inspect_reports_invalid_metadata_columns(tmp_path: Path) -> None: db_path = _create_snapshot_db(tmp_path / "invalid.db") - with sqlite3.connect(db_path) as conn: + with closing(sqlite3.connect(db_path)) as conn, conn: conn.execute("CREATE TABLE pt_snap_metadata (id INTEGER)") conn.execute("INSERT INTO pt_snap_metadata VALUES (1)") @@ -110,7 +111,7 @@ def test_inspect_reports_unsupported_metadata_version(tmp_path: Path) -> None: db_path = _create_snapshot_db(tmp_path / "future.db") service = ImportMetadataService() service.write(db_path, _metadata()) - with sqlite3.connect(db_path) as conn: + with closing(sqlite3.connect(db_path)) as conn, conn: conn.execute("UPDATE pt_snap_metadata SET metadata_schema_version = 999") inspection = service.inspect(db_path) @@ -123,7 +124,7 @@ def test_inspect_rejects_non_utc_completed_at(tmp_path: Path) -> None: db_path = _create_snapshot_db(tmp_path / "non-utc.db") service = ImportMetadataService() service.write(db_path, _metadata()) - with sqlite3.connect(db_path) as conn: + with closing(sqlite3.connect(db_path)) as conn, conn: conn.execute("UPDATE pt_snap_metadata SET completed_at = '2026-07-18T18:00:00+08:00'") inspection = service.inspect(db_path) @@ -134,7 +135,7 @@ def test_inspect_rejects_non_utc_completed_at(tmp_path: Path) -> None: def test_inspect_rejects_duplicate_metadata_rows(tmp_path: Path) -> None: db_path = _create_snapshot_db(tmp_path / "duplicate.db") - with sqlite3.connect(db_path) as conn: + with closing(sqlite3.connect(db_path)) as conn, conn: conn.execute(""" CREATE TABLE pt_snap_metadata ( id INTEGER, diff --git a/tests/core/test_import_service.py b/tests/core/test_import_service.py index 093ccf5..fa5ea72 100644 --- a/tests/core/test_import_service.py +++ b/tests/core/test_import_service.py @@ -3,6 +3,7 @@ import importlib import pickle import sys +from contextlib import closing from pathlib import Path import pytest @@ -347,7 +348,7 @@ def test_malformed_metadata_rebuilds_database( first = service.import_snapshot( ImportOptions(snapshot_file=EMPTY_CACHE_SNAPSHOT, output_dir=tmp_path, set_focus=False) ) - with sqlite3.connect(first.db_path) as conn: + with closing(sqlite3.connect(first.db_path)) as conn, conn: conn.execute("UPDATE pt_snap_metadata SET source_sha256 = 'invalid'") original_dump = service._backend.dump_to_db @@ -375,7 +376,7 @@ def test_legacy_database_rebuilds_once_then_reuses(tmp_path: Path) -> None: import_service_cls = _import_service_type() service = import_service_cls() legacy_db = tmp_path / f"{EMPTY_CACHE_SNAPSHOT.name}.db" - with sqlite3.connect(legacy_db) as conn: + with closing(sqlite3.connect(legacy_db)) as conn, conn: conn.execute( "CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)" ) diff --git a/tests/core/test_overview_service.py b/tests/core/test_overview_service.py index 8d8bcf3..93b5517 100644 --- a/tests/core/test_overview_service.py +++ b/tests/core/test_overview_service.py @@ -7,6 +7,8 @@ from pt_snap_cli.core import DatabaseSchemaError, FocusNotConfiguredError, OverviewService from pt_snap_cli.core.import_metadata import ImportMetadataService +pytestmark = pytest.mark.usefixtures("owned_service_instances") + @pytest.fixture(autouse=True) def _isolate(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): diff --git a/tests/core/test_query_service.py b/tests/core/test_query_service.py index db86db9..743da8f 100644 --- a/tests/core/test_query_service.py +++ b/tests/core/test_query_service.py @@ -16,6 +16,8 @@ from pt_snap_cli.query.config import QueryParameter, QueryTemplate from pt_snap_cli.query.registry import QueryRegistry, register_query +pytestmark = pytest.mark.usefixtures("owned_service_instances") + @pytest.fixture(autouse=True) def mock_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): diff --git a/tests/core/test_report_service.py b/tests/core/test_report_service.py index e0c9d2f..88e2a83 100644 --- a/tests/core/test_report_service.py +++ b/tests/core/test_report_service.py @@ -8,6 +8,8 @@ from pt_snap_cli.core.report_service import ReportService from pt_snap_cli.query.registry import QueryRegistry, _load_all_templates +pytestmark = pytest.mark.usefixtures("owned_service_instances") + @pytest.fixture(autouse=True) def _reload_query_templates(): diff --git a/tests/query/test_callstack_schema_compat.py b/tests/query/test_callstack_schema_compat.py index 315b16f..2cbfa53 100644 --- a/tests/query/test_callstack_schema_compat.py +++ b/tests/query/test_callstack_schema_compat.py @@ -4,6 +4,7 @@ import hashlib import sqlite3 +from contextlib import closing from pathlib import Path import pytest @@ -14,6 +15,8 @@ from pt_snap_cli.query.executor import QueryExecutionError, QueryExecutor from pt_snap_cli.query.registry import QueryRegistry, _load_all_templates, get_query +pytestmark = pytest.mark.usefixtures("owned_service_instances") + @pytest.fixture(autouse=True) def _reload_query_templates() -> None: @@ -243,7 +246,7 @@ def missing_callstack_db(request: pytest.FixtureRequest, tmp_path: Path) -> Path layout = request.param create = create_v1_db if layout == "v1" else create_v2_db path = create(tmp_path / f"missing-{layout}.db") - with sqlite3.connect(path) as conn: + with closing(sqlite3.connect(path)) as conn, conn: conn.execute("DELETE FROM block_0") conn.execute("DELETE FROM trace_entry_0") # Empty text, NULL text, NULL ID, dangling ID, and missing alloc event. @@ -324,7 +327,7 @@ def test_missing_callstacks_merge_before_ranking_and_preserve_totals( def test_active_memory_v2_keeps_nonempty_callstack_ids_separate(v2_db: Path) -> None: - with sqlite3.connect(v2_db) as conn: + with closing(sqlite3.connect(v2_db)) as conn, conn: conn.execute("INSERT INTO callstack (id, callstack) VALUES (99, 'train.py:10')") conn.execute("UPDATE trace_entry_0 SET callstackId = 99 WHERE id = 4") rows = _execute(v2_db, "active_memory_callstack_at_event", {"event_id": 5, "top_n": -1}) diff --git a/tests/query/test_executor.py b/tests/query/test_executor.py index e4c4a92..fc4c119 100644 --- a/tests/query/test_executor.py +++ b/tests/query/test_executor.py @@ -1,6 +1,7 @@ """Tests for query executor.""" import sqlite3 +from contextlib import closing import pytest @@ -396,7 +397,7 @@ def test_execute_on_all_devices_empty_device_list(self): def test_legacy_callstack_schema_error_is_actionable(self, tmp_path): db_path = tmp_path / "legacy.db" - with sqlite3.connect(db_path) as conn: + with closing(sqlite3.connect(db_path)) as conn, conn: conn.execute("CREATE TABLE dictionary (table_name TEXT)") conn.execute("CREATE TABLE trace_entry_0 " "(id INTEGER, callstack TEXT)") executor = QueryExecutor(Context(db_path)) @@ -412,7 +413,7 @@ def test_legacy_callstack_schema_error_is_actionable(self, tmp_path): def test_qualified_legacy_callstack_schema_error_is_actionable(self, tmp_path): db_path = tmp_path / "legacy-qualified.db" - with sqlite3.connect(db_path) as conn: + with closing(sqlite3.connect(db_path)) as conn, conn: conn.execute("CREATE TABLE dictionary (table_name TEXT)") conn.execute("CREATE TABLE trace_entry_0 (id INTEGER)") executor = QueryExecutor(Context(db_path)) @@ -428,7 +429,7 @@ def test_qualified_legacy_callstack_schema_error_is_actionable(self, tmp_path): def test_variant_template_uses_inline_sql_on_v1_database(self, tmp_path): db_path = tmp_path / "v1.db" - with sqlite3.connect(db_path) as conn: + with closing(sqlite3.connect(db_path)) as conn, conn: conn.execute("CREATE TABLE dictionary (table_name TEXT)") conn.execute("CREATE TABLE trace_entry_0 (id INTEGER, size INTEGER, callstack TEXT)") conn.execute( diff --git a/tests/query/test_memory_peak_cte.py b/tests/query/test_memory_peak_cte.py index 78a8b53..a0165bf 100644 --- a/tests/query/test_memory_peak_cte.py +++ b/tests/query/test_memory_peak_cte.py @@ -196,6 +196,7 @@ def test_memory_peak_cte_matches_original( def test_memory_peak_null_start_and_end_runs_via_query_service( memory_peak_db: Path, + request, ) -> None: """End-to-end smoke test: the rewritten template is reachable through the QueryService -> QueryExecutor pipeline used by the CLI and @@ -206,7 +207,9 @@ def test_memory_peak_null_start_and_end_runs_via_query_service( config = Config() config.write_project_focus(memory_peak_db, device_id=0) - result = QueryService().execute_query("memory_peak") + service = QueryService() + request.addfinalizer(service.close) + result = service.execute_query("memory_peak") assert result.total == 1 row = result.rows[0] diff --git a/tests/query/test_query_completeness.py b/tests/query/test_query_completeness.py index 0262fe8..245eb88 100644 --- a/tests/query/test_query_completeness.py +++ b/tests/query/test_query_completeness.py @@ -27,6 +27,8 @@ ) from pt_snap_cli.query.registry import QueryRegistry, _load_all_templates, register_query +pytestmark = pytest.mark.usefixtures("owned_service_instances") + runner = CliRunner() diff --git a/tests/query/test_query_max_rows_pushdown.py b/tests/query/test_query_max_rows_pushdown.py index dbf3b28..3230b77 100644 --- a/tests/query/test_query_max_rows_pushdown.py +++ b/tests/query/test_query_max_rows_pushdown.py @@ -8,6 +8,7 @@ from __future__ import annotations import sqlite3 +from contextlib import closing from pathlib import Path import pytest @@ -18,6 +19,8 @@ from pt_snap_cli.query.executor import QueryExecutor from pt_snap_cli.query.registry import QueryRegistry, _load_all_templates +pytestmark = pytest.mark.usefixtures("owned_service_instances") + @pytest.fixture(autouse=True) def _isolate_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -193,7 +196,7 @@ def test_min_size_filter_combines_with_limit(self, callstack_db: Path) -> None: assert len(rows) == 2 def test_missing_callstack_uses_placeholder(self, callstack_db: Path) -> None: - with sqlite3.connect(callstack_db) as conn: + with closing(sqlite3.connect(callstack_db)) as conn, conn: conn.execute( "INSERT INTO trace_entry_0 (id, size, callstackId) VALUES (?, ?, ?)", (100, 1, 99), diff --git a/tests/skills/test_preflight_contract.py b/tests/skills/test_preflight_contract.py index 794915e..a60b073 100644 --- a/tests/skills/test_preflight_contract.py +++ b/tests/skills/test_preflight_contract.py @@ -4,6 +4,7 @@ import re import shlex import sqlite3 +from contextlib import closing from pathlib import Path import pytest @@ -96,7 +97,7 @@ def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: monkeypatch.delenv("PT_SNAP_DB_PATH", raising=False) monkeypatch.delenv("PT_SNAP_SKILLS_DIR", raising=False) path = tmp_path / "preflight.db" - with sqlite3.connect(path) as conn: + with closing(sqlite3.connect(path)) as conn, conn: conn.execute( "CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)" ) @@ -169,11 +170,11 @@ def test_overview_status_drives_preflight_even_with_outer_success(db: Path, stat service = ImportMetadataService() service.write(db, service.build_metadata(source, service.calculate_sha256(source), None)) elif state == "invalid": - with sqlite3.connect(db) as conn: + with closing(sqlite3.connect(db)) as conn, conn: conn.execute("CREATE TABLE pt_snap_metadata (id INTEGER)") conn.execute("INSERT INTO pt_snap_metadata VALUES (1)") elif state == "schema-error": - with sqlite3.connect(db) as conn: + with closing(sqlite3.connect(db)) as conn, conn: conn.execute("DROP TABLE dictionary") result = runner.invoke(app, ["overview", str(db), "--json"]) if state == "schema-error": diff --git a/tests/snapshot/test_snapshot2db_runtime.py b/tests/snapshot/test_snapshot2db_runtime.py index 0c17a7e..a7bac9a 100644 --- a/tests/snapshot/test_snapshot2db_runtime.py +++ b/tests/snapshot/test_snapshot2db_runtime.py @@ -1,5 +1,6 @@ import pickle import sqlite3 +from contextlib import closing from pathlib import Path import pytest @@ -51,7 +52,7 @@ def test_snapshot2db(dump_database): assert result is True assert database.exists() - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: assert connection.execute("SELECT COUNT(*) FROM trace_entry_0").fetchone()[0] == 8189 assert connection.execute("SELECT COUNT(*) FROM block_0").fetchone()[0] == 3219 @@ -127,7 +128,7 @@ def dump_rows(database, *, eager): else: monkeypatch.setattr(snapshot2db, "replay_snapshot", original_replay) assert snapshot2db.dump(snapshot, database, 0) - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: return connection.execute( "SELECT t.id, t.action, t.address, t.size, t.stream, " "t.allocated, t.active, t.reserved, c.callstack " @@ -247,7 +248,7 @@ def test_failed_dump_preserves_existing_database(tmp_path): database = tmp_path / "existing.db" with snapshot.open("wb") as stream: pickle.dump(representation, stream) - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: connection.execute("CREATE TABLE marker (value TEXT)") connection.execute("INSERT INTO marker VALUES ('preserved')") connection.commit() @@ -255,7 +256,7 @@ def test_failed_dump_preserves_existing_database(tmp_path): with pytest.raises(KeyError, match="name"): snapshot2db.dump(snapshot, database, 0) - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: assert connection.execute("SELECT value FROM marker").fetchone() == ("preserved",) @@ -271,7 +272,7 @@ def test_expandable_snapshot2db(dump_database): assert result is True assert database.exists() - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: assert connection.execute("SELECT COUNT(*) FROM trace_entry_0").fetchone()[0] == 8134 assert connection.execute("SELECT COUNT(*) FROM block_0").fetchone()[0] == 3219 @@ -303,7 +304,7 @@ def test_snapshot2db_dumps_oom_event_without_addr(tmp_path: Path): restore_logs() assert result is True - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: action, address, size = connection.execute( "SELECT action, address, size FROM trace_entry_0" ).fetchone() @@ -318,7 +319,7 @@ def test_dump_all_multiple_device_snapshot(dump_database): assert result is True assert database.exists() - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: tables = { row[0] for row in connection.execute( @@ -352,7 +353,7 @@ def test_database_matches_pre_relocation_golden(dump_database, fixture_name, dev block_table = f"block_{device}" assert result is True - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: rows = ( connection.execute(f"SELECT COUNT(*) FROM {trace_table}").fetchone()[0], connection.execute(f"SELECT COUNT(*) FROM {block_table}").fetchone()[0], @@ -395,7 +396,7 @@ def test_database_schema_and_action_state_mapping_are_exact(dump_database): assert RUNTIME_ACTION_VALUE_MAP == ACTION_VALUE_MAP assert RUNTIME_BLOCK_STATE_VALUE_MAP == BLOCK_STATE_VALUE_MAP - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: assert connection.execute("PRAGMA table_info(callstack)").fetchall() == CALLSTACK_SCHEMA for device in (0, 1): assert ( @@ -423,7 +424,7 @@ def test_database_schema_and_action_state_mapping_are_exact(dump_database): def test_multi_device_database_rows_are_isolated(dump_database): _, database = dump_database("snapshot_with_multi_devices.pkl") - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: device_zero = connection.execute( "SELECT COUNT(*), SUM(size), MAX(reserved) FROM trace_entry_0" ).fetchone() @@ -438,7 +439,7 @@ def test_multi_device_database_rows_are_isolated(dump_database): def test_callstack_serialization_preserves_frame_order(dump_database): _, database = dump_database("snapshot_1768383987920985470.pkl", 0) - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: callstack = connection.execute( "SELECT c.callstack FROM trace_entry_0 t " "JOIN callstack c ON c.id = t.callstackId " @@ -452,7 +453,7 @@ def test_callstack_serialization_preserves_frame_order(dump_database): def test_callstack_table_is_deduplicated_and_covers_every_event(dump_database): _, database = dump_database("snapshot_1768383987920985470.pkl", 0) - with sqlite3.connect(database) as connection: + with closing(sqlite3.connect(database)) as connection, connection: rows, distinct_ids, distinct_texts = connection.execute( "SELECT COUNT(*), COUNT(DISTINCT id), COUNT(DISTINCT callstack) FROM callstack" ).fetchone() diff --git a/tests/test_completion.py b/tests/test_completion.py index 959824b..0d55e14 100644 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -105,6 +105,31 @@ def test_returns_supported_hosts(self) -> None: class TestCompleteDeviceIds: + @pytest.mark.parametrize("valid", [True, False]) + def test_completion_closes_connection(self, tmp_path, monkeypatch, valid): + db_path = tmp_path / "completion.db" + if valid: + _create_sample_db(db_path) + else: + db_path.write_text("not SQLite") + monkeypatch.setenv(ENV_DB_PATH, str(db_path)) + connections = [] + original_connect = sqlite3.connect + + def tracked_connect(*args, **kwargs): + conn = original_connect(*args, **kwargs) + connections.append(conn) + return conn + + monkeypatch.setattr(sqlite3, "connect", tracked_connect) + assert complete_device_ids() == (["0", "1"] if valid else []) + assert len(connections) == 1 + try: + with pytest.raises(sqlite3.ProgrammingError, match="closed"): + connections[0].execute("SELECT 1") + finally: + connections[0].close() + def test_returns_device_ids_from_db(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): db_path = _create_sample_db(tmp_path / "test.db") monkeypatch.setenv(ENV_DB_PATH, str(db_path)) diff --git a/tests/test_context.py b/tests/test_context.py index e77fa6d..5ce4638 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -2,6 +2,7 @@ import sqlite3 import tempfile +from contextlib import closing from pathlib import Path import pytest @@ -134,7 +135,7 @@ def test_device_ids_skip_non_numeric_suffix(self, tmp_path: Path) -> None: def test_device_trace_bounds_empty_and_populated(self, valid_db: Path) -> None: ctx = Context(valid_db) assert ctx.device_trace_bounds() == [(0, None, None)] - with sqlite3.connect(str(valid_db)) as conn: + with closing(sqlite3.connect(str(valid_db))) as conn, conn: conn.execute("INSERT INTO trace_entry_0 (id, action) VALUES (3, 4), (9, 4)") conn.commit() assert Context(valid_db).device_trace_bounds() == [(0, 3, 9)] diff --git a/tests/test_contract_cli_api.py b/tests/test_contract_cli_api.py index 41dd866..65bb194 100644 --- a/tests/test_contract_cli_api.py +++ b/tests/test_contract_cli_api.py @@ -13,6 +13,7 @@ import inspect import json import sqlite3 +from contextlib import closing from pathlib import Path from unittest.mock import patch @@ -28,6 +29,8 @@ runner = CliRunner() +pytestmark = pytest.mark.usefixtures("owned_service_instances") + def create_contract_db(db_path: Path) -> Path: """Create a tiny snapshot database shared by CLI and API contract paths.""" @@ -632,7 +635,7 @@ def test_query_json_contract_matches_api_semantics(contract_db: Path) -> None: @pytest.mark.parametrize("layout", ["v1", "v2"]) def test_missing_callstack_query_json_contract(contract_db: Path, layout: str) -> None: name = "active_memory_callstack_at_event" - with sqlite3.connect(contract_db) as conn: + with closing(sqlite3.connect(contract_db)) as conn, conn: if layout == "v1": conn.executemany( "INSERT INTO trace_entry_0 (id, callstack) VALUES (?, ?)", diff --git a/tests/test_leak_query_window.py b/tests/test_leak_query_window.py index 34b9eb9..929bc6c 100644 --- a/tests/test_leak_query_window.py +++ b/tests/test_leak_query_window.py @@ -3,6 +3,7 @@ import json import shlex import sqlite3 +from contextlib import closing from pathlib import Path import pytest @@ -12,6 +13,8 @@ from pt_snap_cli.cli import app from pt_snap_cli.core import TemplateRenderError +pytestmark = pytest.mark.usefixtures("owned_service_instances") + ROOT = Path(__file__).resolve().parents[1] runner = CliRunner() CANDIDATE_COUNT = 325 @@ -25,7 +28,7 @@ def leak_db(tmp_path, monkeypatch): monkeypatch.delenv("PT_SNAP_QUERY_TIMEOUT", raising=False) monkeypatch.setattr(Path, "home", lambda: tmp_path) path = tmp_path / "leak-window.db" - with sqlite3.connect(path) as conn: + with closing(sqlite3.connect(path)) as conn, conn: conn.executescript(""" CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT); CREATE TABLE trace_entry_0 (id INTEGER PRIMARY KEY, callstack TEXT);