diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a479c2..72ec78f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -122,8 +122,12 @@ pytest subprocesses and import handling, including fixtures, parametrized tests, package metadata, and instrumentation in spawned child processes. Trailmark checks the clean baseline and each distinct instrumented test ordering before mutating, skips the redundant coverage pre-scan, preserves exact parameter IDs, -and rejects skipped instrumentation. Performance regressions should use -deterministic work bounds rather than wall-clock thresholds in the mutation suite. +and rejects skipped instrumentation. Tests use deterministic work bounds rather +than wall-clock thresholds. The test suite has no elapsed-time assertions, +pytest timeout markers, or test subprocess deadlines. Hypothesis deadlines and +its generation-speed health check are disabled. Test product timeout behavior +with a simulated clock and process; keep optional wall-clock measurements in +`tests/benchmark_analysis.py` or `tests/smoke_binary_projects.py`. The adapter uses private plugin APIs; its control tests must pass before upgrading the plugin. diff --git a/pyproject.toml b/pyproject.toml index a60c152..386e6d1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -73,7 +73,6 @@ dev = [ "pytest>=9.2.0", "pytest-cov>=7.1.0", "ruff>=0.17.6,<1.0", - "pytest-timeout>=2.4,<3", "ty>=0.0.107,<0.1", ] diff --git a/tests/binary_oracle.py b/tests/binary_oracle.py index 5cc2231..6a1bf38 100644 --- a/tests/binary_oracle.py +++ b/tests/binary_oracle.py @@ -29,7 +29,7 @@ def offset(self, address: int) -> int: def _run(command: list[str]) -> str: - return subprocess.run(command, check=True, capture_output=True, text=True, timeout=30).stdout # noqa: S603 + return subprocess.run(command, check=True, capture_output=True, text=True).stdout # noqa: S603 def _field(body: str, name: str) -> int: diff --git a/tests/conftest.py b/tests/conftest.py index fbbfec9..b1751b3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,10 @@ import os import pytest +from hypothesis import HealthCheck, settings + +settings.register_profile("trailmark", deadline=None, suppress_health_check=[HealthCheck.too_slow]) +settings.load_profile("trailmark") def pytest_sessionstart(session: pytest.Session) -> None: @@ -15,13 +19,3 @@ def pytest_sessionstart(session: pytest.Session) -> None: or "PYTEST_GREMLINS_SOURCES_FILE" in os.environ ): raise pytest.UsageError("Snapshot updates are disabled in CI and mutation testing") - - -@pytest.fixture(scope="session") -def compiled_verus() -> None: - """Compile outside tests that bound parser traversal time.""" - from tree_sitter import Language - - from trailmark.tree_sitter_custom.verus import language - - Language(language()) diff --git a/tests/parse_work.py b/tests/parse_work.py new file mode 100644 index 0000000..740b472 --- /dev/null +++ b/tests/parse_work.py @@ -0,0 +1,36 @@ +"""Deterministic Python work counts for parser scaling regressions.""" + +import sys +from collections.abc import Callable +from pathlib import Path +from types import FrameType + +from trailmark.models import CodeGraph +from trailmark.parse import parse_file + +type _Trace = Callable[[FrameType, str, object], _Trace | None] + + +def parse_work(path: Path) -> tuple[CodeGraph, int]: + """Count parser line events, including code instrumented in temporary files. + + This measures Python traversal work; native grammar execution is excluded. + """ + work = 0 + + def count(frame: FrameType, event: str, argument: object) -> _Trace: + nonlocal work + if event == "line": + work += 1 + return count + + def select(frame: FrameType, event: str, argument: object) -> _Trace | None: + return count if frame.f_globals.get("__name__", "").startswith("trailmark.") else None + + previous = sys.gettrace() + try: + sys.settrace(select) + graph = parse_file(str(path)) + finally: + sys.settrace(previous) + return graph, work diff --git a/tests/test_binary_models.py b/tests/test_binary_models.py index 03b957f..df0ae94 100644 --- a/tests/test_binary_models.py +++ b/tests/test_binary_models.py @@ -3,14 +3,14 @@ from __future__ import annotations import json -import sys -import time from dataclasses import FrozenInstanceError, replace from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock, Mock import pytest -from trailmark.analysis.native_binary import _restore_functions +from trailmark.analysis.native_binary import _restore_functions, tools from trailmark.analysis.native_binary.decoder import _tail_calls from trailmark.analysis.native_binary.formats import Function, Image, Span, Target from trailmark.analysis.native_binary.mapping import SourceResolver @@ -428,27 +428,79 @@ def test_import_options_reject_mutable_or_unsupported_configuration() -> None: BinaryImportOptions(limits=None) # ty: ignore[invalid-argument-type] -def test_host_tool_output_budget_counts_both_pipes() -> None: +def _host_process(monkeypatch: pytest.MonkeyPatch) -> tuple[Mock, MagicMock]: + """Model ready pipes and process cleanup without waiting for a real child.""" + process = Mock(stdout=Mock(), stderr=Mock(), returncode=None) + process.poll.side_effect = lambda: process.returncode + + def wait(timeout: float | None = None) -> int: + process.returncode = -9 + return -9 + + process.wait.side_effect = wait + selector = MagicMock() + selector.__enter__.return_value = selector + selector.get_map.return_value = True + monkeypatch.setattr(tools.subprocess, "Popen", Mock(return_value=process)) + monkeypatch.setattr(tools.selectors, "DefaultSelector", lambda: selector) + monkeypatch.setattr(tools, "time", SimpleNamespace(monotonic=lambda: 0.0)) + return process, selector + + +def test_host_tool_output_budget_counts_both_pipes(monkeypatch: pytest.MonkeyPatch) -> None: + process, selector = _host_process(monkeypatch) + keys = [ + SimpleNamespace(fd=1, fileobj=process.stdout, data="stdout"), + SimpleNamespace(fd=2, fileobj=process.stderr, data="stderr"), + ] + selector.select.side_effect = [[(key, 1) for key in keys]] + output = {1: b"a" * 100, 2: b"b" * 100} + + def read(fd: int, size: int) -> bytes: + chunk, output[fd] = output[fd][:size], output[fd][size:] + return chunk + + monkeypatch.setattr(tools.os, "read", read) limits = BinaryLimits(max_output_bytes=128) - result = run_tool( - [sys.executable, "-c", "import os; os.write(1,b'a'*100); os.write(2,b'b'*100)"], - limits, - time.monotonic() + 5, - ) + result = run_tool(["tool"], limits, 5.0) assert result.diagnostic is not None assert result.diagnostic.code == "output_limit" - assert len(result.stdout) + len(result.stderr) == 128 + assert (result.stdout, result.stderr) == (b"a" * 100, b"b" * 28) + process.kill.assert_called_once() -def test_host_tool_timeout_terminates_the_process() -> None: - result = run_tool( - [sys.executable, "-c", "import time; time.sleep(20)"], - BinaryLimits(tool_timeout=0.05), - time.monotonic() + 5, - ) +@pytest.mark.parametrize("stage", ["pipes", "wait"]) +def test_host_tool_timeout_terminates_the_process( + monkeypatch: pytest.MonkeyPatch, stage: str +) -> None: + process, selector = _host_process(monkeypatch) + if stage == "pipes": + clock = iter((0.0, 0.0, 1.0, 1.0)) + monkeypatch.setattr(tools, "time", SimpleNamespace(monotonic=lambda: next(clock))) + else: + selector.get_map.side_effect = [True, False] + selector.select.return_value = [ + (SimpleNamespace(fd=1, fileobj=process.stdout, data="stdout"), 1), + (SimpleNamespace(fd=2, fileobj=process.stderr, data="stderr"), 1), + ] + monkeypatch.setattr(tools.os, "read", lambda *_: b"") + + def timed_wait(timeout: float | None = None) -> int: + if timeout is not None: + raise tools.subprocess.TimeoutExpired("tool", timeout) + process.returncode = -9 + return -9 + + process.wait.side_effect = timed_wait + result = run_tool(["tool"], BinaryLimits(tool_timeout=0.05), 5.0) assert result.diagnostic is not None assert result.diagnostic.code == "timeout" - assert result.returncode != 0 + assert result.returncode == -9 + process.kill.assert_called_once() + assert process.wait.call_count == (1 if stage == "pipes" else 2) + process.stdout.close.assert_called_once() + process.stderr.close.assert_called_once() + assert selector.select.call_count == (0 if stage == "pipes" else 1) @pytest.mark.parametrize( @@ -524,8 +576,6 @@ def test_empty_store_queries_need_no_native_dependency() -> None: def test_automatic_tools_prefer_compatible_llvm_even_named_objdump( monkeypatch: pytest.MonkeyPatch, ) -> None: - from trailmark.analysis.native_binary import tools - tools_by_name = { "llvm-objdump": tools.Tool("/llvm", "llvm", "LLVM", " x86 - 32-bit X86\n"), "objdump": tools.Tool("/apple", "llvm", "Apple LLVM", " systemz - SystemZ\n"), @@ -536,7 +586,7 @@ def test_automatic_tools_prefer_compatible_llvm_even_named_objdump( monkeypatch.setattr( tools, "run_tool", lambda *_: tools.ToolResult(b"elf64-s390\n s390:64-bit\n", b"", 0) ) - deadline = time.monotonic() + 10 + deadline = 100.0 assert tools.select_objdump(BinaryImportOptions(), deadline, "s390x", "ELF").path == "/apple" assert ( tools.select_objdump(BinaryImportOptions(backend="gnu"), deadline, "s390x", "ELF").path @@ -573,4 +623,4 @@ def test_fifo_input_is_rejected_without_waiting(tmp_path: Path) -> None: fifo = tmp_path / "fifo" os.mkfifo(fifo) with pytest.raises(ValueError, match="regular file"): - snapshot(fifo, tmp_path / "copy", time.monotonic() + 1) + snapshot(fifo, tmp_path / "copy", float("inf")) diff --git a/tests/test_c_lookup_controls.py b/tests/test_c_lookup_controls.py index f79288e..680f0ee 100644 --- a/tests/test_c_lookup_controls.py +++ b/tests/test_c_lookup_controls.py @@ -74,7 +74,6 @@ def test_cyclic_repeated_guarded_includes_do_not_expand_the_lookup_work(tmp_path capture_output=True, text=True, check=True, - timeout=10, ) assert json.loads(result.stdout) == { "functions": ["sample:action", "sample:helper"], diff --git a/tests/test_c_macro_budgets.py b/tests/test_c_macro_budgets.py index a20cfe3..2b8ed4a 100644 --- a/tests/test_c_macro_budgets.py +++ b/tests/test_c_macro_budgets.py @@ -111,7 +111,6 @@ def test_whitespace_runs_in_many_declaration_macros_are_bounded(tmp_path: Path) capture_output=True, text=True, check=True, - timeout=10, ) assert json.loads(result.stdout) == { "functions": sorted(["sample:helper", *(f"sample:action{i}" for i in range(60))]), diff --git a/tests/test_c_spliced_trivia.py b/tests/test_c_spliced_trivia.py index d1ab799..142e979 100644 --- a/tests/test_c_spliced_trivia.py +++ b/tests/test_c_spliced_trivia.py @@ -182,7 +182,6 @@ def test_unclosed_spliced_literal_reports_diagnostics_without_hanging( [sys.executable, "-c", script, str(path)], capture_output=True, text=True, - timeout=10, check=False, ) assert result.returncode == 0, result.stderr diff --git a/tests/test_c_unclosed_comments.py b/tests/test_c_unclosed_comments.py index caf1555..cc76acc 100644 --- a/tests/test_c_unclosed_comments.py +++ b/tests/test_c_unclosed_comments.py @@ -41,7 +41,6 @@ def test_many_unclosed_comment_openers_are_scanned_without_hanging() -> None: [sys.executable, "-c", script], capture_output=True, text=True, - timeout=10, check=False, ) assert result.returncode == 0, result.stderr diff --git a/tests/test_cpp_declaration_markers.py b/tests/test_cpp_declaration_markers.py index 5d1ac48..0c5166f 100644 --- a/tests/test_cpp_declaration_markers.py +++ b/tests/test_cpp_declaration_markers.py @@ -207,8 +207,7 @@ def test_standalone_template_prefix_preserves_method_owner(tmp_path: Path) -> No def test_repeated_comments_without_template_do_not_stall(tmp_path: Path, suffix: str) -> None: path = tmp_path / "sample.cpp" path.write_text("#define API\nAPI\n" + "/**/" * 40 + "\n" + suffix) - # Keep the adversarial input isolated so an exponential-time regression - # fails promptly rather than hanging the entire parser suite. + # Isolate the native parser while checking the adversarial input's graph. subprocess.run( # noqa: S603 -- Fixed interpreter and code; only a test path varies. [ sys.executable, @@ -222,7 +221,6 @@ def test_repeated_comments_without_template_do_not_stall(tmp_path: Path, suffix: check=True, capture_output=True, text=True, - timeout=10, ) diff --git a/tests/test_dafny_parser.py b/tests/test_dafny_parser.py index 32ee1bb..3ca303a 100644 --- a/tests/test_dafny_parser.py +++ b/tests/test_dafny_parser.py @@ -251,7 +251,6 @@ def test_deep_generic_lookahead_is_bounded_in_native_scanner(tmp_path: Path) -> ], check=True, capture_output=True, - timeout=30, ) diff --git a/tests/test_docs.py b/tests/test_docs.py index 82bb7bb..f297160 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -373,7 +373,7 @@ def pyproject_data() -> dict[str, object]: ("CONTRIBUTING.md", "requires all eight shards to pass"), ("CONTRIBUTING.md", "inconclusive outcomes still fail the gate"), ("CONTRIBUTING.md", "pins pytest-gremlins 1.14.3"), - ("CONTRIBUTING.md", "deterministic work bounds rather than wall-clock thresholds"), + ("CONTRIBUTING.md", "pytest timeout markers, or test subprocess deadlines"), # CLI output streams ("docs/cli.md", "`trailmark augment --json`"), ("docs/cli.md", "JSON to stdout"), diff --git a/tests/test_exception_runtime.py b/tests/test_exception_runtime.py index 70c1964..1e0546c 100644 --- a/tests/test_exception_runtime.py +++ b/tests/test_exception_runtime.py @@ -24,7 +24,6 @@ def test_php_runtime_exposes_implicit_failure_paths_absent_from_direct_throw_met capture_output=True, text=True, check=True, - timeout=10, ) if int(version.stdout) < 70400: pytest.skip("Throwing from __toString and __unserialize require PHP 7.4+") @@ -33,7 +32,6 @@ def test_php_runtime_exposes_implicit_failure_paths_absent_from_direct_throw_met capture_output=True, text=True, check=True, - timeout=10, ) observed = json.loads(result.stdout) assert observed["state"] == "changed" diff --git a/tests/test_lean_regressions.py b/tests/test_lean_regressions.py index b9fed65..9806d42 100644 --- a/tests/test_lean_regressions.py +++ b/tests/test_lean_regressions.py @@ -22,7 +22,6 @@ def _targets(graph: CodeGraph, owner: str, kind: EdgeKind = EdgeKind.REFERENCES) return [e.target_id for e in graph.edges if e.source_id == owner and e.kind == kind] -@pytest.mark.timeout(10) @pytest.mark.parametrize("body", [" + ".join(["x"] * 3000), "[" + ", ".join(["x"] * 8000) + "]"]) def test_deep_and_wide_terms_keep_every_occurrence(tmp_path: Path, body: str) -> None: graph = _parse(tmp_path, f"def x := 1\ndef big := {body}\n") diff --git a/tests/test_mutation_runner.py b/tests/test_mutation_runner.py index af24229..a228792 100644 --- a/tests/test_mutation_runner.py +++ b/tests/test_mutation_runner.py @@ -70,7 +70,6 @@ def test_sharded_campaigns_match_complete_campaign(tmp_path: Path) -> None: capture_output=True, text=True, check=False, - timeout=120, ) assert result.returncode == 0, result.stdout + result.stderr report = json.loads((tmp_path / "coverage/gremlins/gremlins.json").read_text()) @@ -232,9 +231,9 @@ def test_checked_only_in_child(tmp_path): child = context.Process(target=evaluate, args=(queue,)) child.start() try: - answer = queue.get(timeout=10) - child.join(timeout=10) + child.join() assert child.exitcode == 0 + answer = queue.get() assert answer is True finally: if child.is_alive(): @@ -249,7 +248,6 @@ def test_checked_only_in_child(tmp_path): capture_output=True, text=True, check=False, - timeout=120, ) assert result.returncode == 0, result.stdout + result.stderr report = json.loads((tmp_path / "coverage/gremlins/gremlins.json").read_text()) @@ -295,7 +293,6 @@ def test_runner_rejects_skipped_instrumentation( capture_output=True, text=True, check=False, - timeout=120, ) assert result.returncode != 0 assert "Mutation instrumentation skipped files" in result.stdout + result.stderr diff --git a/tests/test_native_binary.py b/tests/test_native_binary.py index e524120..7b7b91c 100644 --- a/tests/test_native_binary.py +++ b/tests/test_native_binary.py @@ -773,7 +773,6 @@ def test_exception_metadata_does_not_imply_recovered_exception_dispatch(tmp_path ], capture_output=True, check=True, - timeout=60, ) binary = lief_module().parse(str(image)) assert binary is not None diff --git a/tests/test_native_stability.py b/tests/test_native_stability.py index 9a06f29..e71d9e2 100644 --- a/tests/test_native_stability.py +++ b/tests/test_native_stability.py @@ -49,7 +49,6 @@ def test_large_file_parses_in_subprocess( [sys.executable, "-X", "faulthandler", "-c", script], capture_output=True, text=True, - timeout=30, check=False, ) assert result.returncode == 0, result.stderr @@ -71,7 +70,6 @@ def test_point_coordinates_survive_repeated_reads_in_subprocess() -> None: [sys.executable, "-X", "faulthandler", "-c", script], capture_output=True, text=True, - timeout=30, check=False, ) assert result.returncode == 0, result.stderr diff --git a/tests/test_proxy_properties.py b/tests/test_proxy_properties.py index 54a5f52..8199530 100644 --- a/tests/test_proxy_properties.py +++ b/tests/test_proxy_properties.py @@ -168,6 +168,5 @@ def test_containment_cycles_without_a_callable_owner_terminate() -> None: capture_output=True, text=True, check=True, - timeout=10, ) assert result.stdout == "done\n" diff --git a/tests/test_round3_frontends.py b/tests/test_round3_frontends.py index 22f02a3..d29bc45 100644 --- a/tests/test_round3_frontends.py +++ b/tests/test_round3_frontends.py @@ -1,7 +1,6 @@ """Regression coverage for callable ownership and bounded extraction.""" from pathlib import Path -from time import perf_counter from typing import cast import pytest @@ -23,9 +22,7 @@ def test_expression_lambdas_are_extracted_once(tmp_path: Path, extension: str, d ) path = tmp_path / f"a.{extension}" path.write_text(source) - start = perf_counter() graph = parse_file(str(path)) - assert perf_counter() - start < 1 lambdas = [u for u in graph.nodes.values() if u.name.startswith("$lambda")] assert len(lambdas) == min(depth, 47 if extension == "php" else 46) calls = [ diff --git a/tests/test_round3_python.py b/tests/test_round3_python.py index dd8fa27..92f11ff 100644 --- a/tests/test_round3_python.py +++ b/tests/test_round3_python.py @@ -4,7 +4,7 @@ import pytest -from tests.test_round5_python import _parse_work +from tests.parse_work import parse_work from trailmark.models import EdgeKind, NodeKind from trailmark.parse import parse_file @@ -78,7 +78,7 @@ def test_many_runtime_definitions_are_linear(tmp_path: Path, body: str) -> None: work = [] for count in (1000, 4000): path.write_text(body * count) - graph, visits = _parse_work(path) + graph, visits = parse_work(path) assert visits > 0 work.append(visits) assert len([u for u in graph.nodes.values() if u.kind == NodeKind.FUNCTION]) == count diff --git a/tests/test_round3_robustness.py b/tests/test_round3_robustness.py index 3e0e891..0f8f082 100644 --- a/tests/test_round3_robustness.py +++ b/tests/test_round3_robustness.py @@ -1,7 +1,6 @@ """Deep callable nesting returns partial graphs with explicit diagnostics.""" from pathlib import Path -from time import perf_counter import pytest @@ -39,9 +38,7 @@ def test_deep_callable_file_is_bounded(tmp_path: Path, extension: str, source: str) -> None: path = tmp_path / f"a.{extension}" path.write_text(source) - start = perf_counter() graph = parse_file(str(path)) - assert perf_counter() - start < 2 assert any(d.kind == "unsupported_syntax" for d in graph.parse_diagnostics) assert graph.nodes assert all(d.location.file_path == str(path) for d in graph.parse_diagnostics) diff --git a/tests/test_round4_frontends.py b/tests/test_round4_frontends.py index 2e79d6f..e225cbc 100644 --- a/tests/test_round4_frontends.py +++ b/tests/test_round4_frontends.py @@ -1,7 +1,6 @@ """Nested classes and callable bodies retain their own graph owners.""" from pathlib import Path -from time import perf_counter import pytest @@ -86,9 +85,7 @@ def test_deep_typescript_classes_are_bounded(tmp_path: Path, expression: bool) - opening = "const A = class { m(){" if expression else "class A { m(){" closing = "}};" if expression else "}}" path.write_text("function run(){" + opening * 3000 + "work();" + closing * 3000 + "}") - start = perf_counter() graph = parse_file(str(path)) - assert perf_counter() - start < 2 assert graph.parse_diagnostics and len(graph.nodes) < 150 diff --git a/tests/test_round5_python.py b/tests/test_round5_python.py index 629a755..029ad80 100644 --- a/tests/test_round5_python.py +++ b/tests/test_round5_python.py @@ -1,51 +1,21 @@ """Python generic declarations, aliases, and long receiver chains stay bounded.""" -import sys -from collections.abc import Callable from pathlib import Path -from types import FrameType import pytest -from trailmark.models import CodeGraph, EdgeKind +from tests.parse_work import parse_work +from trailmark.models import EdgeKind from trailmark.parse import parse_file from trailmark.parsers import _common -type _Trace = Callable[[FrameType, str, object], _Trace | None] - - -def _parse_work(path: Path) -> tuple[CodeGraph, int]: - """Count Python traversal work independently of CPU speed and instrumentation. - - Native grammar time is not measured. Line events detect repeated Python - ancestor walks, including when instrumented code lives in temporary files. - """ - work = 0 - - def count(frame: FrameType, event: str, argument: object) -> _Trace: - nonlocal work - if event == "line": - work += 1 - return count - - def select(frame: FrameType, event: str, argument: object) -> _Trace | None: - return count if frame.f_globals.get("__name__", "").startswith("trailmark.") else None - - previous = sys.gettrace() - try: - sys.settrace(select) - graph = parse_file(str(path)) - finally: - sys.settrace(previous) - return graph, work - def test_long_receiver_chain_is_linear(tmp_path: Path) -> None: path = tmp_path / "app.py" work = [] for length in (750, 3000): path.write_text("def run():\n return a()" + ".b()" * length + "\n") - graph, visits = _parse_work(path) + graph, visits = parse_work(path) assert visits > 0 work.append(visits) assert len([e for e in graph.edges if e.kind == EdgeKind.CALLS]) == length + 1 diff --git a/tests/test_rust_local_items.py b/tests/test_rust_local_items.py index 9394acc..c9c73c5 100644 --- a/tests/test_rust_local_items.py +++ b/tests/test_rust_local_items.py @@ -6,6 +6,7 @@ import pytest +from tests.parse_work import parse_work from trailmark.models.edges import EdgeKind from trailmark.models.nodes import NodeKind from trailmark.parsers.rust.parser import RustParser @@ -384,14 +385,17 @@ def test_associated_paths_and_unit_struct_receivers_still_resolve(tmp_path: Path ] -@pytest.mark.timeout(5, func_only=True) def test_large_rust_file_resolves_calls_without_scanning_every_declaration(tmp_path: Path) -> None: path = tmp_path / "large.rs" - count = 8000 - path.write_text("\n".join(f"fn f{i}() {{ f{(i + 1) % count}(); }}" for i in range(count))) - graph = RustParser().parse_file(str(path)) - calls = [edge for edge in graph.edges if edge.kind == EdgeKind.CALLS] - assert len(calls) == count - assert {(edge.source_id, edge.target_id) for edge in calls} == { - (f"large:f{i}", f"large:f{(i + 1) % count}") for i in range(count) - } + work = [] + for count in (2000, 8000): + path.write_text("\n".join(f"fn f{i}() {{ f{(i + 1) % count}(); }}" for i in range(count))) + graph, visits = parse_work(path) + assert visits > 0 + work.append(visits) + calls = [edge for edge in graph.edges if edge.kind == EdgeKind.CALLS] + assert len(calls) == count + assert {(edge.source_id, edge.target_id) for edge in calls} == { + (f"large:f{i}", f"large:f{(i + 1) % count}") for i in range(count) + } + assert work[1] <= 5 * work[0], work diff --git a/tests/test_rust_parser.py b/tests/test_rust_parser.py index d04c477..71e952f 100644 --- a/tests/test_rust_parser.py +++ b/tests/test_rust_parser.py @@ -480,8 +480,6 @@ def test_ignores_unsupported_delimiters_between_verus_blocks(self, tmp_path: Pat functions = {node.name for node in graph.nodes.values() if node.kind == NodeKind.FUNCTION} assert functions == {"first", "last"} - @pytest.mark.timeout(5, func_only=True) - @pytest.mark.usefixtures("compiled_verus") def test_parses_multiple_verus_ranges_and_ignores_other_macros(self) -> None: source = """\ verus! { spec fn first() -> bool { true } } diff --git a/tests/test_rust_verus_regressions.py b/tests/test_rust_verus_regressions.py index 87c5705..e05a6ee 100644 --- a/tests/test_rust_verus_regressions.py +++ b/tests/test_rust_verus_regressions.py @@ -132,8 +132,6 @@ def test_valid_block_without_functions_is_not_an_error( assert caplog.records == [] -@pytest.mark.timeout(5, func_only=True) -@pytest.mark.usefixtures("compiled_verus") def test_opaque_macros_are_diagnosed_without_expanding_them( tmp_path: Path, caplog: pytest.LogCaptureFixture ) -> None: diff --git a/tests/test_test_policy.py b/tests/test_test_policy.py new file mode 100644 index 0000000..d51fd4e --- /dev/null +++ b/tests/test_test_policy.py @@ -0,0 +1,98 @@ +"""Keep CI correctness checks independent of machine speed.""" + +import ast +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, settings + + +def _timing_controls(source: str) -> list[str]: + controls = [] + for node in ast.walk(ast.parse(source)): + if ( + isinstance(node, ast.Import) + and any(alias.name in {"time", "timeit"} for alias in node.names) + or isinstance(node, ast.ImportFrom) + and node.module in {"time", "timeit"} + ): + controls.append("clock import") + elif ( + isinstance(node, ast.Attribute) + and node.attr == "timeout" + and ( + isinstance(node.value, ast.Attribute) + and node.value.attr == "mark" + or isinstance(node.value, ast.Name) + and node.value.id == "mark" + ) + ): + controls.append("pytest timeout") + elif isinstance(node, ast.Call): + name = getattr(node.func, "attr", getattr(node.func, "id", "")) + for keyword in node.keywords: + if keyword.arg == "timeout" and name in { + "run", + "check_call", + "check_output", + "communicate", + "wait", + "join", + "get", + }: + controls.append("test timeout") + elif ( + keyword.arg == "deadline" + and name in {"settings", "register_profile"} + and not ( + isinstance(keyword.value, ast.Constant) and keyword.value.value is None + ) + ): + controls.append("test deadline") + return controls + + +@pytest.mark.parametrize( + "source", + [ + "import time as clock", + "from time import perf_counter as now", + "@pytest.mark.timeout(5)\ndef test_case(): pass", + "from pytest import mark\n@mark.timeout(5)\ndef test_case(): pass", + "subprocess.run(['tool'], timeout=10)", + "@settings(deadline=200)\ndef test_case(): pass", + ], +) +def test_policy_rejects_clock_based_checks(source: str) -> None: + assert _timing_controls(source) + + +@pytest.mark.parametrize( + "source", + [ + "BinaryLimits(tool_timeout=0.05)", + "TimeoutExpired('tool', timeout=0.05)", + "run_tool(['tool'], limits, deadline=5.0)", + "@settings(deadline=None)\ndef test_case(): pass", + ], +) +def test_policy_allows_product_limits_and_disabled_deadlines(source: str) -> None: + assert _timing_controls(source) == [] + + +def test_suite_has_no_test_timeouts_or_wall_clock_assertions() -> None: + # These are opt-in measurement tools or the mutation executor, not tests. + measurement_tools = {"benchmark_analysis.py", "smoke_binary_projects.py", "run_mutations.py"} + violations = { + path.name: controls + for path in Path(__file__).parent.glob("*.py") + if path.name not in measurement_tools and (controls := _timing_controls(path.read_text())) + } + assert violations == {} + + +def test_hypothesis_has_no_deadline_or_generation_speed_limit() -> None: + defaults = settings.default + assert defaults is not None + assert defaults.deadline is None + assert HealthCheck.too_slow in defaults.suppress_health_check diff --git a/uv.lock b/uv.lock index aac6ba7..62918c4 100644 --- a/uv.lock +++ b/uv.lock @@ -402,18 +402,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/80/cd/4175391a0f2903bd8aa21c0a4bd28de5cd1fd79c3034e5ecfd5e50ea5d04/pytest_gremlins-1.14.3-py3-none-any.whl", hash = "sha256:8e4d553b1a78ac38c7203b994e9dbbfb6149777a3561a425e4530ac515e4762c", size = 240076, upload-time = "2026-11-16T14:38:29.595Z" }, ] -[[package]] -name = "pytest-timeout" -version = "2.4.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ac/82/4c9ecabab13363e72d880f2fb504c5f750433b2b6f16e99f4ec21ada284c/pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a", size = 17973, upload-time = "2025-05-05T19:44:34.99Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fa/b6/3127540ecdf1464a00e5a01ee60a1b09175f6913f0644ac748494d9c4b21/pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2", size = 14382, upload-time = "2025-05-05T19:44:33.502Z" }, -] - [[package]] name = "ruff" version = "0.17.6" @@ -499,7 +487,6 @@ dev = [ { name = "pytest" }, { name = "pytest-cov" }, { name = "pytest-gremlins" }, - { name = "pytest-timeout" }, { name = "ruff" }, { name = "ty" }, ] @@ -520,7 +507,6 @@ dev = [ { name = "pytest", specifier = ">=9.2.0" }, { name = "pytest-cov", specifier = ">=7.1.0" }, { name = "pytest-gremlins", specifier = "==1.14.3" }, - { name = "pytest-timeout", specifier = ">=2.4,<3" }, { name = "ruff", specifier = ">=0.17.6,<1.0" }, { name = "ty", specifier = ">=0.0.107,<0.1" }, ]