Compare commits

..

No commits in common. "82fe807deb6cd88a9ef235c4ae6b3765961f3813" and "5029d4685b33896c19e7d92195593d0fc25e8ae4" have entirely different histories.

6 changed files with 146 additions and 336 deletions

View File

@ -38,64 +38,15 @@ _defined_ in module X. **Always finish a re-export split with**
PYTHONPATH=. python3 -c "from python_pkg.pkg import mod; mod.TheName"
```
## `mock.patch` pins names to a module — run this grep FIRST
Two other things the gate will not catch for you:
**This is the constraint that decides where a seam can go.** `patch("mod.name")`
rebinds an attribute on `mod`. If you move a function to `_new.py`, that
function resolves its collaborators through `_new`'s globals, and the patch on
`mod` no longer reaches it. Tests then fail with either
`<module> does not have the attribute 'x'` or, worse, a real call to the thing
that was supposed to be mocked.
Before choosing any seam, list every pinned name in the package:
```bash
grep -ohP 'patch\((?:f")?(?:\{MOD\}|"[\w.]+)\.\K[\w]+' <pkg>/tests/*.py | sort -u
```
Everything it prints — **including plain imports like `subprocess`, `shutil`,
`Path`, `time`, and collaborators imported from sibling modules** — must stay
resolvable in the module the test names. Two consequences:
- A function that _calls_ a patched collaborator has to stay in that module,
or move together with it.
- `patch.object(mod, "tk", fake)` is the same rule in another spelling.
`test_ui.py` uses it, which is why every `tkinter` line had to stay in
`ui.py` — moving widget construction out errored 22 tests.
`brother_printer` is the extreme case: its test modules patch ~90 distinct
names across the package, including `estimate_consumable_life` on `display`.
An otherwise clean extraction of the page-count block was reverted because of
exactly that. Grep first, then pick the seam.
**Tests that call private methods pin them too** — `test_player.py` calls
`mpv._note_errors(...)`, so that method stayed as a one-line delegate to the
moved implementation. That is the escape hatch for a **one-off** pinned name:
leave a thin delegate behind. It does not scale — under `select = ["ALL"]`
every delegate needs a full docstring with `Args:`, so a 25-line function
leaves a 12-line stub. Eight of those to make a line count is the cap-gaming
the spec forbids.
### You may edit the tests to follow the code (agreed 2026-08-16)
When a patch target moves, **update the patch target**. Bounded by:
- no assertion changed,
- no test deleted, skipped or weakened,
- the pass **count** identical before and after (record it in the evidence).
Updating `MOD = "python_pkg.pkg.display"` to the function's new home is
bookkeeping, not weakening. Do it **per patched name**, never as a blanket
swap: a name patched from two different test modules (`_display_report_header`
is patched by both `test_display.py` and `test_display_part2.py`) has to stay
reachable from both, so it belongs in whichever module keeps the shared entry
points.
The test modules are usually the best map of where the seam goes. In
`brother_printer`, `test_display.py` patches only USB-side helpers,
`test_display_part2.py` only network-side, and `test_display_part3.py` only the
page-count collaborators — three concerns in one 427-line module. Split the
source to match, and let each test module's `MOD` follow.
- **Check what the tests patch before choosing a seam.** `test_ui.py` does
`patch.object(ui, "tk", fake)`, so every line touching `tkinter` had to stay
in `ui.py`; moving widget construction out errored 22 tests. Grep the test
file for `patch.object(<module>` first and treat those names as pinned.
- **Tests that call private methods pin them too** — `test_player.py` calls
`mpv._note_errors(...)`, so that method stayed as a one-line delegate to the
moved implementation.
**Budget the new import block and `__all__` before deciding a two-way split is
enough.** Five splits so far landed 2–16 lines over the cap after the first cut

View File

@ -1,41 +0,0 @@
{
"intent": "Reduce python_pkg/brother_printer/display.py by extracting the parts no test patches, and collapse the duplicated toner/drum bar rendering into one helper. This does NOT bring display.py under the 250-line cap -- it is 342 and needs a further ~92 lines removed, which is blocked on a decision about editing test files.",
"scope": [
"python_pkg/brother_printer/display.py",
"python_pkg/brother_printer/_supply.py (new)",
"python_pkg/brother_printer/_severity.py (new)",
"Non-goal: no assertion changed, no test deleted or weakened"
],
"changes": [
"Extracted the supply-level arithmetic into _supply.py: _classify_percentage_level, _classify_supply_level, _format_supply_bar, _process_supply_item, _parse_supply_value, _collect_supply_items. These are imported by the tests, not patched, so they were free to move.",
"Extracted the three _SEVERITY_* lookup tables into _severity.py. Pure data, patched by nothing.",
"Added _supply.render_life_bar and used it for both the toner and drum bars in _display_page_count_estimate. Those two blocks were the same logic with different colours and notes -- this removes the duplication rather than just relocating it.",
"display.py re-exports the moved supply names through __all__, because tests/test_display.py imports them from display.",
"display.py 427 -> 342 lines; _supply.py 131; _severity.py 44."
],
"verification": [
{
"command": "python3 -m pytest python_pkg/brother_printer/tests/ -q",
"result": "pass",
"evidence": "402 passed in 1.76s -- the same count as before the change, run after each of the three extractions."
},
{
"command": "pre-commit run --files python_pkg/brother_printer/display.py python_pkg/brother_printer/_supply.py python_pkg/brother_printer/_severity.py",
"result": "pass",
"evidence": "ruff, ruff format, mypy, pylint, bandit and the coverage-gated pytest all pass. Only the evidence-artifact hook remained, which this file satisfies. No suppression added; a pylint C0104 on the name 'bar' was fixed by renaming it, not disabling the check."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all",
"result": "fail",
"evidence": "display.py is still 342 lines and remains a violation. Stated explicitly: this commit reduces it and removes real duplication, but does not clear it."
}
],
"risks": [
"The remaining ~92 lines cannot be extracted without either editing test files or adding ~8 pure-indirection delegate functions. brother_printer's test modules patch roughly 90 names across the package via patch(f'{MOD}.<name>'), and mock.patch pins a name to the module it is patched on: a function that moves to a new module resolves its collaborators through the new module's globals, so the patch no longer reaches it. An earlier attempt to move the page-count block was reverted for exactly this reason (AttributeError: module display does not have the attribute 'estimate_consumable_life').",
"_display_report_header is patched from both test_display.py and test_display_part2.py, so any split of display.py into USB and network halves has to keep that function reachable from both patch sites."
],
"rollback": [
"git revert the commit; display.py returns to 427 lines and the two new modules are deleted.",
"After rollback, run python3 -m pytest python_pkg/brother_printer/tests/ -q and confirm it still reports 402 passed."
]
}

View File

@ -1,44 +0,0 @@
"""The icon, colour and closing summary for each PJL severity.
Split out of :mod:`python_pkg.brother_printer.display` to keep it under the
250-line cap. Pure data: no test patches these tables, so unlike most of
``display`` they were free to move.
"""
from __future__ import annotations
from python_pkg.brother_printer.constants import (
BOLD,
CYAN,
GREEN,
RED,
RESET,
YELLOW,
)
_SEVERITY_ICONS: dict[str, str] = {
"ok": "✓",
"info": "i",
"warn": "⚡",
"critical": "⚠",
}
_SEVERITY_COLORS: dict[str, str] = {
"ok": GREEN,
"info": CYAN,
"warn": YELLOW,
"critical": RED,
}
_SEVERITY_SUMMARIES: dict[str, str] = {
"ok": f"{GREEN}{BOLD}✓ Printer is healthy. No replacements needed.{RESET}",
"info": (
f"{CYAN}{BOLD}i Printer is busy/processing. No replacements needed.{RESET}"
),
"warn": (
f"{YELLOW}{BOLD}⚡ WARNING: Maintenance will be needed"
f" soon.{RESET}\n{YELLOW} Order replacement parts"
f" now to avoid interruption.{RESET}"
),
"critical": (
f"{RED}{BOLD}⚠ ACTION REQUIRED: Replacement or fix needed now!{RESET}"
),
}

View File

@ -1,131 +0,0 @@
"""Turning a raw SNMP supply reading into a percentage, a bar and a verdict.
Split out of :mod:`python_pkg.brother_printer.display` to keep it under the
250-line cap. Only the arithmetic lives here. The functions that *print*
(``_display_supply_levels``, ``_display_supply_warnings``) stay in ``display``
because ``tests/test_display_part2.py`` patches them there, and a patched name
has to remain resolvable in the module the test names.
``display`` re-exports everything below, because the tests import these names
from there rather than from here.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from python_pkg.brother_printer.constants import (
BOLD,
GREEN,
PROGRESS_BAR_WIDTH,
RED,
RESET,
SNMP_LEVEL_LOW,
SNMP_LEVEL_OK,
SUPPLY_LOW_PCT,
SUPPLY_WARN_PCT,
YELLOW,
_out,
)
from python_pkg.brother_printer.data_classes import SupplyStatus
if TYPE_CHECKING:
from python_pkg.brother_printer.data_classes import NetworkResult
def _classify_percentage_level(desc: str, pct: int) -> tuple[int, str, str, str, bool]:
"""Classify a supply by its calculated percentage."""
if pct <= SUPPLY_LOW_PCT:
return pct, f"{pct}%", RED, f"{desc} at {pct}%.", True
if pct <= SUPPLY_WARN_PCT:
return pct, f"{pct}%", YELLOW, f"{desc} at {pct}% -- order soon.", False
return pct, f"{pct}%", GREEN, "", False
def _classify_supply_level(
desc: str, max_val: int, level: int
) -> tuple[int, str, str, str, bool]:
"""Classify a supply level. Returns (pct, status, color, warning, replace)."""
if level == SNMP_LEVEL_OK:
return -1, "OK", GREEN, "", False
if level == SNMP_LEVEL_LOW:
return -1, "LOW", RED, f"{desc} is LOW.", True
if level == 0:
return 0, "EMPTY", RED, f"{desc} is EMPTY -- replace now!", True
if max_val > 0:
pct = min(level * 100 // max_val, 100)
return _classify_percentage_level(desc, pct)
return -1, "", GREEN, "", False
def _format_supply_bar(pct: int) -> str:
"""Build a progress bar string for a supply percentage."""
if pct < 0:
return ""
filled = pct * PROGRESS_BAR_WIDTH // 100
empty = PROGRESS_BAR_WIDTH - filled
return f"[{'█' * filled}{'░' * empty}]"
def _process_supply_item(desc: str, max_val: int, level: int) -> SupplyStatus:
"""Process a single supply item into display info."""
pct, status_text, color, warning, needs_replacement = _classify_supply_level(
desc, max_val, level
)
bar_text = _format_supply_bar(pct)
return SupplyStatus(color, bar_text, status_text, warning, needs_replacement)
def _parse_supply_value(values: list[str], index: int) -> int:
"""Safely parse an integer from a supply value list."""
try:
return int(values[index])
except (IndexError, ValueError):
return 0
def _collect_supply_items(
result: NetworkResult,
) -> tuple[list[SupplyStatus], list[str]]:
"""Parse and collect supply items with their descriptions."""
items: list[SupplyStatus] = []
descs: list[str] = []
for i, desc in enumerate(result.supplies.descriptions):
max_val = _parse_supply_value(result.supplies.max_values, i)
level = _parse_supply_value(result.supplies.levels, i)
items.append(_process_supply_item(desc, max_val, level))
descs.append(desc)
return items, descs
def render_life_bar(
label: str,
pct: int,
*,
exhausted: bool = False,
low: bool = False,
exhausted_note: str = "",
low_note: str = "",
) -> None:
"""Print one consumable's remaining-life bar.
The toner and drum bars in the page-count estimate were byte-for-byte the
same logic with different colours and notes, which is what this collapses.
Args:
label: Displayed name, already padded by the caller if needed.
pct: Percentage remaining, 0-100.
exhausted: Render red with ``exhausted_note``.
low: Render yellow with ``low_note``. Ignored when *exhausted*.
exhausted_note: Suffix shown when *exhausted*.
low_note: Suffix shown when *low*.
"""
filled = pct * PROGRESS_BAR_WIDTH // 100
meter = f"[{'█' * filled}{'░' * (PROGRESS_BAR_WIDTH - filled)}]"
if exhausted:
color, note = RED, exhausted_note
elif low:
color, note = YELLOW, low_note
else:
color, note = GREEN, ""
_out(f" {BOLD}{label}{RESET} {color}{meter} ~{pct}%{note}{RESET}")

View File

@ -3,34 +3,20 @@
from __future__ import annotations
import sys
from typing import TYPE_CHECKING
# ── Shared display helpers ───────────────────────────────────────────
# Re-exported through __all__: tests/test_display.py imports these names from
# this module. Only the un-patched supply *maths* moved to _supply -- everything
# the tests reach with mock.patch has to stay resolvable here.
from python_pkg.brother_printer._severity import (
_SEVERITY_COLORS,
_SEVERITY_ICONS,
_SEVERITY_SUMMARIES,
)
from python_pkg.brother_printer._supply import (
_classify_percentage_level,
_classify_supply_level,
_collect_supply_items,
_format_supply_bar,
_parse_supply_value,
_process_supply_item,
render_life_bar,
)
from python_pkg.brother_printer.constants import (
BOLD,
CYAN,
DIM,
DRUM_RATED_PAGES,
GREEN,
PROGRESS_BAR_WIDTH,
RED,
RESET,
SNMP_LEVEL_LOW,
SNMP_LEVEL_OK,
SUPPLY_LOW_PCT,
SUPPLY_WARN_PCT,
TONER_RATED_PAGES,
YELLOW,
_out,
@ -44,23 +30,13 @@ from python_pkg.brother_printer.cups_queue import (
display_cups_queue_status,
get_cups_queue_status,
)
from python_pkg.brother_printer.data_classes import (
NetworkResult,
SupplyStatus,
USBResult,
)
if TYPE_CHECKING:
from python_pkg.brother_printer.data_classes import (
NetworkResult,
USBResult,
)
__all__ = [
"_classify_percentage_level",
"_classify_supply_level",
"_collect_supply_items",
"_format_supply_bar",
"_parse_supply_value",
"_process_supply_item",
"display_network_results",
"display_usb_results",
]
# ── Shared display helpers ───────────────────────────────────────────
def _display_report_header() -> None:
@ -125,20 +101,36 @@ def _display_page_count_estimate(printer_total: int = 0) -> None:
f" and reads high.{RESET}"
)
_out()
render_life_bar(
"Toner:",
estimate.toner_pct_remaining,
exhausted=estimate.toner_exhausted,
low=estimate.toner_low,
exhausted_note=" ← REPLACE NOW",
low_note=" ← order soon",
)
render_life_bar(
"Drum: ",
estimate.drum_pct_remaining,
low=estimate.drum_near_end,
low_note=" ← nearing end",
# Toner bar
toner_pct = estimate.toner_pct_remaining
toner_filled = toner_pct * PROGRESS_BAR_WIDTH // 100
toner_empty = PROGRESS_BAR_WIDTH - toner_filled
toner_bar = f"[{'█' * toner_filled}{'░' * toner_empty}]"
if estimate.toner_exhausted:
toner_color = RED
toner_note = " ← REPLACE NOW"
elif estimate.toner_low:
toner_color = YELLOW
toner_note = " ← order soon"
else:
toner_color = GREEN
toner_note = ""
_out(
f" {BOLD}Toner:{RESET} {toner_color}{toner_bar} ~{toner_pct}%"
f"{toner_note}{RESET}"
)
# Drum bar
drum_pct = estimate.drum_pct_remaining
drum_filled = drum_pct * PROGRESS_BAR_WIDTH // 100
drum_empty = PROGRESS_BAR_WIDTH - drum_filled
drum_bar = f"[{'█' * drum_filled}{'░' * drum_empty}]"
if estimate.drum_near_end:
drum_color = YELLOW
drum_note = " ← nearing end"
else:
drum_color = GREEN
drum_note = ""
_out(f" {BOLD}Drum:{RESET} {drum_color}{drum_bar} ~{drum_pct}%{drum_note}{RESET}")
_out(
f" {DIM}Based on pages since last replacement"
f" vs rated capacity (toner ~{TONER_RATED_PAGES},"
@ -191,6 +183,34 @@ def _display_usb_device_info(result: USBResult) -> None:
_out(f"{BOLD}Toner Save:{RESET} OFF")
_SEVERITY_ICONS: dict[str, str] = {
"ok": "✓",
"info": "i",
"warn": "⚡",
"critical": "⚠",
}
_SEVERITY_COLORS: dict[str, str] = {
"ok": GREEN,
"info": CYAN,
"warn": YELLOW,
"critical": RED,
}
_SEVERITY_SUMMARIES: dict[str, str] = {
"ok": f"{GREEN}{BOLD}✓ Printer is healthy. No replacements needed.{RESET}",
"info": (
f"{CYAN}{BOLD}i Printer is busy/processing. No replacements needed.{RESET}"
),
"warn": (
f"{YELLOW}{BOLD}⚡ WARNING: Maintenance will be needed"
f" soon.{RESET}\n{YELLOW} Order replacement parts"
f" now to avoid interruption.{RESET}"
),
"critical": (
f"{RED}{BOLD}⚠ ACTION REQUIRED: Replacement or fix needed now!{RESET}"
),
}
def _format_status_detail(
severity: str, short_text: str, action: str, result: USBResult
) -> None:
@ -271,6 +291,49 @@ def display_usb_results(result: USBResult) -> None:
# ── Network supply level helpers ─────────────────────────────────────
def _classify_percentage_level(desc: str, pct: int) -> tuple[int, str, str, str, bool]:
"""Classify a supply by its calculated percentage."""
if pct <= SUPPLY_LOW_PCT:
return pct, f"{pct}%", RED, f"{desc} at {pct}%.", True
if pct <= SUPPLY_WARN_PCT:
return pct, f"{pct}%", YELLOW, f"{desc} at {pct}% -- order soon.", False
return pct, f"{pct}%", GREEN, "", False
def _classify_supply_level(
desc: str, max_val: int, level: int
) -> tuple[int, str, str, str, bool]:
"""Classify a supply level. Returns (pct, status, color, warning, replace)."""
if level == SNMP_LEVEL_OK:
return -1, "OK", GREEN, "", False
if level == SNMP_LEVEL_LOW:
return -1, "LOW", RED, f"{desc} is LOW.", True
if level == 0:
return 0, "EMPTY", RED, f"{desc} is EMPTY -- replace now!", True
if max_val > 0:
pct = min(level * 100 // max_val, 100)
return _classify_percentage_level(desc, pct)
return -1, "", GREEN, "", False
def _format_supply_bar(pct: int) -> str:
"""Build a progress bar string for a supply percentage."""
if pct < 0:
return ""
filled = pct * PROGRESS_BAR_WIDTH // 100
empty = PROGRESS_BAR_WIDTH - filled
return f"[{'█' * filled}{'░' * empty}]"
def _process_supply_item(desc: str, max_val: int, level: int) -> SupplyStatus:
"""Process a single supply item into display info."""
pct, status_text, color, warning, needs_replacement = _classify_supply_level(
desc, max_val, level
)
bar_text = _format_supply_bar(pct)
return SupplyStatus(color, bar_text, status_text, warning, needs_replacement)
def _display_supply_warnings(*, needs_replacement: bool, warnings: list[str]) -> None:
"""Display supply level warnings summary."""
_out()
@ -286,6 +349,28 @@ def _display_supply_warnings(*, needs_replacement: bool, warnings: list[str]) ->
_out(f"{GREEN}{BOLD}✓ All consumables are at healthy levels.{RESET}")
def _parse_supply_value(values: list[str], index: int) -> int:
"""Safely parse an integer from a supply value list."""
try:
return int(values[index])
except (IndexError, ValueError):
return 0
def _collect_supply_items(
result: NetworkResult,
) -> tuple[list[SupplyStatus], list[str]]:
"""Parse and collect supply items with their descriptions."""
items: list[SupplyStatus] = []
descs: list[str] = []
for i, desc in enumerate(result.supplies.descriptions):
max_val = _parse_supply_value(result.supplies.max_values, i)
level = _parse_supply_value(result.supplies.levels, i)
items.append(_process_supply_item(desc, max_val, level))
descs.append(desc)
return items, descs
def _display_supply_levels(result: NetworkResult) -> None:
"""Display consumable supply levels section."""
_out()

View File

@ -6,9 +6,10 @@
## Where things stand
**183 files** over 250 lines (was 198). Everything is committed and pushed to
`main` at `9e688c5`; the tree is clean. The three unrelated edits an earlier
handoff warned about (`README.md`, the two `analysis_options.yaml`) are gone.
**184 files** over 250 lines (was 198). All work so far is committed and pushed
to `main`; the tree is clean. The three unrelated edits an earlier handoff
warned about (`README.md`, the two `analysis_options.yaml`) are no longer
present.
Done already (do not redo):
@ -20,12 +21,8 @@ Done already (do not redo):
`cli` 282→247, `review` 330→196, `net` 335→109, `store` 382→202,
`downloader` 420→238, `player` 373→235, `ui` 398→242
- `e03fbd1` `wsg_grabber/tests/test_review.py` 297 → 112 + two new modules
- `2832b78` `brother_printer/display.py` 427 → 342 — **partial, still a
violation.** Extracted `_supply.py` + `_severity.py` and deduped the
toner/drum bars. The last ~92 lines were blocked on `mock.patch` pinning,
which the decision below now unblocks.
`git log --oneline --grep='cap'` is the authoritative list.
`git log --oneline --grep='250-line cap'` is the authoritative list.
## The live worklist
@ -61,13 +58,6 @@ of you inventing a new boundary for them.
6. Shell verification is `bash -n` + `shellcheck` + `systemctl cat` path checks.
**Never execute enforcement scripts that mutate the phone or the live system.**
7. One commit per logical unit.
8. **Editing test files to follow moved code is allowed** (2026-08-16), bounded
by: no assertion changed, nothing deleted/skipped/weakened, and an identical
pass count before and after. See `docs/python-split-recipes.md`. Do not
re-ask this — an earlier session wrongly treated tests as untouchable and
stalled on `brother_printer` because of it.
9. Per-commit gate is `pre-commit run --files <changed>`; the real `git commit`
is the full gate (it adds jscpd). Push per directory tranche, not per commit.
## The constraint that will bite you