Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 2 additions & 1 deletion src/pt_snap_cli/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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_%'"
Expand Down
35 changes: 35 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"""Test configuration."""

import gc
from functools import wraps

import pytest

from tests._fixture_provenance import FixtureProvenanceError, verify_snapshot_fixtures
Expand All @@ -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()
18 changes: 12 additions & 6 deletions tests/core/test_context_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)
Expand All @@ -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()

Expand All @@ -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(
Expand All @@ -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"

Expand All @@ -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

Expand All @@ -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")
Expand Down
11 changes: 6 additions & 5 deletions tests/core/test_import_metadata.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import sqlite3
from contextlib import closing
from dataclasses import FrozenInstanceError
from pathlib import Path

Expand All @@ -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)"
)
Expand Down Expand Up @@ -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)")

Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions tests/core/test_import_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import importlib
import pickle
import sys
from contextlib import closing
from pathlib import Path

import pytest
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)"
)
Expand Down
2 changes: 2 additions & 0 deletions tests/core/test_overview_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 2 additions & 0 deletions tests/core/test_query_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 2 additions & 0 deletions tests/core/test_report_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
7 changes: 5 additions & 2 deletions tests/query/test_callstack_schema_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import hashlib
import sqlite3
from contextlib import closing
from pathlib import Path

import pytest
Expand All @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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})
Expand Down
7 changes: 4 additions & 3 deletions tests/query/test_executor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tests for query executor."""

import sqlite3
from contextlib import closing

import pytest

Expand Down Expand Up @@ -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))
Expand All @@ -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))
Expand All @@ -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(
Expand Down
5 changes: 4 additions & 1 deletion tests/query/test_memory_peak_cte.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]
Expand Down
2 changes: 2 additions & 0 deletions tests/query/test_query_completeness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()


Expand Down
5 changes: 4 additions & 1 deletion tests/query/test_query_max_rows_pushdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from __future__ import annotations

import sqlite3
from contextlib import closing
from pathlib import Path

import pytest
Expand All @@ -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:
Expand Down Expand Up @@ -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),
Expand Down
Loading
Loading