FFFF feat(python): detect tests exceeding a configurable time budget by 2409324124 · Pull Request #208 · habit-hooks/habit-hooks · GitHub
[go: up one dir, main page]

Skip to content
Open
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
10000 Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Added

- **Python flags tests that exceed a 1 second budget**, coached as `slow-test`. The sensor runs pytest and reads precise setup, call and teardown timings through its report hooks, independently of terminal output. Override the budget through the usual sensor args, for example `[sensors.slow-test] args = ["--budget", "2"]`. The generic `slow-test` guide coaches keeping tests fast and deterministic. (#57)

### Fixed

- **On Python 3.13 a plugin's `search_paths` could name a directory outside
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ Detectors are **not** bundled: a plugin spawns the real tool, or reads it as a l
| Plugin | Detectors | Install |
| ------ | --------- | ------- |
| **generic** | [`jscpd`](https://github.com/kucherenko/jscpd) — the line counter is built in | `npm install --save-dev jscpd` |
| **python** | [`ruff`](https://docs.astral.sh/ruff/), [`deptry`](https://github.com/fpgmaas/deptry) | `pip install ruff deptry` |
| **python** | [`ruff`](https://docs.astral.sh/ruff/), [`deptry`](https://github.com/fpgmaas/deptry), [`pytest`](https://pytest.org/) | `pip install ruff deptry pytest` |
| **typescript** | `node`, [`eslint`](https://eslint.org/), [`knip`](https://knip.dev/), [`ts-morph`](https://ts-morph.com/) | `npm install --save-dev eslint knip ts-morph` (`node` from your system package manager) |
| **php** | `php` — [phpmd](https://phpmd.org/) ships bundled as a phar | nothing beyond a PHP runtime |
| **java** | [`pmd`](https://pmd.github.io/) | `brew install pmd` |
Expand Down Expand Up @@ -333,7 +333,7 @@ The plugins we ship:
| Plugin | Language | Sensors | Tools used |
|--------|----------|---------|------------|
| `generic` | (none) | `line-count`, `jscpd` | built-in line counter, jscpd |
| `python` | `python` | `ruff`, `deptry` | ruff, deptry |
| `python` | `python` | `ruff`, `deptry`, `slow-test` | ruff, deptry, pytest |
| `typescript` | `typescript` | `eslint`, `knip`, `comment` | eslint, knip, ts-morph |
| `php` | `php` | `phpmd` | phpmd |
| `java` | `java` | `pmd` | pmd |
Expand Down
1 change: 1 addition & 0 deletions docs/smell-vocabulary.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Default severity: `enforced` fails the run (exit 1); `suggested` coaches but exi
| `unused-dependency` | Unused dependency | enforced |
| `unused-import` | Unused import | enforced |
| `swallowed-exception` | Swallowed exception | suggested |
| `slow-test` | Slow test | suggested |
| `parse-error` | Parse / config error | enforced |

## Proposing new smells
Expand Down
15 changes: 15 additions & 0 deletions plugins/generic/src/habit_hooks_generic/guides/slow-test.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Slow tests hide the cost of work that should happen once, or of luck that should be a fixture. The smell is not the clock; it is a test that does too much, rebuilds expensive state, or hunts through random seeds instead of asserting a known case.

Work through it in order:

1. **Cut per-test work.** Keep each test on one behaviour. Setup, I/O, and waits that are not the behaviour under test belong outside the example, or out of the suite.
2. **Reuse fixtures instead of rebuilding expensive state.** A database, a rendered tree, or a compiled fixture that several tests need should be built once and shared (or frozen) rather than reconstructed in every example. Share immutable setup or reset mutable state between tests so reuse does not couple their outcomes.
3. **Make the test deterministic.** Seed randomness. Freeze the fixture you care about and assert that case, rather than asserting over many random seeds and hoping a slow search eventually hits the interesting one.

A sleep, a larger timeout, or deleting the assertion to sneak under the budget is not a fix. The test should be fast because it does less, and reliable because its input is known.

Tests over {{ details.maxAllowed }} seconds:

{% for issue in issues -%}
{{ issue.details.test }} {{ issue.details.content }}
{% endfor -%}
13 changes: 11 additions & 2 deletions plugins/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,19 @@

## What it does

The plugin enables `habit-sensors` over a Python project and rewrites three tools' findings into structural code smells from the [canonical vocabulary](https://github.com/habit-hooks/habit-hooks/blob/main/docs/smell-vocabulary.md):
The plugin enables `habit-sensors` over a Python project and rewrites four tools' findings into structural code smells from the [canonical vocabulary](https://github.com/habit-hooks/habit-hooks/blob/main/docs/smell-vocabulary.md):

- **ruff** — `too-many-parameters`, `high-complexity`, `unused-variable`, `unused-import`, `swallowed-exception`. Unmapped codes pass through under their own name rather than disappearing.
- **deptry** — dependencies declared but never imported.
- **comment analysis** — comments and docstrings that narrate instead of stating a non-obvious why, coached as `non-essential-comment`.
- **pytest** — runs the test files in scope with `pytest --durations=0` and flags tests whose setup, call and teardown together exceed a 1 second budget (overridable with `[sensors.slow-test] args = ["--budget", "2"]`), coached as `slow-test`. Timings come from pytest report hooks, not captured terminal text: quiet output, `--no-summary`, and text printed by tests cannot hide or forge them.

A tool that crashes fails the run rather than reporting clean.

## Requirements

- Python 3.11+
- [ruff](https://docs.astral.sh/ruff/) and [deptry](https://github.com/fpgmaas/deptry) on `PATH` (`pip install ruff deptry`).
- [ruff](https://docs.astral.sh/ruff/), [deptry](https://github.com/fpgmaas/deptry) and [pytest](https://pytest.org/) on `PATH` (`pip install ruff deptry pytest`).

## Installation

Expand All @@ -32,3 +33,11 @@ plugins = ["python", "generic"]
```

The full walk-through — init, running, snoozing, CI — is in the [core README](https://github.com/habit-hooks/habit-hooks#readme).

## Slow-test scope and timing

The sensor runs only Python test files in the Habit Hooks scope, using the project's `python_files` patterns (including custom names), pytest configuration and installed plugins. A change to application code or `conftest.py` alone does not select dependent tests; use `--all` to check all tracked test files. When the project enables `--doctest-modules`, scoped Python modules are also checked for doctests. Each scan executes tests again, so their side effects and runtime still apply.

Setup, call and teardown durations are summed at pytest's native precision; only the displayed time is rounded. The comparison is strictly greater than the budget, not greater than or equal. Pytest attributes shared fixture setup and teardown to the tests that perform them, not evenly across the suite. Repeated or rerun executions of the same node ID use the slowest attempt, not the sum of retries; distinct parametrized IDs remain separate. Node IDs retain pytest's escaping, so literal backslashes and Unicode parameter IDs are not reinterpreted.

Empty, deselected and skipped suites can legitimately produce no findings. Collection errors, missing timing data, and pytest crashes fail the scan instead of reporting clean. `--collect-only` and `--setup-only` are refused because they do not measure test execution. Selection options such as `-k`, `--lf`, and `-x` are respected, so only executed tests are measured. Custom collectors and plugins that replace pytest's normal setup/call/teardown reports are not supported; they must supply normal duration reports for measured tests.
2 changes: 2 additions & 0 deletions plugins/python/src/habit_hooks_python/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ sensors = [
{ tool = "ruff", args = ["check", "--output-format=json", "--select=C901,PLR0913,PLR0915,F841,F401,BLE001", "${files}"], transform = "ruff.jq", success_exit_codes = [0, 1] },
{ name = "deptry", tool = "${python}", args = ["${dir}/sensors/deptry_sensor.py", "${detector:deptry}"] },
{ name = "comment", tool = "${python}", args = ["${dir}/comment.py", "${files}"] },
{ name = "slow-test", tool = "${python}", args = ["${dir}/sensors/slow_test.py", "${detector:pytest}", "${args}", "--", "${files}"] },
]
transformers = []

detectors = [
{ name = "ruff", kind = "command", install = "pip install ruff" },
{ name = "deptry", kind = "command", install = "pip install deptry" },
{ name = "pytest", kind = "command", install = "pip install pytest" },
]
127 changes: 127 additions & 0 deletions plugins/python/src/habit_hooks_python/sensors/slow_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
from __future__ import annotations

import argparse
import json
import math
import os
import subprocess
import sys
import tempfile
from pathlib import Path

DEFAULT_BUDGET_SECONDS = 1.0
SUCCESS_EXIT_CODES = {0, 1, 5}
BUDGET_ERROR = "budget must be a positive number of seconds"
NO_DURATION_REPORT = "pytest produced no complete timing report\n"


def positive_seconds(value: str) -> float:
try:
budget = float(value)
except ValueError:
raise argparse.ArgumentTypeError(BUDGET_ERROR) from None
if not math.isfinite(budget) or budget <= 0:
raise argparse.ArgumentTypeError(BUDGET_ERROR)
return budget


def parse_args(argv: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("pytest")
parser.add_argument(
"--budget", type=positive_seconds, default=DEFAULT_BUDGET_SECONDS
)
parser.add_argument("files", nargs="*")
return parser.parse_args(argv)


def file_of(nodeid: str) -> str:
return nodeid.split("::", 1)[0].replace("\\", "/")


def issue(nodeid: str, duration: float) -> dict:
path = file_of(nodeid)
return {
"key": nodeid,
"details": {
"file": path,
"test": nodeid,
"duration": duration,
"content": f"{duration:.2f}s",
"source": "pytest:durations",
},
}


def findings(entries: list[tuple[str, float]], budget: float) -> list[dict]:
issues = [
issue(nodeid, duration)
for nodeid, duration in sorted(entries, key=lambda item: item[1], reverse=True)
if duration > budget
]
if not issues:
return []
return [{"smell": "slow-test", "details": {"maxAllowed": budget}, "issues": issues}]


def run_pytest(
pytest: str, files: list[str], report: Path
) -> subprocess.CompletedProcess[str]:
env = os.environ.copy()
helper_dir = str(Path(__file__).resolve().parent)
env["PYTHONPATH"] = os.pathsep.join(
filter(None, [env.get("PYTHONPATH"), helper_dir])
)
return subprocess.run(
[
pytest,
"-p",
"slow_test_report",
"--durations=0",
"--habit-hooks-report",
str(report),
"--",
*files,
],
capture_output=True,
encoding="utf-8",
errors="replace",
env=env,
)


def report_entries(report: Path) -> list[tuple[str, float]]:
data = json.loads(report.read_text(encoding="utf-8"))
if data["collection_failed"] or (data["collected"] and not data["durations"]):
raise ValueError(NO_DURATION_REPORT)
return list(data["durations"].items())


def report_from(
result: subprocess.CompletedProcess[str], report: Path, budget: float
) -> int:
if result.returncode not in SUCCESS_EXIT_CODES:
sys.stderr.write(result.stderr or result.stdout)
return 2
try:
entries = report_entries(report)
except (OSError, ValueError, KeyError, TypeError):
sys.stderr.write(NO_DURATION_REPORT + (result.stderr or result.stdout))
return 2
print(json.dumps(findings(entries, budget)))
return 0


def main(argv: list[str] | None = None) -> int:
args = parse_args(argv if argv is not None else sys.argv[1:])
files = [path for path in args.files if path.endswith(".py")]
if not files:
print(json.dumps([]))
return 0
with tempfile.TemporaryDirectory() as tmp:
report = Path(tmp) / "timings.json"
return report_from(run_pytest(args.pytest, files, report), report, args.budget)


if __name__ == "__main__":
sys.exit(main())
82 changes: 82 additions & 0 deletions plugins/python/src/habit_hooks_python/sensors/slow_test_report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
from __future__ import annotations

import fnmatch
import json
import os
from pathlib import Path

import pytest


def pytest_addoption(parser: pytest.Parser) -> None:
parser.addoption("--habit-hooks-report")


def matches_pattern(path: Path, pattern: str) -> bool:
pattern = pattern.replace("/", os.sep)
name = str(path.absolute()) if os.sep in pattern else path.name
if os.sep in pattern and not os.path.isabs(pattern):
pattern = f"*{os.sep}{pattern}"
return fnmatch.fnmatch(name, pattern)


def matches_test_pattern(path: str, patterns: list[str]) -> bool:
return Path(path).name != "conftest.py" and any(
matches_pattern(Path(path), pattern) for pattern in patterns
)


@pytest.hookimpl(trylast=True)
def pytest_sessionstart(session: pytest.Session) -> None:
config = session.config
if config.option.collectonly or config.option.setuponly:
raise pytest.UsageError(
"slow-test requires test execution, not collection/setup only"
)
config.args = [
path
for path in config.args
if getattr(config.option, "doctestmodules", False)
or matches_test_pattern(path, config.getini("python_files"))
]


def write_report(config: pytest.Config, data: dict) -> None:
if not hasattr(config, "workerinput"):
Path(config.getoption("--habit-hooks-report")).write_text(
json.dumps(data), encoding="utf-8"
)


def pytest_configure(config: pytest.Config) -> None:
config.pluginmanager.register(Timings(config), "habit-hooks-timings")


class Timings:
def __init__(self, config: pytest.Config) -> None:
self.config = config
self.current: dict[tuple[str, str], float] = {}
self.durations: dict[str, float] = {}
self.collection_failed = False

def pytest_collectreport(self, report: pytest.CollectReport) -> None:
self.collection_failed |= report.failed

def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
key = (getattr(report, "worker_id", ""), report.nodeid)
if report.when == "setup":
self.current[key] = 0.0
self.current[key] = self.current.get(key, 0.0) + report.duration
self.durations[report.nodeid] = max(
self.durations.get(report.nodeid, 0.0), self.current[key]
)

def pytest_sessionfinish(self, session: pytest.Session) -> None:
write_report(
self.config,
{
"collected": session.testscollected,
"collection_failed": self.collection_failed,
"durations": self.durations,
},
)
Loading
0