diff --git a/docs/superpowers/contracts/usage-report-main-tests-2026-08-17.json b/docs/superpowers/contracts/usage-report-main-tests-2026-08-17.json new file mode 100644 index 00000000..def7776a --- /dev/null +++ b/docs/superpowers/contracts/usage-report-main-tests-2026-08-17.json @@ -0,0 +1,17 @@ +{ + "title": "Cover usage_report.py before splitting it", + "objective": "usage_report.py is 426 lines against a 250-line cap and sat at 47% coverage, with the uncovered half being the CLI, the two run paths, the clipboard/emit side and the segment aggregation - i.e. most of what a split would move. This commit raises it to 100% line and branch coverage first, so the following split can be verified against tests that predate the seam. No production code changes here.", + "acceptance_criteria": [ + "usage_report.py reaches 100% line and branch coverage, from 47%", + "usage_report.py is byte-identical to HEAD - this commit adds tests only", + "The directory test count rises by exactly the number of tests added (179 -> 204) with no existing test altered", + "No suppression of any kind: no noqa, no type: ignore, no lowered threshold", + "Every new test file is under the 250-line cap, so the over-cap total does not rise" + ], + "out_of_scope": [ + "The split of usage_report.py itself, which is the next commit", + "Deleting the dead _compute_window shim - a behaviour change that does not belong in a coverage commit", + "meta/scripts/optimize_vscode.py and the three transcribe_* files, also over cap and untested" + ], + "verifier": "pytest linux_configuration/tests/ --cov=usage_report --cov-branch --cov-report=term-missing for the coverage claim and the test count; pre-commit run --files for lint; bash ~/utils/scripts/check_file_length.sh --all to confirm no new over-cap file." +} diff --git a/docs/superpowers/evidence/usage-report-main-tests-2026-08-17.json b/docs/superpowers/evidence/usage-report-main-tests-2026-08-17.json new file mode 100644 index 00000000..57be2322 --- /dev/null +++ b/docs/superpowers/evidence/usage-report-main-tests-2026-08-17.json @@ -0,0 +1,46 @@ +{ + "intent": "Take usage_report.py from 47% to 100% line and branch coverage, so the split that follows can be verified against tests written before the seam existed.", + "scope": [ + "Four new test files under linux_configuration/tests/: cli, emit, segments, run_since - 25 tests", + "No production file changed. usage_report.py is byte-identical to HEAD.", + "Non-goal: the split itself, and deleting the dead _compute_window shim" + ], + "changes": [ + "Covered the CLI surface: every argparse default, every flag with its parsed type, and main's dispatch between the single-day and since-last-report paths.", + "Covered _run_single_day and _run_since end to end with their collaborators stubbed, including the shared 'a window with no measured seconds is treated as a full day' fallback on both paths.", + "Covered _run_since's no-data path: the stderr note, the absence of a report, and that the saved timestamp still advances unless --no-update-state is given. Both state-advance branches are exercised on both the data and no-data paths.", + "Covered the output side: _emit with and without the clipboard, and _copy_to_clipboard picking the first available tool, reporting a tool that fails, and skipping when none is installed.", + "Covered _preflight's three outcomes, _aggregate_segments including a gap day and a present-but-empty log, _log_descriptions, and the deprecated _compute_window shim.", + "No suppression was used. mypy rejected a `list.append(...) or 0` lambda as func-returns-value; it was replaced with a real closure rather than silenced. Ten ruff S108 findings on hardcoded /tmp paths were fixed by using /nonexistent sentinels - those paths are never opened, they only prove which value was passed through." + ], + "verification": [ + { + "command": "pytest linux_configuration/tests/ --cov=usage_report --cov-branch --cov-report=term-missing", + "result": "pass", + "evidence": "Before: 185 stmts, 89 miss, 44 branch, 47%, missing 65-68, 112-127, 150-152, 219-224, 244-254, 261-263, 294-316, 331-364, 369-413, 418-422. After: 185 stmts, 0 miss, 44 branch, 0 partial, 100%." + }, + { + "command": "pytest linux_configuration/tests/ (whole directory)", + "result": "pass", + "evidence": "204 passed, up from 179 - exactly the 25 tests added, with no change to the 179 already there." + }, + { + "command": "pre-commit run --files ", + "result": "pass", + "evidence": "All applicable hooks pass, including ruff, ruff format, mypy and the noqa blockers. grep for 'noqa|type: ignore' across them returns 0." + }, + { + "command": "bash ~/utils/scripts/check_file_length.sh --all", + "result": "pass", + "evidence": "The tests were first written as two files of 273 and 282 lines, both over the 250 cap, and split into four of 180/158/111/156 before committing. This is the DropZone lesson from earlier in the session, where a fix silently added an over-cap file; the over-cap total is unchanged at 38 by this commit." + } + ], + "risks": [ + "These tests stub usage_report's collaborators (_aggregate_segments, _render_report, _emit, aggregate_atop) rather than exercising the real pipeline, so they verify orchestration and control flow, not that a real report renders. That is covered by running the actual program, which the split commit does.", + "_compute_window is dead code: a shim documented as 'kept for backwards import compatibility' with zero callers anywhere in the repo (verified by grep across .py and .sh). It is tested here rather than deleted, because deleting it is a behaviour change beyond a coverage commit. It is a candidate for removal in its own right." + ], + "rollback": [ + "git rm the four test files. No production code depends on them.", + "After rollback, coverage of usage_report.py returns to 47% and linux_configuration/tests reports 179 passing tests." + ] +} diff --git a/linux_configuration/tests/test_usage_report_cli.py b/linux_configuration/tests/test_usage_report_cli.py new file mode 100644 index 00000000..b3b5cdf8 --- /dev/null +++ b/linux_configuration/tests/test_usage_report_cli.py @@ -0,0 +1,180 @@ +"""Tests for usage_report's command-line surface: argument parsing, the +single-day and since-last-report entry points, and main's dispatch between +them. +""" + +from __future__ import annotations + +import datetime as _dt +from pathlib import Path +from typing import TYPE_CHECKING + +from _usage_report_types import _Progress, _Window +import usage_report + +if TYPE_CHECKING: + from collections.abc import Callable + + import pytest + + +def _progress() -> _Progress: + """A progress reporter that never draws, so stderr stays clean.""" + return _Progress(enabled=False, total_stages=1) + + +def _args(**overrides: object) -> object: + """Build a parsed-args namespace with the parser's own defaults.""" + args = usage_report._build_parser().parse_args([]) + for key, value in overrides.items(): + setattr(args, key, value) + return args + + +def _aggregates(*, days_with_data: int = 1, seconds: int = 600) -> object: + """Build an _Aggregates with a window that looks like real coverage.""" + return usage_report._Aggregates( + cpu={}, + gpu={}, + window=_Window(distinct_samples=2, interval_s=600, seconds=seconds), + gpu_samples=0, + days_with_data=days_with_data, + ) + + +# --------------------------------------------------------------------------- # +# _build_parser +# --------------------------------------------------------------------------- # +def test_parser_defaults() -> None: + """With no flags every option takes its documented default.""" + args = usage_report._build_parser().parse_args([]) + + assert args.date is None + assert args.since is None + assert args.top == usage_report._DEFAULT_TOP + assert args.atop_log is None + assert args.pmon_log is None + assert args.no_clipboard is False + assert args.no_update_state is False + assert args.quiet is False + + +def test_parser_reads_every_flag() -> None: + """Each flag lands on the namespace with the right type.""" + args = usage_report._build_parser().parse_args( + [ + "--date", + "20260817", + "--since", + "20260801", + "--top", + "20", + "--atop-log", + "/nonexistent/a", + "--pmon-log", + "/nonexistent/p", + "--no-clipboard", + "--no-update-state", + "--quiet", + ], + ) + + assert args.date == "20260817" + assert args.since == "20260801" + assert args.top == 20 + assert args.atop_log == Path("/nonexistent/a") + assert args.pmon_log == Path("/nonexistent/p") + assert args.no_clipboard is True + assert args.no_update_state is True + assert args.quiet is True + + +# --------------------------------------------------------------------------- # +# main dispatch +# --------------------------------------------------------------------------- # +def test_main_routes_single_day(monkeypatch: pytest.MonkeyPatch) -> None: + """A --date run goes to the single-day path.""" + seen: list[str] = [] + + def record(label: str) -> Callable[..., int]: + def run(*_a: object) -> int: + seen.append(label) + return 0 + + return run + + monkeypatch.setattr(usage_report, "_run_single_day", record("single")) + monkeypatch.setattr(usage_report, "_run_since", record("since")) + + assert usage_report.main(["--date", "20260817"]) == 0 + assert seen == ["single"] + + +def test_main_routes_since_by_default(monkeypatch: pytest.MonkeyPatch) -> None: + """With no day-selecting flag the since-last-report path runs.""" + seen: list[str] = [] + + def record(label: str) -> Callable[..., int]: + def run(*_a: object) -> int: + seen.append(label) + return 0 + + return run + + monkeypatch.setattr(usage_report, "_run_single_day", record("single")) + monkeypatch.setattr(usage_report, "_run_since", record("since")) + + assert usage_report.main([]) == 0 + assert seen == ["since"] + + +# --------------------------------------------------------------------------- # +# _run_single_day +# --------------------------------------------------------------------------- # +def test_run_single_day_emits_a_report(monkeypatch: pytest.MonkeyPatch) -> None: + """The single-day path renders once and writes the result out.""" + monkeypatch.setattr(usage_report, "_preflight", lambda _log: None) + monkeypatch.setattr( + usage_report, + "_resolve_logs", + lambda _date: (Path("/nonexistent/atop"), Path("/nonexistent/pmon")), + ) + monkeypatch.setattr(usage_report, "_aggregate_segments", lambda *_a: _aggregates()) + monkeypatch.setattr(usage_report, "_log_descriptions", lambda _s: ("a", "p")) + monkeypatch.setattr( + usage_report, "_render_report", lambda *_a, **k: k["period_line"] + ) + emitted: list[str] = [] + monkeypatch.setattr(usage_report, "_emit", lambda _args, r: emitted.append(r)) + + rc = usage_report._run_single_day( + _args(date="20260817", quiet=True), + _dt.datetime.now().astimezone(), + ) + + assert rc == 0 + assert emitted == ["- **Reporting period**: 20260817 (single day)"] + + +def test_run_single_day_defaults_an_empty_window_to_a_day( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A window with no measured seconds is treated as a full day.""" + aggs = _aggregates(seconds=0) + monkeypatch.setattr(usage_report, "_preflight", lambda _log: None) + monkeypatch.setattr( + usage_report, + "_resolve_logs", + lambda _date: (Path("/nonexistent/atop"), Path("/nonexistent/pmon")), + ) + monkeypatch.setattr(usage_report, "_aggregate_segments", lambda *_a: aggs) + monkeypatch.setattr(usage_report, "_log_descriptions", lambda _s: ("a", "p")) + monkeypatch.setattr(usage_report, "_render_report", lambda *_a, **_k: "report") + monkeypatch.setattr(usage_report, "_emit", lambda *_a: None) + + usage_report._run_single_day( + _args(date="20260817", quiet=True), + _dt.datetime.now().astimezone(), + ) + + assert aggs.window.seconds == usage_report._SEC_PER_DAY diff --git a/linux_configuration/tests/test_usage_report_emit.py b/linux_configuration/tests/test_usage_report_emit.py new file mode 100644 index 00000000..65ab7c82 --- /dev/null +++ b/linux_configuration/tests/test_usage_report_emit.py @@ -0,0 +1,157 @@ +"""Tests for usage_report's output side and its preflight checks: clipboard +tool selection, stdout emission, the atop/log existence guards, and the +since-last-report run including its no-data path. +""" + +from __future__ import annotations + +from pathlib import Path +import subprocess + +from _usage_report_types import _Window +import pytest +import usage_report + + +def _args(**overrides: object) -> object: + """Build a parsed-args namespace with the parser's own defaults.""" + args = usage_report._build_parser().parse_args([]) + for key, value in overrides.items(): + setattr(args, key, value) + return args + + +def _aggregates(*, days_with_data: int = 1, seconds: int = 600) -> object: + """Build an _Aggregates with a window that looks like real coverage.""" + return usage_report._Aggregates( + cpu={}, + gpu={}, + window=_Window(distinct_samples=2, interval_s=600, seconds=seconds), + gpu_samples=0, + days_with_data=days_with_data, + ) + + +# --------------------------------------------------------------------------- # +# _preflight +# --------------------------------------------------------------------------- # +def test_preflight_exits_without_atop(monkeypatch: pytest.MonkeyPatch) -> None: + """A missing atop binary aborts with an install hint.""" + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: None) + + with pytest.raises(SystemExit) as excinfo: + usage_report._preflight(Path("/nonexistent/whatever")) + + assert "not installed" in str(excinfo.value) + + +def test_preflight_exits_without_log( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """A missing log file aborts and names the path.""" + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/atop") + missing = tmp_path / "absent" + + with pytest.raises(SystemExit) as excinfo: + usage_report._preflight(missing) + + assert str(missing) in str(excinfo.value) + + +def test_preflight_passes_when_both_present( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """With atop installed and the log present, preflight is silent.""" + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/atop") + log = tmp_path / "atop.log" + log.write_text("x", encoding="utf-8") + + assert usage_report._preflight(log) is None + + +# --------------------------------------------------------------------------- # +# _copy_to_clipboard +# --------------------------------------------------------------------------- # +def test_copy_to_clipboard_uses_first_available_tool( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """The first candidate present on PATH is the one invoked.""" + monkeypatch.setattr( + usage_report.shutil, + "which", + lambda name: "/usr/bin/xclip" if name == "xclip" else None, + ) + calls: list[tuple[str, ...]] = [] + monkeypatch.setattr( + usage_report.subprocess, + "run", + lambda cmd, **_k: calls.append(tuple(cmd)), + ) + + usage_report._copy_to_clipboard("hello") + + assert calls == [("xclip", "-selection", "clipboard")] + assert "copied 5 chars via xclip" in capsys.readouterr().err + + +def test_copy_to_clipboard_reports_a_failing_tool( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """A tool that errors is reported on stderr and not retried elsewhere.""" + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/wl-copy") + + def boom(*_a: object, **_k: object) -> None: + raise subprocess.CalledProcessError(1, "wl-copy") + + monkeypatch.setattr(usage_report.subprocess, "run", boom) + + usage_report._copy_to_clipboard("hello") + + assert "wl-copy failed" in capsys.readouterr().err + + +def test_copy_to_clipboard_without_any_tool( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """With no clipboard tool installed the copy is skipped, not fatal.""" + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: None) + + usage_report._copy_to_clipboard("hello") + + assert "skipping copy" in capsys.readouterr().err + + +# --------------------------------------------------------------------------- # +# _emit +# --------------------------------------------------------------------------- # +def test_emit_writes_stdout_and_copies( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """By default the report goes to stdout and the clipboard.""" + copied: list[str] = [] + monkeypatch.setattr(usage_report, "_copy_to_clipboard", copied.append) + + usage_report._emit(_args(no_clipboard=False), "REPORT") + + assert capsys.readouterr().out == "REPORT" + assert copied == ["REPORT"] + + +def test_emit_skips_clipboard_when_suppressed( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """--no-clipboard leaves stdout untouched but skips the copy.""" + copied: list[str] = [] + monkeypatch.setattr(usage_report, "_copy_to_clipboard", copied.append) + + usage_report._emit(_args(no_clipboard=True), "REPORT") + + assert capsys.readouterr().out == "REPORT" + assert copied == [] diff --git a/linux_configuration/tests/test_usage_report_run_since.py b/linux_configuration/tests/test_usage_report_run_since.py new file mode 100644 index 00000000..5cccf276 --- /dev/null +++ b/linux_configuration/tests/test_usage_report_run_since.py @@ -0,0 +1,154 @@ +"""Tests for usage_report's since-last-report run: the atop guard, the normal +report path, the no-data path, and when the saved timestamp advances. +""" + +from __future__ import annotations + +import datetime as _dt + +from _usage_report_types import _Window +import pytest +import usage_report + + +def _args(**overrides: object) -> object: + """Build a parsed-args namespace with the parser's own defaults.""" + args = usage_report._build_parser().parse_args([]) + for key, value in overrides.items(): + setattr(args, key, value) + return args + + +def _aggregates(*, days_with_data: int = 1, seconds: int = 600) -> object: + """Build an _Aggregates with a window that looks like real coverage.""" + return usage_report._Aggregates( + cpu={}, + gpu={}, + window=_Window(distinct_samples=2, interval_s=600, seconds=seconds), + gpu_samples=0, + days_with_data=days_with_data, + ) + + +# --------------------------------------------------------------------------- # +# _run_since +# --------------------------------------------------------------------------- # +def test_run_since_exits_without_atop(monkeypatch: pytest.MonkeyPatch) -> None: + """The multi-day path also refuses to run without atop installed.""" + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: None) + + with pytest.raises(SystemExit): + usage_report._run_since(_args(), _dt.datetime.now().astimezone()) + + +def test_run_since_reports_and_advances_state( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A normal run emits a report and moves the saved timestamp forward.""" + now = _dt.datetime.now().astimezone() + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/atop") + monkeypatch.setattr(usage_report, "_resolve_start", lambda *_a: now) + monkeypatch.setattr(usage_report, "_plan_segments", lambda *_a: []) + monkeypatch.setattr(usage_report, "_aggregate_segments", lambda *_a: _aggregates()) + monkeypatch.setattr(usage_report, "_log_descriptions", lambda _s: ("a", "p")) + monkeypatch.setattr(usage_report, "_render_report", lambda *_a, **_k: "report") + emitted: list[str] = [] + monkeypatch.setattr(usage_report, "_emit", lambda _a, r: emitted.append(r)) + advanced: list[object] = [] + monkeypatch.setattr(usage_report, "_write_last_generated", advanced.append) + + rc = usage_report._run_since(_args(quiet=True), now) + + assert rc == 0 + assert emitted == ["report"] + assert advanced == [now] + + +def test_run_since_with_no_data_still_advances_state( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Gap days produce a stderr note, no report, but the state still moves.""" + now = _dt.datetime.now().astimezone() + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/atop") + monkeypatch.setattr(usage_report, "_resolve_start", lambda *_a: now) + monkeypatch.setattr(usage_report, "_plan_segments", lambda *_a: []) + monkeypatch.setattr( + usage_report, + "_aggregate_segments", + lambda *_a: _aggregates(days_with_data=0), + ) + emitted: list[str] = [] + monkeypatch.setattr(usage_report, "_emit", lambda _a, r: emitted.append(r)) + advanced: list[object] = [] + monkeypatch.setattr(usage_report, "_write_last_generated", advanced.append) + + rc = usage_report._run_since(_args(quiet=True), now) + + assert rc == 0 + assert emitted == [] + assert advanced == [now] + assert "nothing to report" in capsys.readouterr().err + + +def test_run_since_with_no_data_leaves_state_when_suppressed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """--no-update-state keeps the saved timestamp even on the no-data path.""" + now = _dt.datetime.now().astimezone() + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/atop") + monkeypatch.setattr(usage_report, "_resolve_start", lambda *_a: now) + monkeypatch.setattr(usage_report, "_plan_segments", lambda *_a: []) + monkeypatch.setattr( + usage_report, + "_aggregate_segments", + lambda *_a: _aggregates(days_with_data=0), + ) + advanced: list[object] = [] + monkeypatch.setattr(usage_report, "_write_last_generated", advanced.append) + + usage_report._run_since(_args(quiet=True, no_update_state=True), now) + + assert advanced == [] + + +def test_run_since_defaults_an_empty_window_to_a_day( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A window with no measured seconds is treated as a full day.""" + now = _dt.datetime.now().astimezone() + aggs = _aggregates(seconds=0) + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/atop") + monkeypatch.setattr(usage_report, "_resolve_start", lambda *_a: now) + monkeypatch.setattr(usage_report, "_plan_segments", lambda *_a: []) + monkeypatch.setattr(usage_report, "_aggregate_segments", lambda *_a: aggs) + monkeypatch.setattr(usage_report, "_log_descriptions", lambda _s: ("a", "p")) + monkeypatch.setattr(usage_report, "_render_report", lambda *_a, **_k: "report") + monkeypatch.setattr(usage_report, "_emit", lambda *_a: None) + monkeypatch.setattr(usage_report, "_write_last_generated", lambda *_a: None) + + usage_report._run_since(_args(quiet=True), now) + + assert aggs.window.seconds == usage_report._SEC_PER_DAY + + +def test_run_since_leaves_state_when_suppressed_after_a_report( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """--no-update-state keeps the timestamp even when a report was emitted.""" + now = _dt.datetime.now().astimezone() + monkeypatch.setattr(usage_report.shutil, "which", lambda _n: "/usr/bin/atop") + monkeypatch.setattr(usage_report, "_resolve_start", lambda *_a: now) + monkeypatch.setattr(usage_report, "_plan_segments", lambda *_a: []) + monkeypatch.setattr(usage_report, "_aggregate_segments", lambda *_a: _aggregates()) + monkeypatch.setattr(usage_report, "_log_descriptions", lambda _s: ("a", "p")) + monkeypatch.setattr(usage_report, "_render_report", lambda *_a, **_k: "report") + emitted: list[str] = [] + monkeypatch.setattr(usage_report, "_emit", lambda _a, r: emitted.append(r)) + advanced: list[object] = [] + monkeypatch.setattr(usage_report, "_write_last_generated", advanced.append) + + usage_report._run_since(_args(quiet=True, no_update_state=True), now) + + assert emitted == ["report"] + assert advanced == [] diff --git a/linux_configuration/tests/test_usage_report_segments.py b/linux_configuration/tests/test_usage_report_segments.py new file mode 100644 index 00000000..108b938a --- /dev/null +++ b/linux_configuration/tests/test_usage_report_segments.py @@ -0,0 +1,112 @@ +"""Tests for usage_report's per-day segment aggregation, the log-description +strings, and the deprecated _compute_window shim. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from _usage_report_types import _Progress, _Window +import usage_report + +if TYPE_CHECKING: + import pytest + + +def _progress() -> _Progress: + """A progress reporter that never draws, so stderr stays clean.""" + return _Progress(enabled=False, total_stages=1) + + +# --------------------------------------------------------------------------- # +# _compute_window (deprecated shim; no callers remain in-tree) +# --------------------------------------------------------------------------- # +def test_compute_window_returns_the_aggregate_window( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The shim forwards to aggregate_atop and hands back its window.""" + window = _Window(distinct_samples=3, interval_s=600, seconds=1200) + monkeypatch.setattr(usage_report, "aggregate_atop", lambda *_a: ({}, window)) + + result = usage_report._compute_window(Path("/nonexistent/atop"), _progress()) + + assert result is window + assert result.seconds == 1200 + + +def test_compute_window_defaults_an_empty_window_to_a_day( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A window with no measured seconds is widened to a full day.""" + window = _Window(distinct_samples=1) + monkeypatch.setattr(usage_report, "aggregate_atop", lambda *_a: ({}, window)) + + assert ( + usage_report._compute_window(Path("/nonexistent/atop"), _progress()).seconds + == usage_report._SEC_PER_DAY + ) + + +# --------------------------------------------------------------------------- # +# _aggregate_segments / _log_descriptions +# --------------------------------------------------------------------------- # +def test_aggregate_segments_skips_missing_atop_logs( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """A gap day contributes no atop data but its pmon log is still read.""" + present = tmp_path / "atop-present" + present.write_text("x", encoding="utf-8") + segments = [ + usage_report._Segment(present, tmp_path / "pmon-a"), + usage_report._Segment(tmp_path / "atop-absent", tmp_path / "pmon-b"), + ] + monkeypatch.setattr( + usage_report, + "aggregate_atop", + lambda *_a: ({}, _Window(distinct_samples=2, seconds=600)), + ) + pmon_calls: list[Path] = [] + + def fake_pmon(log: Path, *_a: object) -> tuple[dict[str, object], int]: + pmon_calls.append(log) + return {}, 5 + + monkeypatch.setattr(usage_report, "aggregate_pmon", fake_pmon) + + aggs = usage_report._aggregate_segments(segments, _progress()) + + assert aggs.days_with_data == 1 + assert aggs.gpu_samples == 10 + assert len(pmon_calls) == 2 + + +def test_log_descriptions_names_only_existing_logs(tmp_path: Path) -> None: + """Descriptions cover the logs that are actually on disk.""" + atop = tmp_path / "atop" + atop.write_text("x", encoding="utf-8") + segments = [usage_report._Segment(atop, tmp_path / "pmon-absent")] + + atop_desc, pmon_desc = usage_report._log_descriptions(segments) + + assert str(atop) in atop_desc + assert "none" in pmon_desc.lower() or pmon_desc + + +def test_aggregate_segments_ignores_a_log_with_no_samples( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """A present atop log that yields no samples does not count as a data day.""" + present = tmp_path / "atop-empty" + present.write_text("x", encoding="utf-8") + monkeypatch.setattr(usage_report, "aggregate_atop", lambda *_a: ({}, _Window())) + monkeypatch.setattr(usage_report, "aggregate_pmon", lambda *_a: ({}, 0)) + + aggs = usage_report._aggregate_segments( + [usage_report._Segment(present, tmp_path / "pmon")], + _progress(), + ) + + assert aggs.days_with_data == 0