mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 19:16:18 +01:00
Compare commits
No commits in common. "2c01a0267ebf62e1a2ffc7db840bcec97441c80c" and "ad3d70f197368503a7ff14bafcde69a84d8f3b03" have entirely different histories.
2c01a0267e
...
ad3d70f197
@ -1,19 +0,0 @@
|
||||
{
|
||||
"title": "Split the brother_printer cups_queue test modules under the 250-line cap",
|
||||
"objective": "Bring test_cups_queue.py (458 lines) and test_cups_queue_part2.py (278 lines) under the repo-wide 250-line cap by partitioning them along the class boundaries the source split already established, without losing or weakening a single test.",
|
||||
"acceptance_criteria": [
|
||||
"All six cups_queue test modules are at most 250 lines.",
|
||||
"The brother_printer suite still reports exactly 402 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the brother_printer source modules.",
|
||||
"No MOD constant changes: every name these tests patch already lives in the module the file names, so the split is a pure partition of test classes.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened; whole test classes move verbatim and only the import blocks are adjusted to what each file actually uses.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts.",
|
||||
"Touching the brother_printer source, which is already under the cap.",
|
||||
"Splitting the remaining over-cap test modules (test_cups_service.py, test_display.py, test_usb_query.py and the consumables pair), which are separate commits.",
|
||||
"Introducing a shared conftest.py: these classes need no shared fixture builders, and an unnecessary one would push jscpd toward its duplication threshold."
|
||||
],
|
||||
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (expects exactly 402 passed), plus pre-commit run --files on the touched files, plus bash ~/utils/scripts/check_file_length.sh --all for the cap."
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
{
|
||||
"title": "Split the brother_printer cups_service test modules under the 250-line cap",
|
||||
"objective": "Bring test_cups_service.py (390 lines), test_cups_service_part2.py (261) and test_cups_service_part3.py (260) under the repo-wide 250-line cap by partitioning them at class and method boundaries, and rename the part-numbered survivors after the concern they cover.",
|
||||
"acceptance_criteria": [
|
||||
"Every cups_service and _cups_fallback test module is at most 250 lines.",
|
||||
"The brother_printer suite still reports exactly 402 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the brother_printer source modules.",
|
||||
"No MOD constant changes: the source split in the previous commit already put every patched name in the module these files name.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened; whole classes and whole methods move verbatim and only the import blocks are adjusted.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts.",
|
||||
"Touching the brother_printer source, which is already under the cap.",
|
||||
"Splitting test_display.py, test_usb_query.py, test_check_brother_printer.py or the consumables pair, which are separate commits.",
|
||||
"Introducing a shared conftest.py; these classes build their mocks inline and need no shared fixture builders."
|
||||
],
|
||||
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (expects exactly 402 passed), plus pre-commit run --files on the touched files, plus bash ~/utils/scripts/check_file_length.sh --all for the cap."
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
{
|
||||
"title": "Split the brother_printer display and usb_query test modules under the 250-line cap",
|
||||
"objective": "Bring test_display.py (363 lines) and test_usb_query.py (328) under the repo-wide 250-line cap by partitioning them at class boundaries, and retire display.py's now-dead __all__ re-export block once no test reaches the supply helpers through it.",
|
||||
"acceptance_criteria": [
|
||||
"test_display.py, test_supply_levels.py, test_usb_query.py and test_usb_query_sequence.py are each at most 250 lines.",
|
||||
"The brother_printer suite still reports exactly 402 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the brother_printer source modules.",
|
||||
"display.py keeps every name that test_display.py and test_display_part2.py patch on it as a real module attribute, verified by an import-time probe rather than inferred from a green run.",
|
||||
"The six _supply names are removed from display.py's __all__ only after confirming by grep that no source module and no test still imports them through display.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened; whole classes move verbatim and only the import blocks are adjusted.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts.",
|
||||
"Moving _display_supply_levels or _display_supply_warnings out of display.py: test_display_part2.py patches _display_supply_levels there.",
|
||||
"Splitting test_check_brother_printer.py or the consumables pair, which are separate commits."
|
||||
],
|
||||
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (expects exactly 402 passed), plus the display attribute probe, plus pre-commit run --files on the touched files, plus bash ~/utils/scripts/check_file_length.sh --all for the cap."
|
||||
}
|
||||
@ -1,18 +0,0 @@
|
||||
{
|
||||
"title": "Clear the last three brother_printer test modules over the 250-line cap",
|
||||
"objective": "Bring test_check_brother_printer.py (275 lines), test_consumables.py (272) and test_consumables_part2.py (273) under the repo-wide 250-line cap, taking python_pkg/brother_printer from fifteen violations to zero.",
|
||||
"acceptance_criteria": [
|
||||
"bash ~/utils/scripts/check_file_length.sh --all lists no file under python_pkg/brother_printer.",
|
||||
"The brother_printer suite still reports exactly 402 passing tests -- the same count as at the start of this whole package pass, proving no test was dropped or silently skipped across any of the eight commits.",
|
||||
"The package keeps 100% branch coverage of the brother_printer source modules.",
|
||||
"test_consumables_part2.py's split removes the need for its second MOD_PD constant: the tests that needed it are exactly the ones that move, so each resulting file has one module under test again.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened; whole classes move verbatim and only the import blocks are adjusted.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts.",
|
||||
"Touching the brother_printer source, which is already under the cap.",
|
||||
"Other packages' violations, which are separate commits."
|
||||
],
|
||||
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (expects exactly 402 passed), plus bash ~/utils/scripts/check_file_length.sh --all showing no brother_printer entry, plus pre-commit run --files on the touched files."
|
||||
}
|
||||
@ -1,43 +0,0 @@
|
||||
{
|
||||
"intent": "Bring the two over-cap cups_queue test modules under the 250-line cap by partitioning them by test class, with no change to what is tested.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/tests/test_cups_queue.py (458 -> 167)",
|
||||
"python_pkg/brother_printer/tests/test_cups_queue_actions.py, test_cups_queue_backend.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_cups_queue_part2.py -> test_cups_queue_menu.py (278 -> 131)",
|
||||
"python_pkg/brother_printer/tests/test_cups_queue_handlers.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_cups_queue_part3.py -> test_cups_queue_display.py (rename only)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"test_cups_queue.py split three ways at class boundaries: the lpstat parsing and get_cups_queue_status tests stay, the four _cups_* action primitives go to test_cups_queue_actions.py, and the health check plus backend-error log scanning go to test_cups_queue_backend.py.",
|
||||
"test_cups_queue_part2.py split at TestHandleDisabledWithJobs: the menu and the five _dwj_* choices stay, the four _handle_* dispatchers go to test_cups_queue_handlers.py.",
|
||||
"No MOD constant changed anywhere in this commit. Unlike the source splits, every patched name already lives in the module each file names, so this is a pure partition of test classes.",
|
||||
"Import blocks trimmed to what each file uses: the original lost eight now-unmoved names and StringIO, the backend file needed subprocess added for its TimeoutExpired cases, and the handlers file needed CUPSJob. test_cups_queue_part2.py dropped its four _handle_* imports but keeps patching them by string, since _offer_queue_fix dispatches to them.",
|
||||
"Renamed the two part-numbered survivors to test_cups_queue_menu.py and test_cups_queue_display.py so the file name says which concern it covers."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count. This is the check that matters here: a partition that dropped a whole class would still report a green run."
|
||||
},
|
||||
{
|
||||
"command": "wc -l python_pkg/brother_printer/tests/test_cups_queue*.py",
|
||||
"result": "pass",
|
||||
"evidence": "167, 157, 164, 161, 131 and 76 lines - all six modules under the 250-line cap."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the touched test files and artifacts>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit, name-tests-test and pytest-with-coverage all pass."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Trimming import blocks by hand can remove a name that is only reachable at runtime. Guarded by the pass count plus ruff's F401 sweep, and by checking whether each dropped name was still patched by string rather than imported.",
|
||||
"No shared conftest.py was introduced; if a later split of the remaining test modules needs the same fixture scaffolding, it belongs in tests/conftest.py rather than a fourth copy, to keep jscpd under its 2% duplication threshold."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the two originals return at 458 and 278 lines and the three new modules disappear.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
{
|
||||
"intent": "Bring the three over-cap cups_service test modules under the 250-line cap by partitioning them, with no change to what is tested.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/tests/test_cups_service.py (390 -> 172)",
|
||||
"python_pkg/brother_printer/tests/test_cups_service_port.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_cups_service_part2.py -> test_cups_economode.py (261 -> 115)",
|
||||
"python_pkg/brother_printer/tests/test_cups_status_mapping.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_cups_service_part3.py -> test_cups_fallback_query.py (260 -> 105)",
|
||||
"python_pkg/brother_printer/tests/test_cups_fallback_port_ok.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_cups_service_part4.py -> test_cups_ipp.py (rename only)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"test_cups_service.py split at TestPortStatusViaUsblp: the pyusb device info and CUPS service control tests stay, the usblp ioctl port-status tests go to test_cups_service_port.py.",
|
||||
"test_cups_service_part2.py split at TestCupsReasonsToError: economode and CUPS-state mapping stay, the error-reason mapping, port-status-to-code mapping and printer-name discovery go to test_cups_status_mapping.py.",
|
||||
"test_cups_service_part3.py was a single 235-line class, so it split by method at test_port_ok_toner_exhausted: the no-port-status and hardware-error cases stay, the four healthy-port cases become TestQueryUsbViaCupsPortOk in test_cups_fallback_port_ok.py.",
|
||||
"Renamed the four part-numbered files after what they actually cover: test_cups_economode.py, test_cups_fallback_query.py, test_cups_ipp.py, plus the two new names.",
|
||||
"Import blocks trimmed per file to what each uses. No MOD constant changed; the source split in the previous commits already put every patched name in the module these files name."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests/test_cups_status_mapping.py -q",
|
||||
"result": "fail then pass",
|
||||
"evidence": "The first run after the part2 split reported 2 failed, 400 passed: the moved classes needed subprocess (for TimeoutExpired) and get_status_info, which my hand-written import block had dropped. Both added; the suite returned to 402. Recorded because it is exactly the failure the pass-count check exists to catch."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep brother_printer",
|
||||
"result": "pass",
|
||||
"evidence": "No cups_service or _cups_fallback test module is listed any more; brother_printer is down to five over-cap files, all of them other test modules."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the touched test files and artifacts>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit, name-tests-test and pytest-with-coverage all pass."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Hand-trimmed import blocks are the live risk in this kind of split, as the two failures above show. A dropped name fails loudly at collection or call time, so the pass count catches it; the danger would be trimming an import that only a skipped test used.",
|
||||
"Three of these files are now named after _cups_fallback rather than cups_service, matching where the code moved in an earlier commit."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the three originals return at 390, 261 and 260 lines and the three new modules disappear.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -1,53 +0,0 @@
|
||||
{
|
||||
"intent": "Bring the display and usb_query test modules under the 250-line cap, and remove the re-export block in display.py that the earlier partial split left behind.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/tests/test_display.py (363 -> 204)",
|
||||
"python_pkg/brother_printer/tests/test_supply_levels.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_usb_query.py (328 -> 126)",
|
||||
"python_pkg/brother_printer/tests/test_usb_query_sequence.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_usb_query_part2.py -> test_pjl_io.py (rename only)",
|
||||
"python_pkg/brother_printer/display.py (dead re-export removed)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"test_display.py split at TestClassifyPercentageLevel: the USB report tests stay, the consumable supply maths and its display go to test_supply_levels.py, which imports the six classification helpers from _supply directly and the two printing functions from display.",
|
||||
"That was the last reader of the six _supply names through display, so display.py's __all__ shrank to the two public entry points, its _supply import narrowed to the one name it actually calls, and the stale comment claiming the tests reach those names through this module was deleted. Confirmed by grep across python_pkg that no source module or test still imports them from display.",
|
||||
"test_usb_query.py split at TestRetryPjlQuery: discovery and PJL response parsing stay, the retry, sequencing, result init and query_usb_pjl tests go to test_usb_query_sequence.py. Those patch the wire helpers on usb_query rather than _pjl_io, which is correct - that is the module whose globals the sequencing code resolves them through.",
|
||||
"Renamed test_usb_query_part2.py to test_pjl_io.py, matching the module it has covered since the source split."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (first run after the usb_query split)",
|
||||
"result": "fail then pass",
|
||||
"evidence": "Reported 9 failed, 393 passed: TestParsePagecount sat between the two moved classes and travelled with them, so the new module needed errno, os, _parse_status and _parse_pagecount that my hand-written import block had not anticipated. Added; the count returned to 402."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -c \"from python_pkg.brother_printer import display as d; d._display_report_header; d._display_supply_levels; d._display_supply_warnings; d._display_network_device_info; d._display_page_count_estimate; d.display_cups_queue_status; d.get_status_info\"",
|
||||
"result": "pass",
|
||||
"evidence": "runtime probe OK after the __all__ removal - every name the two display test modules patch is still a real attribute, so shrinking the re-export did not expose them to ruff's F401/TC001 rewrite."
|
||||
},
|
||||
{
|
||||
"command": "grep -rn 'display import' python_pkg/",
|
||||
"result": "pass",
|
||||
"evidence": "Only check_brother_printer.py, test_display.py, test_display_part2.py and test_supply_levels.py import from display, and none of them names a _supply helper - which is what made the __all__ entries safe to drop rather than merely unused-looking."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the touched files and artifacts>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff removed two imports the split left unused in test_usb_query.py; clean on re-run, and pytest-with-coverage passes."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Removing names from __all__ is the one edit here that could break a caller silently at import time rather than loudly. Guarded by the repo-wide grep and the attribute probe, not by the test run alone.",
|
||||
"test_usb_query_sequence.py patches _drain_buffer and pjl_query on usb_query while test_pjl_io.py patches their definitions on _pjl_io. Both are correct and must stay that way; collapsing them onto one module would unpatch the other caller."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the two originals return at 363 and 328 lines, display.py's __all__ comes back, and the two new modules disappear.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -1,48 +0,0 @@
|
||||
{
|
||||
"intent": "Clear the last three over-cap brother_printer test modules, taking the package from fifteen violations to zero.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/tests/test_consumables_part2.py -> test_counter_scales.py (273 -> 133)",
|
||||
"python_pkg/brother_printer/tests/test_page_delivery.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_consumables.py (272 -> 123)",
|
||||
"python_pkg/brother_printer/tests/test_consumable_estimate.py (new)",
|
||||
"python_pkg/brother_printer/tests/test_check_brother_printer.py (275 -> 112)",
|
||||
"python_pkg/brother_printer/tests/test_check_brother_printer_main.py (new)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"test_consumables_part2.py split at TestCheckPageDelivery, which is exactly the MOD/MOD_PD boundary an earlier commit introduced. The two classes that needed MOD_PD move to test_page_delivery.py and use a plain MOD there, so the two-constant workaround dissolves rather than being carried forward: each file has one module under test again.",
|
||||
"test_consumables.py split at TestEstimateConsumableLife: the state file and CUPS page-log tests stay, the life estimate and replacement resets go to test_consumable_estimate.py.",
|
||||
"test_check_brother_printer.py split at TestMain: discovery and the network/USB mode selection stay, the CLI entry point and the reset flags go to test_check_brother_printer_main.py.",
|
||||
"Renamed test_consumables_part2.py to test_counter_scales.py and narrowed its docstring, which had claimed to cover dropped-page detection that now lives in test_page_delivery.py."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed - the same count as before the first of the eight commits in this package pass, so nothing was lost anywhere along the way."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (first run after the check_brother_printer split)",
|
||||
"result": "fail then pass",
|
||||
"evidence": "Reported 4 failed, 398 passed: TestResetConsumableFromPrinter travelled with TestMain and needed USBResult, which my hand-written import block had omitted. Added; the count returned to 402."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep brother_printer",
|
||||
"result": "pass",
|
||||
"evidence": "No output - python_pkg/brother_printer is entirely under the 250-line cap, down from fifteen violations at the start of the session."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the touched test files and artifacts>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit, name-tests-test and pytest-with-coverage all pass."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Hand-trimmed import blocks remain the recurring risk in test splits; this pass hit it three times and the pass-count check caught it every time. A test that was already skipped would not be caught this way, but the package has none.",
|
||||
"Several test modules are now named after the private module they cover (_page_delivery, _pjl_io, _queue_fix). If a future split renames one of those source modules, the test file names go stale even though nothing breaks."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the three originals return at 275, 272 and 273 lines and the three new modules disappear.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -5,6 +5,10 @@ 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._page_count import (
|
||||
_display_consumables_reference,
|
||||
_display_page_count_estimate,
|
||||
@ -16,7 +20,14 @@ from python_pkg.brother_printer._severity import (
|
||||
_SEVERITY_ICONS,
|
||||
_SEVERITY_SUMMARIES,
|
||||
)
|
||||
from python_pkg.brother_printer._supply import _collect_supply_items
|
||||
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,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
BOLD,
|
||||
CYAN,
|
||||
@ -36,7 +47,16 @@ if TYPE_CHECKING:
|
||||
USBResult,
|
||||
)
|
||||
|
||||
__all__ = ["display_network_results", "display_usb_results"]
|
||||
__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",
|
||||
]
|
||||
|
||||
|
||||
def _display_report_header() -> None:
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""Tests for brother_printer.check_brother_printer - discovery and modes."""
|
||||
"""Tests for brother_printer.check_brother_printer module."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -11,8 +11,10 @@ import pytest
|
||||
from python_pkg.brother_printer.check_brother_printer import (
|
||||
_discover_network_printer,
|
||||
_no_printer_found,
|
||||
_reset_consumable_from_printer,
|
||||
_run_network_mode,
|
||||
_run_usb_mode,
|
||||
main,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import USBResult
|
||||
|
||||
@ -108,3 +110,166 @@ class TestNoPrinterFound:
|
||||
pytest.raises(SystemExit),
|
||||
):
|
||||
_no_printer_found()
|
||||
|
||||
|
||||
class TestMain:
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
def test_reset_toner(self, mock_reset: MagicMock) -> None:
|
||||
main(["--reset-toner"])
|
||||
mock_reset.assert_called_once_with("toner")
|
||||
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
def test_reset_drum(self, mock_reset: MagicMock) -> None:
|
||||
main(["--reset-drum"])
|
||||
mock_reset.assert_called_once_with("drum")
|
||||
|
||||
@patch(f"{MOD}.os.geteuid", return_value=1000)
|
||||
def test_not_root(self, m: MagicMock) -> None:
|
||||
with (
|
||||
patch("sys.stdout", new_callable=StringIO),
|
||||
pytest.raises(SystemExit),
|
||||
):
|
||||
main([])
|
||||
|
||||
@patch(f"{MOD}._run_network_mode")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_with_ip(self, g: MagicMock, mock_net: MagicMock) -> None:
|
||||
main(["1.2.3.4"])
|
||||
mock_net.assert_called_once_with("1.2.3.4")
|
||||
|
||||
@patch(f"{MOD}._run_usb_mode")
|
||||
@patch(f"{MOD}.find_brother_usb", return_value="Brother USB")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_usb_found(
|
||||
self,
|
||||
g: MagicMock,
|
||||
f: MagicMock,
|
||||
mock_usb: MagicMock,
|
||||
) -> None:
|
||||
main([])
|
||||
mock_usb.assert_called_once()
|
||||
|
||||
def test_network_discovered(self) -> None:
|
||||
from python_pkg.brother_printer.data_classes import NetworkResult
|
||||
|
||||
with (
|
||||
patch(f"{MOD}.os.geteuid", return_value=0),
|
||||
patch(f"{MOD}.find_brother_usb", return_value=""),
|
||||
patch(f"{MOD}._discover_network_printer", return_value="192.168.1.100"),
|
||||
patch(f"{MOD}.shutil.which", return_value="/usr/bin/snmpwalk"),
|
||||
patch(f"{MOD}.query_network_snmp") as mock_query,
|
||||
patch(f"{MOD}.display_network_results") as mock_display,
|
||||
patch("sys.stdout", new_callable=StringIO),
|
||||
):
|
||||
mock_query.return_value = NetworkResult(ip="192.168.1.100")
|
||||
main([])
|
||||
mock_display.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._no_printer_found")
|
||||
@patch(f"{MOD}._discover_network_printer", return_value="")
|
||||
@patch(f"{MOD}.find_brother_usb", return_value="")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_nothing_found(
|
||||
self,
|
||||
g: MagicMock,
|
||||
f: MagicMock,
|
||||
d: MagicMock,
|
||||
mock_no: MagicMock,
|
||||
) -> None:
|
||||
main([])
|
||||
mock_no.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._no_printer_found")
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
@patch(f"{MOD}._discover_network_printer", return_value="192.168.1.100")
|
||||
@patch(f"{MOD}.find_brother_usb", return_value="")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_network_discovered_no_snmpwalk(
|
||||
self,
|
||||
g: MagicMock,
|
||||
f: MagicMock,
|
||||
d: MagicMock,
|
||||
w: MagicMock,
|
||||
mock_no: MagicMock,
|
||||
) -> None:
|
||||
main([])
|
||||
mock_no.assert_called_once()
|
||||
|
||||
def test_default_argv(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}.sys.argv", ["prog", "--reset-toner"]),
|
||||
patch(f"{MOD}.reset_consumable") as mock_reset,
|
||||
):
|
||||
main()
|
||||
mock_reset.assert_called_once_with("toner")
|
||||
|
||||
@patch(f"{MOD}.os.geteuid", return_value=1000)
|
||||
def test_not_root_with_args(self, g: MagicMock) -> None:
|
||||
with (
|
||||
patch("sys.stdout", new_callable=StringIO),
|
||||
pytest.raises(SystemExit),
|
||||
):
|
||||
main(["1.2.3.4"])
|
||||
|
||||
|
||||
class TestResetConsumableFromPrinter:
|
||||
"""Resetting a baseline must use the printer's own counter, or refuse.
|
||||
|
||||
Baselines live on the printer's lifetime-counter scale. Recording one from
|
||||
any other source skews every later estimate, so a printer that cannot be
|
||||
read is a hard error rather than a silent fallback.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_uses_printer_page_count(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="2017")
|
||||
_reset_consumable_from_printer("toner")
|
||||
mock_reset.assert_called_once_with("toner", 2017)
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_refuses_without_page_count(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="")
|
||||
with pytest.raises(SystemExit):
|
||||
_reset_consumable_from_printer("toner")
|
||||
mock_reset.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_reports_underlying_error(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="", error="device busy")
|
||||
with pytest.raises(SystemExit):
|
||||
_reset_consumable_from_printer("drum")
|
||||
printed = " ".join(str(c) for c in mock_out.call_args_list)
|
||||
assert "device busy" in printed
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_non_numeric_page_count_refused(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="???")
|
||||
with pytest.raises(SystemExit):
|
||||
_reset_consumable_from_printer("toner")
|
||||
mock_reset.assert_not_called()
|
||||
|
||||
@ -1,183 +0,0 @@
|
||||
"""Tests for brother_printer.check_brother_printer - the CLI entry point.
|
||||
|
||||
Split from test_check_brother_printer.py under the 250-line cap. These cover
|
||||
argument handling, mode selection and the consumable reset flags.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.brother_printer.check_brother_printer import (
|
||||
_reset_consumable_from_printer,
|
||||
main,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import USBResult
|
||||
|
||||
MOD = "python_pkg.brother_printer.check_brother_printer"
|
||||
|
||||
|
||||
class TestMain:
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
def test_reset_toner(self, mock_reset: MagicMock) -> None:
|
||||
main(["--reset-toner"])
|
||||
mock_reset.assert_called_once_with("toner")
|
||||
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
def test_reset_drum(self, mock_reset: MagicMock) -> None:
|
||||
main(["--reset-drum"])
|
||||
mock_reset.assert_called_once_with("drum")
|
||||
|
||||
@patch(f"{MOD}.os.geteuid", return_value=1000)
|
||||
def test_not_root(self, m: MagicMock) -> None:
|
||||
with (
|
||||
patch("sys.stdout", new_callable=StringIO),
|
||||
pytest.raises(SystemExit),
|
||||
):
|
||||
main([])
|
||||
|
||||
@patch(f"{MOD}._run_network_mode")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_with_ip(self, g: MagicMock, mock_net: MagicMock) -> None:
|
||||
main(["1.2.3.4"])
|
||||
mock_net.assert_called_once_with("1.2.3.4")
|
||||
|
||||
@patch(f"{MOD}._run_usb_mode")
|
||||
@patch(f"{MOD}.find_brother_usb", return_value="Brother USB")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_usb_found(
|
||||
self,
|
||||
g: MagicMock,
|
||||
f: MagicMock,
|
||||
mock_usb: MagicMock,
|
||||
) -> None:
|
||||
main([])
|
||||
mock_usb.assert_called_once()
|
||||
|
||||
def test_network_discovered(self) -> None:
|
||||
from python_pkg.brother_printer.data_classes import NetworkResult
|
||||
|
||||
with (
|
||||
patch(f"{MOD}.os.geteuid", return_value=0),
|
||||
patch(f"{MOD}.find_brother_usb", return_value=""),
|
||||
patch(f"{MOD}._discover_network_printer", return_value="192.168.1.100"),
|
||||
patch(f"{MOD}.shutil.which", return_value="/usr/bin/snmpwalk"),
|
||||
patch(f"{MOD}.query_network_snmp") as mock_query,
|
||||
patch(f"{MOD}.display_network_results") as mock_display,
|
||||
patch("sys.stdout", new_callable=StringIO),
|
||||
):
|
||||
mock_query.return_value = NetworkResult(ip="192.168.1.100")
|
||||
main([])
|
||||
mock_display.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._no_printer_found")
|
||||
@patch(f"{MOD}._discover_network_printer", return_value="")
|
||||
@patch(f"{MOD}.find_brother_usb", return_value="")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_nothing_found(
|
||||
self,
|
||||
g: MagicMock,
|
||||
f: MagicMock,
|
||||
d: MagicMock,
|
||||
mock_no: MagicMock,
|
||||
) -> None:
|
||||
main([])
|
||||
mock_no.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._no_printer_found")
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
@patch(f"{MOD}._discover_network_printer", return_value="192.168.1.100")
|
||||
@patch(f"{MOD}.find_brother_usb", return_value="")
|
||||
@patch(f"{MOD}.os.geteuid", return_value=0)
|
||||
def test_network_discovered_no_snmpwalk(
|
||||
self,
|
||||
g: MagicMock,
|
||||
f: MagicMock,
|
||||
d: MagicMock,
|
||||
w: MagicMock,
|
||||
mock_no: MagicMock,
|
||||
) -> None:
|
||||
main([])
|
||||
mock_no.assert_called_once()
|
||||
|
||||
def test_default_argv(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}.sys.argv", ["prog", "--reset-toner"]),
|
||||
patch(f"{MOD}.reset_consumable") as mock_reset,
|
||||
):
|
||||
main()
|
||||
mock_reset.assert_called_once_with("toner")
|
||||
|
||||
@patch(f"{MOD}.os.geteuid", return_value=1000)
|
||||
def test_not_root_with_args(self, g: MagicMock) -> None:
|
||||
with (
|
||||
patch("sys.stdout", new_callable=StringIO),
|
||||
pytest.raises(SystemExit),
|
||||
):
|
||||
main(["1.2.3.4"])
|
||||
|
||||
|
||||
class TestResetConsumableFromPrinter:
|
||||
"""Resetting a baseline must use the printer's own counter, or refuse.
|
||||
|
||||
Baselines live on the printer's lifetime-counter scale. Recording one from
|
||||
any other source skews every later estimate, so a printer that cannot be
|
||||
read is a hard error rather than a silent fallback.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_uses_printer_page_count(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="2017")
|
||||
_reset_consumable_from_printer("toner")
|
||||
mock_reset.assert_called_once_with("toner", 2017)
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_refuses_without_page_count(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="")
|
||||
with pytest.raises(SystemExit):
|
||||
_reset_consumable_from_printer("toner")
|
||||
mock_reset.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_reports_underlying_error(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="", error="device busy")
|
||||
with pytest.raises(SystemExit):
|
||||
_reset_consumable_from_printer("drum")
|
||||
printed = " ".join(str(c) for c in mock_out.call_args_list)
|
||||
assert "device busy" in printed
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}.reset_consumable")
|
||||
@patch(f"{MOD}.query_usb_pjl")
|
||||
def test_non_numeric_page_count_refused(
|
||||
self,
|
||||
mock_query: MagicMock,
|
||||
mock_reset: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_query.return_value = USBResult(page_count="???")
|
||||
with pytest.raises(SystemExit):
|
||||
_reset_consumable_from_printer("toner")
|
||||
mock_reset.assert_not_called()
|
||||
@ -1,167 +0,0 @@
|
||||
"""Tests for brother_printer.consumables - the toner and drum life estimate.
|
||||
|
||||
Split from test_consumables.py under the 250-line cap. These cover which
|
||||
counter the estimate is based on and how replacement resets rebase it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.consumables import (
|
||||
STATE_SCHEMA_CUPS_SCALE,
|
||||
STATE_SCHEMA_PRINTER_SCALE,
|
||||
estimate_consumable_life,
|
||||
reset_consumable,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.consumables"
|
||||
|
||||
|
||||
class TestEstimateConsumableLife:
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=0)
|
||||
def test_no_pages(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
result = estimate_consumable_life()
|
||||
assert result.total_pages == 0
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=500)
|
||||
def test_mid_life(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.total_pages == 500
|
||||
assert result.toner_pct_remaining == 50
|
||||
assert result.toner_exhausted is False
|
||||
assert result.toner_low is False
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1000)
|
||||
def test_toner_exhausted(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.toner_exhausted is True
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=800)
|
||||
def test_toner_low(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.toner_low is True
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=9000)
|
||||
def test_drum_near_end(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 8500,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.drum_near_end is True
|
||||
|
||||
|
||||
class TestEstimateConsumableLifeCounterSource:
|
||||
"""Which counter the estimate came from, and whether it says so."""
|
||||
|
||||
@patch(f"{MOD}._migrate_state_to_printer_scale")
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_printer_counter_is_authoritative(
|
||||
self,
|
||||
mock_cups: MagicMock,
|
||||
mock_load: MagicMock,
|
||||
mock_migrate: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 1767,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
mock_migrate.side_effect = lambda state, total: state
|
||||
estimate = estimate_consumable_life(2017)
|
||||
assert estimate.total_pages == 2017
|
||||
assert estimate.approximate is False
|
||||
assert estimate.toner_pages == 250
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_falls_back_to_cups_log_and_flags_it(
|
||||
self,
|
||||
mock_cups: MagicMock,
|
||||
mock_load: MagicMock,
|
||||
) -> None:
|
||||
"""Without the printer's counter, say the number is approximate."""
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
estimate = estimate_consumable_life(0)
|
||||
assert estimate.total_pages == 1658
|
||||
assert estimate.approximate is True
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=0)
|
||||
def test_no_counter_at_all(self, mock_cups: MagicMock) -> None:
|
||||
assert estimate_consumable_life(0).total_pages == 0
|
||||
|
||||
|
||||
class TestResetConsumableScale:
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_printer_total_marks_state_migrated(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
"""A baseline written from the printer is already on the new scale."""
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
reset_consumable("toner", 2017)
|
||||
saved = mock_save.call_args[0][0]
|
||||
assert saved["toner_replaced_at"] == 2017
|
||||
assert saved["schema"] == STATE_SCHEMA_PRINTER_SCALE
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_without_printer_total_uses_cups_log(
|
||||
self,
|
||||
mock_cups: MagicMock,
|
||||
mock_load: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
reset_consumable("drum")
|
||||
saved = mock_save.call_args[0][0]
|
||||
assert saved["drum_replaced_at"] == 1658
|
||||
assert saved["schema"] == STATE_SCHEMA_CUPS_SCALE
|
||||
@ -1,4 +1,4 @@
|
||||
"""Tests for brother_printer.consumables - the state file and page log."""
|
||||
"""Tests for brother_printer.consumables - state, estimates, resets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -7,9 +7,11 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.consumables import (
|
||||
STATE_SCHEMA_CUPS_SCALE,
|
||||
STATE_SCHEMA_PRINTER_SCALE,
|
||||
_get_cups_total_pages,
|
||||
_load_consumable_state,
|
||||
_save_consumable_state,
|
||||
estimate_consumable_life,
|
||||
reset_consumable,
|
||||
)
|
||||
|
||||
@ -119,3 +121,152 @@ class TestResetConsumable:
|
||||
reset_consumable("toner")
|
||||
saved_state = mock_save.call_args[0][0]
|
||||
assert saved_state["toner_replaced_at"] == 500
|
||||
|
||||
|
||||
class TestEstimateConsumableLife:
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=0)
|
||||
def test_no_pages(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
result = estimate_consumable_life()
|
||||
assert result.total_pages == 0
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=500)
|
||||
def test_mid_life(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.total_pages == 500
|
||||
assert result.toner_pct_remaining == 50
|
||||
assert result.toner_exhausted is False
|
||||
assert result.toner_low is False
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1000)
|
||||
def test_toner_exhausted(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.toner_exhausted is True
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=800)
|
||||
def test_toner_low(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.toner_low is True
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=9000)
|
||||
def test_drum_near_end(self, p: MagicMock, mock_load: MagicMock) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 8500,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
result = estimate_consumable_life()
|
||||
assert result.drum_near_end is True
|
||||
|
||||
|
||||
class TestEstimateConsumableLifeCounterSource:
|
||||
"""Which counter the estimate came from, and whether it says so."""
|
||||
|
||||
@patch(f"{MOD}._migrate_state_to_printer_scale")
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_printer_counter_is_authoritative(
|
||||
self,
|
||||
mock_cups: MagicMock,
|
||||
mock_load: MagicMock,
|
||||
mock_migrate: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 1767,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
mock_migrate.side_effect = lambda state, total: state
|
||||
estimate = estimate_consumable_life(2017)
|
||||
assert estimate.total_pages == 2017
|
||||
assert estimate.approximate is False
|
||||
assert estimate.toner_pages == 250
|
||||
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_falls_back_to_cups_log_and_flags_it(
|
||||
self,
|
||||
mock_cups: MagicMock,
|
||||
mock_load: MagicMock,
|
||||
) -> None:
|
||||
"""Without the printer's counter, say the number is approximate."""
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"last_printer_count": 0,
|
||||
"last_cups_total": 0,
|
||||
}
|
||||
estimate = estimate_consumable_life(0)
|
||||
assert estimate.total_pages == 1658
|
||||
assert estimate.approximate is True
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=0)
|
||||
def test_no_counter_at_all(self, mock_cups: MagicMock) -> None:
|
||||
assert estimate_consumable_life(0).total_pages == 0
|
||||
|
||||
|
||||
class TestResetConsumableScale:
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_printer_total_marks_state_migrated(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
"""A baseline written from the printer is already on the new scale."""
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
reset_consumable("toner", 2017)
|
||||
saved = mock_save.call_args[0][0]
|
||||
assert saved["toner_replaced_at"] == 2017
|
||||
assert saved["schema"] == STATE_SCHEMA_PRINTER_SCALE
|
||||
|
||||
@patch(f"{MOD}._out")
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_without_printer_total_uses_cups_log(
|
||||
self,
|
||||
mock_cups: MagicMock,
|
||||
mock_load: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
mock_out: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
reset_consumable("drum")
|
||||
saved = mock_save.call_args[0][0]
|
||||
assert saved["drum_replaced_at"] == 1658
|
||||
assert saved["schema"] == STATE_SCHEMA_CUPS_SCALE
|
||||
|
||||
273
python_pkg/brother_printer/tests/test_consumables_part2.py
Normal file
273
python_pkg/brother_printer/tests/test_consumables_part2.py
Normal file
@ -0,0 +1,273 @@
|
||||
"""Tests for brother_printer.consumables - counter scales and dropped pages.
|
||||
|
||||
The printer's counter and the CUPS page log measure different things. These
|
||||
tests pin the rebasing between them and the dropped-page detection that the
|
||||
gap makes possible.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._page_delivery import (
|
||||
_snapshot_counters,
|
||||
check_page_delivery,
|
||||
)
|
||||
from python_pkg.brother_printer.consumables import (
|
||||
STATE_SCHEMA_CUPS_SCALE,
|
||||
STATE_SCHEMA_PRINTER_SCALE,
|
||||
_cups_total_on_printer_scale,
|
||||
_migrate_state_to_printer_scale,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.consumables"
|
||||
# check_page_delivery and _snapshot_counters moved to _page_delivery, so the
|
||||
# state-file helpers they call resolve through that module's globals instead.
|
||||
MOD_PD = "python_pkg.brother_printer._page_delivery"
|
||||
|
||||
|
||||
class TestMigrateStateToPrinterScale:
|
||||
"""Rebasing replacement baselines from the CUPS page log onto the printer.
|
||||
|
||||
The baselines are recorded against whatever counter was in use when they
|
||||
were written. Switching counters without rebasing them silently changes
|
||||
every reported percentage, so this is the migration that keeps the numbers
|
||||
meaning the same thing before and after.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_shifts_baseline_by_offset(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
state = {
|
||||
"toner_replaced_at": 1408,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
# Offset is 2017 - 1658 = 359.
|
||||
assert result["toner_replaced_at"] == 1767
|
||||
assert result["schema"] == STATE_SCHEMA_PRINTER_SCALE
|
||||
mock_save.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_zero_baseline_left_alone(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
"""Zero means 'never replaced', not 'replaced at page zero'.
|
||||
|
||||
On the printer's scale zero already means "as old as the printer",
|
||||
which is the truthful reading; shifting it would re-hide the pages the
|
||||
CUPS log never saw.
|
||||
"""
|
||||
state = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
assert result["drum_replaced_at"] == 0
|
||||
assert result["toner_replaced_at"] == 0
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_runs_only_once(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
"""A second run must not shift the baselines again."""
|
||||
state = {
|
||||
"toner_replaced_at": 1767,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_PRINTER_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
assert result["toner_replaced_at"] == 1767
|
||||
mock_save.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=2100)
|
||||
def test_negative_offset_leaves_baselines(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
"""If the CUPS log somehow exceeds the printer, do not corrupt state."""
|
||||
state = {
|
||||
"toner_replaced_at": 1408,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
assert result["toner_replaced_at"] == 1408
|
||||
assert result["schema"] == STATE_SCHEMA_PRINTER_SCALE
|
||||
|
||||
|
||||
class TestCheckPageDelivery:
|
||||
"""Spotting pages the printer silently dropped.
|
||||
|
||||
CUPS calls a job successful once the data leaves the machine, so this
|
||||
comparison against the printer's own counter is the only signal that a page
|
||||
never actually came out.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_detects_dropped_pages(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
"""Replay of the real failure: CUPS sent 63, printer printed none."""
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2087,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.cups_pages == 63
|
||||
assert check.printer_pages == 0
|
||||
assert check.dropped == 63
|
||||
assert check.suspected is True
|
||||
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_healthy_job_does_not_warn(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2024,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.dropped == 0
|
||||
assert check.suspected is False
|
||||
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1780)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_small_gap_is_not_a_warning(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
"""A page or two of drift is timing, not a fault."""
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2087,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.dropped == 2
|
||||
assert check.suspected is False
|
||||
|
||||
def test_skipped_while_printing(self) -> None:
|
||||
"""Mid-job the counters legitimately disagree, so never compare."""
|
||||
assert check_page_delivery(2087, queue_idle=False).suspected is False
|
||||
|
||||
def test_skipped_without_printer_count(self) -> None:
|
||||
assert check_page_delivery(0, queue_idle=True).suspected is False
|
||||
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_first_run_only_establishes_baseline(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {"last_printer_count": 0, "last_cups_total": 0}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.suspected is False
|
||||
mock_snap.assert_called_once()
|
||||
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=10)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_log_rotation_draws_no_conclusion(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
"""A rotated page log makes the delta negative; do not cry wolf."""
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2087,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.suspected is False
|
||||
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_printer_counter_reset_draws_no_conclusion(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 5000,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.suspected is False
|
||||
|
||||
|
||||
class TestSnapshotCounters:
|
||||
@patch(f"{MOD_PD}._save_consumable_state")
|
||||
def test_writes_new_snapshot(self, mock_save: MagicMock) -> None:
|
||||
state = {"last_printer_count": 2000, "last_cups_total": 1700}
|
||||
_snapshot_counters(state, 2087, 1778)
|
||||
saved = mock_save.call_args[0][0]
|
||||
assert saved["last_printer_count"] == 2087
|
||||
assert saved["last_cups_total"] == 1778
|
||||
|
||||
@patch(f"{MOD_PD}._save_consumable_state")
|
||||
def test_unchanged_counters_skip_the_write(self, mock_save: MagicMock) -> None:
|
||||
"""Do not rewrite the file on every run when nothing moved."""
|
||||
state = {"last_printer_count": 2087, "last_cups_total": 1778}
|
||||
_snapshot_counters(state, 2087, 1778)
|
||||
mock_save.assert_not_called()
|
||||
|
||||
|
||||
class TestCupsTotalOnPrinterScale:
|
||||
"""The CUPS figure must be shifted onto the scale the baselines use.
|
||||
|
||||
Without the shift the raw CUPS total sits below a printer-scale baseline,
|
||||
the subtraction clamps at zero, and a part-used cartridge reads 100%.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1778)
|
||||
def test_applies_offset(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 2087, "last_cups_total": 1778}
|
||||
assert _cups_total_on_printer_scale(state) == 2087
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1778)
|
||||
def test_no_snapshot_returns_raw(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 0, "last_cups_total": 0}
|
||||
assert _cups_total_on_printer_scale(state) == 1778
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1778)
|
||||
def test_negative_offset_returns_raw(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 1700, "last_cups_total": 1778}
|
||||
assert _cups_total_on_printer_scale(state) == 1778
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=0)
|
||||
def test_no_cups_pages(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 2087, "last_cups_total": 1778}
|
||||
assert _cups_total_on_printer_scale(state) == 0
|
||||
@ -1,131 +0,0 @@
|
||||
"""Tests for brother_printer.consumables - rebasing the counter scales.
|
||||
|
||||
The printer's counter and the CUPS page log measure different things. These
|
||||
tests pin the rebasing between them; the dropped-page detection that the gap
|
||||
makes possible is covered in test_page_delivery.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.consumables import (
|
||||
STATE_SCHEMA_CUPS_SCALE,
|
||||
STATE_SCHEMA_PRINTER_SCALE,
|
||||
_cups_total_on_printer_scale,
|
||||
_migrate_state_to_printer_scale,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.consumables"
|
||||
|
||||
|
||||
class TestMigrateStateToPrinterScale:
|
||||
"""Rebasing replacement baselines from the CUPS page log onto the printer.
|
||||
|
||||
The baselines are recorded against whatever counter was in use when they
|
||||
were written. Switching counters without rebasing them silently changes
|
||||
every reported percentage, so this is the migration that keeps the numbers
|
||||
meaning the same thing before and after.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_shifts_baseline_by_offset(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
state = {
|
||||
"toner_replaced_at": 1408,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
# Offset is 2017 - 1658 = 359.
|
||||
assert result["toner_replaced_at"] == 1767
|
||||
assert result["schema"] == STATE_SCHEMA_PRINTER_SCALE
|
||||
mock_save.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_zero_baseline_left_alone(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
"""Zero means 'never replaced', not 'replaced at page zero'.
|
||||
|
||||
On the printer's scale zero already means "as old as the printer",
|
||||
which is the truthful reading; shifting it would re-hide the pages the
|
||||
CUPS log never saw.
|
||||
"""
|
||||
state = {
|
||||
"toner_replaced_at": 0,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
assert result["drum_replaced_at"] == 0
|
||||
assert result["toner_replaced_at"] == 0
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1658)
|
||||
def test_runs_only_once(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
"""A second run must not shift the baselines again."""
|
||||
state = {
|
||||
"toner_replaced_at": 1767,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_PRINTER_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
assert result["toner_replaced_at"] == 1767
|
||||
mock_save.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=2100)
|
||||
def test_negative_offset_leaves_baselines(
|
||||
self,
|
||||
mock_total: MagicMock,
|
||||
mock_save: MagicMock,
|
||||
) -> None:
|
||||
"""If the CUPS log somehow exceeds the printer, do not corrupt state."""
|
||||
state = {
|
||||
"toner_replaced_at": 1408,
|
||||
"drum_replaced_at": 0,
|
||||
"schema": STATE_SCHEMA_CUPS_SCALE,
|
||||
}
|
||||
result = _migrate_state_to_printer_scale(state, 2017)
|
||||
assert result["toner_replaced_at"] == 1408
|
||||
assert result["schema"] == STATE_SCHEMA_PRINTER_SCALE
|
||||
|
||||
|
||||
class TestCupsTotalOnPrinterScale:
|
||||
"""The CUPS figure must be shifted onto the scale the baselines use.
|
||||
|
||||
Without the shift the raw CUPS total sits below a printer-scale baseline,
|
||||
the subtraction clamps at zero, and a part-used cartridge reads 100%.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1778)
|
||||
def test_applies_offset(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 2087, "last_cups_total": 1778}
|
||||
assert _cups_total_on_printer_scale(state) == 2087
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1778)
|
||||
def test_no_snapshot_returns_raw(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 0, "last_cups_total": 0}
|
||||
assert _cups_total_on_printer_scale(state) == 1778
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1778)
|
||||
def test_negative_offset_returns_raw(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 1700, "last_cups_total": 1778}
|
||||
assert _cups_total_on_printer_scale(state) == 1778
|
||||
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=0)
|
||||
def test_no_cups_pages(self, mock_cups: MagicMock) -> None:
|
||||
state = {"last_printer_count": 2087, "last_cups_total": 1778}
|
||||
assert _cups_total_on_printer_scale(state) == 0
|
||||
@ -1,115 +0,0 @@
|
||||
"""Tests for brother_printer._cups_fallback - economode and state mapping."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._cups_fallback import (
|
||||
_get_cups_economode,
|
||||
_map_cups_to_status_code,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
_CUPS_REASONS_TO_STATUS,
|
||||
get_status_info,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer._cups_fallback"
|
||||
|
||||
|
||||
# ── _get_cups_economode ──────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestGetCupsEconomode:
|
||||
"""Tests for _get_cups_economode."""
|
||||
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_lpoptions(self, m: MagicMock) -> None:
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_economode_on(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="BREconomode/Toner Save Mode: *True False\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == "ON"
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_economode_off(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="BREconomode/Toner Save Mode: True *False\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == "OFF"
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_no_economode_line(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="Resolution/Output Resolution: 600dpi *1200dpi\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_economode_no_star_match(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="BREconomode/Toner Save Mode: True False\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_timeout(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.TimeoutExpired("lpoptions", 5)
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_oserror(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = OSError("fail")
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
|
||||
# ── _map_cups_to_status_code ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestMapCupsToStatusCode:
|
||||
"""Tests for _map_cups_to_status_code.
|
||||
|
||||
Every code here must exist in BROTHER_STATUS_CODES; mapping CUPS onto a
|
||||
code the table does not know silently degrades to "unknown status".
|
||||
"""
|
||||
|
||||
def test_reason_match(self) -> None:
|
||||
assert _map_cups_to_status_code("idle", "toner-low-report") == "40038"
|
||||
|
||||
def test_state_match(self) -> None:
|
||||
assert _map_cups_to_status_code("idle", "none") == "10001"
|
||||
|
||||
def test_processing_state(self) -> None:
|
||||
assert _map_cups_to_status_code("processing", "none") == "10023"
|
||||
|
||||
def test_stopped_state(self) -> None:
|
||||
assert _map_cups_to_status_code("stopped", "none") == "40079"
|
||||
|
||||
def test_unknown_state(self) -> None:
|
||||
assert _map_cups_to_status_code("mystery", "none") == "10001"
|
||||
|
||||
def test_state_with_parenthetical(self) -> None:
|
||||
assert _map_cups_to_status_code("idle (on fire)", "none") == "10001"
|
||||
|
||||
def test_every_mapped_code_is_resolvable(self) -> None:
|
||||
"""Guard the class of bug where a mapping points at a deleted code."""
|
||||
for state in ("idle", "processing", "stopped"):
|
||||
code = _map_cups_to_status_code(state, "none")
|
||||
_, text, _ = get_status_info(code)
|
||||
assert "Unknown" not in text
|
||||
for reason in _CUPS_REASONS_TO_STATUS:
|
||||
code = _map_cups_to_status_code("idle", reason)
|
||||
_, text, _ = get_status_info(code)
|
||||
assert "Unknown" not in text
|
||||
|
||||
|
||||
# ── _cups_reasons_to_error ───────────────────────────────────────────
|
||||
@ -1,102 +0,0 @@
|
||||
"""Tests for brother_printer._cups_fallback - the CUPS fallback query."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._cups_fallback import query_usb_via_cups
|
||||
from python_pkg.brother_printer.data_classes import USBPortStatus
|
||||
|
||||
MOD = "python_pkg.brother_printer._cups_fallback"
|
||||
|
||||
|
||||
# ── query_usb_via_cups ───────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestQueryUsbViaCups:
|
||||
"""Tests for query_usb_via_cups."""
|
||||
|
||||
@patch(f"{MOD}.find_cups_printer_name", return_value="")
|
||||
@patch(f"{MOD}._ensure_cups_running", return_value=True)
|
||||
def test_no_printer(self, e: MagicMock, f: MagicMock) -> None:
|
||||
result = query_usb_via_cups()
|
||||
assert result.error != ""
|
||||
|
||||
def test_no_port_status_idle(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}._ensure_cups_running", return_value=True),
|
||||
patch(f"{MOD}.find_cups_printer_name", return_value="Brother"),
|
||||
patch(f"{MOD}._get_pyusb_device_info", return_value={}),
|
||||
patch(
|
||||
f"{MOD}.printer_info_from_cups",
|
||||
return_value={"product": "HL-1110", "serial": "ABC"},
|
||||
),
|
||||
patch(
|
||||
f"{MOD}._get_cups_ipp_status",
|
||||
return_value={
|
||||
"printer-state": "idle",
|
||||
"printer-state-reasons": "none",
|
||||
"printer-state-message": "Ready",
|
||||
},
|
||||
),
|
||||
patch(f"{MOD}._get_cups_economode", return_value="ON"),
|
||||
patch(f"{MOD}._query_usb_port_status_raw", return_value=None),
|
||||
):
|
||||
result = query_usb_via_cups()
|
||||
assert result.online == "TRUE"
|
||||
assert result.product == "HL-1110"
|
||||
assert result.economode == "ON"
|
||||
|
||||
def test_no_port_status_stopped(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}._ensure_cups_running", return_value=True),
|
||||
patch(f"{MOD}.find_cups_printer_name", return_value="Brother"),
|
||||
patch(f"{MOD}._get_pyusb_device_info", return_value={}),
|
||||
patch(
|
||||
f"{MOD}.printer_info_from_cups",
|
||||
return_value={"product": "", "serial": ""},
|
||||
),
|
||||
patch(
|
||||
f"{MOD}._get_cups_ipp_status",
|
||||
return_value={
|
||||
"printer-state": "stopped",
|
||||
"printer-state-reasons": "none",
|
||||
},
|
||||
),
|
||||
patch(f"{MOD}._get_cups_economode", return_value=""),
|
||||
patch(f"{MOD}._query_usb_port_status_raw", return_value=None),
|
||||
):
|
||||
result = query_usb_via_cups()
|
||||
assert result.online == "FALSE"
|
||||
assert result.product == "Brother Laser Printer"
|
||||
|
||||
def test_port_status_hw_error(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}._ensure_cups_running", return_value=True),
|
||||
patch(f"{MOD}.find_cups_printer_name", return_value="Brother"),
|
||||
patch(f"{MOD}._get_pyusb_device_info", return_value={}),
|
||||
patch(
|
||||
f"{MOD}.printer_info_from_cups",
|
||||
return_value={"product": "", "serial": ""},
|
||||
),
|
||||
patch(
|
||||
f"{MOD}._get_cups_ipp_status",
|
||||
return_value={
|
||||
"printer-state": "stopped",
|
||||
"printer-state-reasons": "none",
|
||||
},
|
||||
),
|
||||
patch(f"{MOD}._get_cups_economode", return_value=""),
|
||||
patch(
|
||||
f"{MOD}._query_usb_port_status_raw",
|
||||
return_value=USBPortStatus(
|
||||
error=True,
|
||||
paper_empty=True,
|
||||
online=False,
|
||||
raw_byte=0x20,
|
||||
),
|
||||
),
|
||||
):
|
||||
result = query_usb_via_cups()
|
||||
assert result.status_code == "41000"
|
||||
assert result.online == "FALSE"
|
||||
@ -2,10 +2,18 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_queue import (
|
||||
_check_cups_backend_errors,
|
||||
_cups_cancel_all_jobs,
|
||||
_cups_cancel_job,
|
||||
_cups_enable_printer,
|
||||
_cups_restart_service,
|
||||
_find_backend_error_in_log,
|
||||
_is_cups_printer_healthy,
|
||||
_parse_lpstat_jobs,
|
||||
_parse_lpstat_printer_line,
|
||||
get_cups_queue_status,
|
||||
@ -165,3 +173,286 @@ class TestGetCupsQueueStatus:
|
||||
]
|
||||
result = get_cups_queue_status()
|
||||
assert result.enabled is True # default unchanged
|
||||
|
||||
|
||||
class TestCupsEnablePrinter:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_cupsenable(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_enable_printer("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cupsenable")
|
||||
def test_success(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock()
|
||||
assert _cups_enable_printer("B") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cupsenable")
|
||||
def test_timeout(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.TimeoutExpired("cupsenable", 5)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_enable_printer("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cupsenable")
|
||||
def test_oserror(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = OSError("fail")
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_enable_printer("B") is False
|
||||
|
||||
|
||||
class TestCupsCancelAllJobs:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_cancel(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_cancel_all_jobs("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_success(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock()
|
||||
assert _cups_cancel_all_jobs("B") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_error(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.CalledProcessError(1, "cancel")
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_cancel_all_jobs("B") is False
|
||||
|
||||
|
||||
class TestCupsCancelJob:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_cancel(self, m: MagicMock) -> None:
|
||||
assert _cups_cancel_job("job-1") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_success(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock()
|
||||
assert _cups_cancel_job("job-1") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_error(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.CalledProcessError(1, "cancel")
|
||||
assert _cups_cancel_job("job-1") is False
|
||||
|
||||
|
||||
class TestCupsRestartService:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_systemctl(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}.time.time")
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_success(
|
||||
self,
|
||||
w: MagicMock,
|
||||
mock_popen: MagicMock,
|
||||
mock_time: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
proc = MagicMock()
|
||||
proc.poll.side_effect = [None, 0]
|
||||
proc.returncode = 0
|
||||
mock_popen.return_value = proc
|
||||
mock_time.side_effect = [0.0, 1.0, 2.0]
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is True
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}.time.time")
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_timeout(
|
||||
self,
|
||||
w: MagicMock,
|
||||
mock_popen: MagicMock,
|
||||
mock_time: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
proc = MagicMock()
|
||||
proc.poll.return_value = None
|
||||
mock_popen.return_value = proc
|
||||
mock_time.side_effect = [0.0, 31.0]
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
proc.kill.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}.time.time")
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_nonzero_exit(
|
||||
self,
|
||||
w: MagicMock,
|
||||
mock_popen: MagicMock,
|
||||
mock_time: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
proc = MagicMock()
|
||||
proc.poll.side_effect = [None, 1]
|
||||
proc.returncode = 1
|
||||
mock_popen.return_value = proc
|
||||
mock_time.side_effect = [0.0, 1.0, 2.0]
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_oserror(self, w: MagicMock, mock_popen: MagicMock) -> None:
|
||||
mock_popen.side_effect = OSError("fail")
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
|
||||
|
||||
class TestIsCupsPrinterHealthy:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_lpstat(self, m: MagicMock) -> None:
|
||||
assert _is_cups_printer_healthy("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpstat")
|
||||
def test_healthy(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="printer BrotherHL1110 is idle. enabled since Mon\n",
|
||||
)
|
||||
assert _is_cups_printer_healthy("BrotherHL1110") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpstat")
|
||||
def test_not_healthy(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="printer BrotherHL1110 disabled\n",
|
||||
)
|
||||
assert _is_cups_printer_healthy("BrotherHL1110") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpstat")
|
||||
def test_timeout(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.TimeoutExpired("lpstat", 5)
|
||||
assert _is_cups_printer_healthy("B") is False
|
||||
|
||||
|
||||
class TestFindBackendErrorInLog:
|
||||
def test_no_errors(self) -> None:
|
||||
lines = ["[2025-01-01] Completed job\n"]
|
||||
err, _, _ = _find_backend_error_in_log(lines)
|
||||
assert err == ""
|
||||
|
||||
def test_backend_error(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-01] Completed job",
|
||||
"[2025-01-02] backend errors for BrotherHL1110",
|
||||
]
|
||||
err, ts, success_ts = _find_backend_error_in_log(lines)
|
||||
assert "backend errors" in err
|
||||
assert ts == "2025-01-02"
|
||||
assert success_ts == "2025-01-01"
|
||||
|
||||
def test_stopped_with_status(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-02] stopped with status 1",
|
||||
]
|
||||
err, ts, _ = _find_backend_error_in_log(lines)
|
||||
assert "stopped with status" in err
|
||||
assert ts == "2025-01-02"
|
||||
|
||||
def test_error_no_timestamp(self) -> None:
|
||||
lines = ["backend errors no timestamp here"]
|
||||
err, ts, _ = _find_backend_error_in_log(lines)
|
||||
assert "backend errors" in err
|
||||
assert ts == ""
|
||||
|
||||
def test_completed_with_total(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-01] page total 10",
|
||||
"[2025-01-02] backend errors",
|
||||
]
|
||||
_, _, success_ts = _find_backend_error_in_log(lines)
|
||||
assert success_ts == "2025-01-01"
|
||||
|
||||
def test_no_success_after_error(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-02] backend errors",
|
||||
]
|
||||
_, _, success_ts = _find_backend_error_in_log(lines)
|
||||
assert success_ts == ""
|
||||
|
||||
def test_completed_no_timestamp(self) -> None:
|
||||
lines = [
|
||||
"Completed job",
|
||||
"[2025-01-02] backend errors",
|
||||
]
|
||||
_, _, success_ts = _find_backend_error_in_log(lines)
|
||||
assert success_ts == ""
|
||||
|
||||
|
||||
class TestCheckCupsBackendErrors:
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=True)
|
||||
def test_healthy_printer(self, m: MagicMock) -> None:
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(f"{MOD}._find_backend_error_in_log", return_value=("", "", ""))
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_no_log_file(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = False
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(
|
||||
f"{MOD}._find_backend_error_in_log", return_value=("error", "2025-01-02", "")
|
||||
)
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_has_errors(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.return_value = "log content"
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is True
|
||||
|
||||
@patch(
|
||||
f"{MOD}._find_backend_error_in_log",
|
||||
return_value=("error", "2025-01-01", "2025-01-02"),
|
||||
)
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_success_after_error(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.return_value = "log content"
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_oserror_reading_log(self, h: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.side_effect = OSError("fail")
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(f"{MOD}._find_backend_error_in_log", return_value=("", "", ""))
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_no_backend_error_in_log(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.return_value = "clean log"
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@ -1,157 +0,0 @@
|
||||
"""Tests for brother_printer.cups_queue - the CUPS fix action primitives.
|
||||
|
||||
Split from test_cups_queue.py under the 250-line cap. These are the four
|
||||
functions that shell out to cupsenable, cancel and systemctl, so every one of
|
||||
them patches shutil.which and subprocess on the module under test.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_queue import (
|
||||
_cups_cancel_all_jobs,
|
||||
_cups_cancel_job,
|
||||
_cups_enable_printer,
|
||||
_cups_restart_service,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_queue"
|
||||
|
||||
|
||||
class TestCupsEnablePrinter:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_cupsenable(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_enable_printer("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cupsenable")
|
||||
def test_success(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock()
|
||||
assert _cups_enable_printer("B") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cupsenable")
|
||||
def test_timeout(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.TimeoutExpired("cupsenable", 5)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_enable_printer("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cupsenable")
|
||||
def test_oserror(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = OSError("fail")
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_enable_printer("B") is False
|
||||
|
||||
|
||||
class TestCupsCancelAllJobs:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_cancel(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_cancel_all_jobs("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_success(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock()
|
||||
assert _cups_cancel_all_jobs("B") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_error(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.CalledProcessError(1, "cancel")
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_cancel_all_jobs("B") is False
|
||||
|
||||
|
||||
class TestCupsCancelJob:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_cancel(self, m: MagicMock) -> None:
|
||||
assert _cups_cancel_job("job-1") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_success(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock()
|
||||
assert _cups_cancel_job("job-1") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/cancel")
|
||||
def test_error(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.CalledProcessError(1, "cancel")
|
||||
assert _cups_cancel_job("job-1") is False
|
||||
|
||||
|
||||
class TestCupsRestartService:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_systemctl(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}.time.time")
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_success(
|
||||
self,
|
||||
w: MagicMock,
|
||||
mock_popen: MagicMock,
|
||||
mock_time: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
proc = MagicMock()
|
||||
proc.poll.side_effect = [None, 0]
|
||||
proc.returncode = 0
|
||||
mock_popen.return_value = proc
|
||||
mock_time.side_effect = [0.0, 1.0, 2.0]
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is True
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}.time.time")
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_timeout(
|
||||
self,
|
||||
w: MagicMock,
|
||||
mock_popen: MagicMock,
|
||||
mock_time: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
proc = MagicMock()
|
||||
proc.poll.return_value = None
|
||||
mock_popen.return_value = proc
|
||||
mock_time.side_effect = [0.0, 31.0]
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
proc.kill.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}.time.time")
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_nonzero_exit(
|
||||
self,
|
||||
w: MagicMock,
|
||||
mock_popen: MagicMock,
|
||||
mock_time: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
proc = MagicMock()
|
||||
proc.poll.side_effect = [None, 1]
|
||||
proc.returncode = 1
|
||||
mock_popen.return_value = proc
|
||||
mock_time.side_effect = [0.0, 1.0, 2.0]
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.Popen")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/systemctl")
|
||||
def test_oserror(self, w: MagicMock, mock_popen: MagicMock) -> None:
|
||||
mock_popen.side_effect = OSError("fail")
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
assert _cups_restart_service() is False
|
||||
@ -1,164 +0,0 @@
|
||||
"""Tests for brother_printer.cups_queue - stale backend error detection.
|
||||
|
||||
Split from test_cups_queue.py under the 250-line cap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_queue import (
|
||||
_check_cups_backend_errors,
|
||||
_find_backend_error_in_log,
|
||||
_is_cups_printer_healthy,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_queue"
|
||||
|
||||
|
||||
class TestIsCupsPrinterHealthy:
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_lpstat(self, m: MagicMock) -> None:
|
||||
assert _is_cups_printer_healthy("B") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpstat")
|
||||
def test_healthy(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="printer BrotherHL1110 is idle. enabled since Mon\n",
|
||||
)
|
||||
assert _is_cups_printer_healthy("BrotherHL1110") is True
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpstat")
|
||||
def test_not_healthy(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="printer BrotherHL1110 disabled\n",
|
||||
)
|
||||
assert _is_cups_printer_healthy("BrotherHL1110") is False
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpstat")
|
||||
def test_timeout(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.TimeoutExpired("lpstat", 5)
|
||||
assert _is_cups_printer_healthy("B") is False
|
||||
|
||||
|
||||
class TestFindBackendErrorInLog:
|
||||
def test_no_errors(self) -> None:
|
||||
lines = ["[2025-01-01] Completed job\n"]
|
||||
err, _, _ = _find_backend_error_in_log(lines)
|
||||
assert err == ""
|
||||
|
||||
def test_backend_error(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-01] Completed job",
|
||||
"[2025-01-02] backend errors for BrotherHL1110",
|
||||
]
|
||||
err, ts, success_ts = _find_backend_error_in_log(lines)
|
||||
assert "backend errors" in err
|
||||
assert ts == "2025-01-02"
|
||||
assert success_ts == "2025-01-01"
|
||||
|
||||
def test_stopped_with_status(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-02] stopped with status 1",
|
||||
]
|
||||
err, ts, _ = _find_backend_error_in_log(lines)
|
||||
assert "stopped with status" in err
|
||||
assert ts == "2025-01-02"
|
||||
|
||||
def test_error_no_timestamp(self) -> None:
|
||||
lines = ["backend errors no timestamp here"]
|
||||
err, ts, _ = _find_backend_error_in_log(lines)
|
||||
assert "backend errors" in err
|
||||
assert ts == ""
|
||||
|
||||
def test_completed_with_total(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-01] page total 10",
|
||||
"[2025-01-02] backend errors",
|
||||
]
|
||||
_, _, success_ts = _find_backend_error_in_log(lines)
|
||||
assert success_ts == "2025-01-01"
|
||||
|
||||
def test_no_success_after_error(self) -> None:
|
||||
lines = [
|
||||
"[2025-01-02] backend errors",
|
||||
]
|
||||
_, _, success_ts = _find_backend_error_in_log(lines)
|
||||
assert success_ts == ""
|
||||
|
||||
def test_completed_no_timestamp(self) -> None:
|
||||
lines = [
|
||||
"Completed job",
|
||||
"[2025-01-02] backend errors",
|
||||
]
|
||||
_, _, success_ts = _find_backend_error_in_log(lines)
|
||||
assert success_ts == ""
|
||||
|
||||
|
||||
class TestCheckCupsBackendErrors:
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=True)
|
||||
def test_healthy_printer(self, m: MagicMock) -> None:
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(f"{MOD}._find_backend_error_in_log", return_value=("", "", ""))
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_no_log_file(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = False
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(
|
||||
f"{MOD}._find_backend_error_in_log", return_value=("error", "2025-01-02", "")
|
||||
)
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_has_errors(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.return_value = "log content"
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is True
|
||||
|
||||
@patch(
|
||||
f"{MOD}._find_backend_error_in_log",
|
||||
return_value=("error", "2025-01-01", "2025-01-02"),
|
||||
)
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_success_after_error(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.return_value = "log content"
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_oserror_reading_log(self, h: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.side_effect = OSError("fail")
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
|
||||
@patch(f"{MOD}._find_backend_error_in_log", return_value=("", "", ""))
|
||||
@patch(f"{MOD}._is_cups_printer_healthy", return_value=False)
|
||||
def test_no_backend_error_in_log(self, h: MagicMock, f: MagicMock) -> None:
|
||||
with patch(f"{MOD}.Path") as mock_path:
|
||||
mock_log = MagicMock()
|
||||
mock_log.exists.return_value = True
|
||||
mock_log.read_text.return_value = "clean log"
|
||||
mock_path.return_value = mock_log
|
||||
has_errors, _ = _check_cups_backend_errors("B")
|
||||
assert has_errors is False
|
||||
@ -1,131 +0,0 @@
|
||||
"""Tests for brother_printer._queue_fix - the interactive fix menu."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._queue_fix import (
|
||||
_dwj_cancel_and_enable,
|
||||
_dwj_cancel_only,
|
||||
_dwj_enable_only,
|
||||
_dwj_restart_and_enable,
|
||||
_dwj_restart_only,
|
||||
_offer_queue_fix,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import CUPSJob, CUPSQueueStatus
|
||||
|
||||
MOD = "python_pkg.brother_printer._queue_fix"
|
||||
|
||||
|
||||
# ── _offer_queue_fix ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestOfferQueueFix:
|
||||
"""Tests for _offer_queue_fix menu routing."""
|
||||
|
||||
@patch(f"{MOD}._handle_disabled_with_jobs")
|
||||
@patch(f"{MOD}._prompt", return_value="1")
|
||||
def test_disabled_with_jobs(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(
|
||||
printer_name="B",
|
||||
enabled=False,
|
||||
jobs=[CUPSJob("j1", "alice", "1024", "Mon")],
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with(queue, "1")
|
||||
|
||||
@patch(f"{MOD}._handle_disabled_no_jobs")
|
||||
@patch(f"{MOD}._prompt", return_value="2")
|
||||
def test_disabled_no_jobs(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(printer_name="B", enabled=False)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with(queue, "2")
|
||||
|
||||
@patch(f"{MOD}._handle_enabled_with_jobs")
|
||||
@patch(f"{MOD}._prompt", return_value="1")
|
||||
def test_enabled_with_jobs(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(
|
||||
printer_name="B",
|
||||
enabled=True,
|
||||
jobs=[CUPSJob("j1", "alice", "1024", "Mon")],
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with(queue, "1")
|
||||
|
||||
@patch(f"{MOD}._handle_backend_errors_only")
|
||||
@patch(f"{MOD}._prompt", return_value="1")
|
||||
def test_backend_errors_only(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(printer_name="B", enabled=True)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with("1")
|
||||
|
||||
|
||||
# ── _dwj_* action functions ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestDwjEnableOnly:
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=True)
|
||||
def test_success(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_enable_only("B")
|
||||
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=False)
|
||||
def test_failure(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_enable_only("B")
|
||||
|
||||
|
||||
class TestDwjCancelAndEnable:
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=True)
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=True)
|
||||
def test_success(self, c: MagicMock, e: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_and_enable("B")
|
||||
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=False)
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=True)
|
||||
def test_enable_fails(self, c: MagicMock, e: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_and_enable("B")
|
||||
|
||||
|
||||
class TestDwjCancelOnly:
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=True)
|
||||
def test_success(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_only("B")
|
||||
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=False)
|
||||
def test_failure(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_only("B")
|
||||
|
||||
|
||||
class TestDwjRestartOnly:
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=True)
|
||||
def test_success(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_only("B")
|
||||
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=False)
|
||||
def test_failure(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_only("B")
|
||||
|
||||
|
||||
class TestDwjRestartAndEnable:
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=True)
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=True)
|
||||
def test_success(self, r: MagicMock, e: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_and_enable("B")
|
||||
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=False)
|
||||
def test_restart_fails(self, r: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_and_enable("B")
|
||||
@ -1,9 +1,4 @@
|
||||
"""Tests for brother_printer._queue_fix - the choice dispatchers.
|
||||
|
||||
Split from test_cups_queue_part2.py under the 250-line cap. Each dispatcher
|
||||
maps a menu choice onto the CUPS action primitives, which are patched on
|
||||
_queue_fix because that is the module whose globals they resolve through.
|
||||
"""
|
||||
"""Tests for brother_printer._queue_fix module - part 2 (interactive fix)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -11,16 +6,138 @@ from io import StringIO
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._queue_fix import (
|
||||
_dwj_cancel_and_enable,
|
||||
_dwj_cancel_only,
|
||||
_dwj_enable_only,
|
||||
_dwj_restart_and_enable,
|
||||
_dwj_restart_only,
|
||||
_handle_backend_errors_only,
|
||||
_handle_disabled_no_jobs,
|
||||
_handle_disabled_with_jobs,
|
||||
_handle_enabled_with_jobs,
|
||||
_offer_queue_fix,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import CUPSJob, CUPSQueueStatus
|
||||
|
||||
MOD = "python_pkg.brother_printer._queue_fix"
|
||||
|
||||
|
||||
# ── _offer_queue_fix ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestOfferQueueFix:
|
||||
"""Tests for _offer_queue_fix menu routing."""
|
||||
|
||||
@patch(f"{MOD}._handle_disabled_with_jobs")
|
||||
@patch(f"{MOD}._prompt", return_value="1")
|
||||
def test_disabled_with_jobs(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(
|
||||
printer_name="B",
|
||||
enabled=False,
|
||||
jobs=[CUPSJob("j1", "alice", "1024", "Mon")],
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with(queue, "1")
|
||||
|
||||
@patch(f"{MOD}._handle_disabled_no_jobs")
|
||||
@patch(f"{MOD}._prompt", return_value="2")
|
||||
def test_disabled_no_jobs(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(printer_name="B", enabled=False)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with(queue, "2")
|
||||
|
||||
@patch(f"{MOD}._handle_enabled_with_jobs")
|
||||
@patch(f"{MOD}._prompt", return_value="1")
|
||||
def test_enabled_with_jobs(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(
|
||||
printer_name="B",
|
||||
enabled=True,
|
||||
jobs=[CUPSJob("j1", "alice", "1024", "Mon")],
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with(queue, "1")
|
||||
|
||||
@patch(f"{MOD}._handle_backend_errors_only")
|
||||
@patch(f"{MOD}._prompt", return_value="1")
|
||||
def test_backend_errors_only(self, p: MagicMock, mock_handler: MagicMock) -> None:
|
||||
queue = CUPSQueueStatus(printer_name="B", enabled=True)
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_offer_queue_fix(queue)
|
||||
mock_handler.assert_called_once_with("1")
|
||||
|
||||
|
||||
# ── _dwj_* action functions ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestDwjEnableOnly:
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=True)
|
||||
def test_success(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_enable_only("B")
|
||||
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=False)
|
||||
def test_failure(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_enable_only("B")
|
||||
|
||||
|
||||
class TestDwjCancelAndEnable:
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=True)
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=True)
|
||||
def test_success(self, c: MagicMock, e: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_and_enable("B")
|
||||
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=False)
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=True)
|
||||
def test_enable_fails(self, c: MagicMock, e: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_and_enable("B")
|
||||
|
||||
|
||||
class TestDwjCancelOnly:
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=True)
|
||||
def test_success(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_only("B")
|
||||
|
||||
@patch(f"{MOD}._cups_cancel_all_jobs", return_value=False)
|
||||
def test_failure(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_cancel_only("B")
|
||||
|
||||
|
||||
class TestDwjRestartOnly:
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=True)
|
||||
def test_success(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_only("B")
|
||||
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=False)
|
||||
def test_failure(self, m: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_only("B")
|
||||
|
||||
|
||||
class TestDwjRestartAndEnable:
|
||||
@patch(f"{MOD}._cups_enable_printer", return_value=True)
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=True)
|
||||
def test_success(self, r: MagicMock, e: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_and_enable("B")
|
||||
|
||||
@patch(f"{MOD}._cups_restart_service", return_value=False)
|
||||
def test_restart_fails(self, r: MagicMock) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO):
|
||||
_dwj_restart_and_enable("B")
|
||||
|
||||
|
||||
# ── _handle_disabled_with_jobs ───────────────────────────────────────
|
||||
|
||||
|
||||
class TestHandleDisabledWithJobs:
|
||||
"""Tests for _handle_disabled_with_jobs dispatch."""
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""Tests for brother_printer._queue_fix - the queue status display."""
|
||||
"""Tests for brother_printer._queue_fix module - part 3 (display status)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -1,16 +1,21 @@
|
||||
"""Tests for brother_printer.cups_service - pyusb info and service control."""
|
||||
"""Tests for brother_printer.cups_service module."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_service import (
|
||||
_cups_is_busy,
|
||||
_ensure_cups_running,
|
||||
_get_pyusb_device_info,
|
||||
_port_status_via_usblp,
|
||||
_query_usb_port_status_raw,
|
||||
is_cups_scheduler_running,
|
||||
start_cups,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import USBPortStatus
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_service"
|
||||
|
||||
@ -170,3 +175,216 @@ class TestEnsureCupsRunning:
|
||||
@patch(f"{MOD}.is_cups_scheduler_running", return_value=False)
|
||||
def test_start_fails(self, is_running: MagicMock, st: MagicMock) -> None:
|
||||
assert _ensure_cups_running() is False
|
||||
|
||||
|
||||
class TestPortStatusViaUsblp:
|
||||
"""The zero-side-effect path: read the status byte from /dev/usb/lp*."""
|
||||
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_no_dev_dir(self, mock_path: MagicMock) -> None:
|
||||
mock_path.return_value.is_dir.return_value = False
|
||||
assert _port_status_via_usblp() is None
|
||||
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_no_devices(self, mock_path: MagicMock) -> None:
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = []
|
||||
assert _port_status_via_usblp() is None
|
||||
|
||||
@patch(f"{MOD}.os.close")
|
||||
@patch(f"{MOD}.fcntl.ioctl")
|
||||
@patch(f"{MOD}.os.open", return_value=7)
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_success(
|
||||
self,
|
||||
mock_path: MagicMock,
|
||||
mock_open: MagicMock,
|
||||
mock_ioctl: MagicMock,
|
||||
mock_close: MagicMock,
|
||||
) -> None:
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = ["/dev/usb/lp0"]
|
||||
|
||||
def fill(fd: int, req: int, buf: bytearray) -> None:
|
||||
buf[0] = 0x18
|
||||
|
||||
mock_ioctl.side_effect = fill
|
||||
result = _port_status_via_usblp()
|
||||
assert result is not None
|
||||
assert result.online is True
|
||||
assert result.error is False
|
||||
assert result.paper_empty is False
|
||||
# Must never block: the printer may be mid-job.
|
||||
assert mock_open.call_args[0][1] & os.O_NONBLOCK
|
||||
mock_close.assert_called_once_with(7)
|
||||
|
||||
@patch(f"{MOD}.os.open", side_effect=OSError("busy"))
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_open_fails(self, mock_path: MagicMock, mock_open: MagicMock) -> None:
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = ["/dev/usb/lp0"]
|
||||
assert _port_status_via_usblp() is None
|
||||
|
||||
|
||||
class TestQueryUsbPortStatusRaw:
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=USBPortStatus(raw_byte=0x18))
|
||||
def test_prefers_usblp(self, m: MagicMock) -> None:
|
||||
"""The free path wins; pyusb is never touched."""
|
||||
result = _query_usb_port_status_raw("idle")
|
||||
assert result is not None
|
||||
assert result.raw_byte == 0x18
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_never_probes_while_printing(self, m: MagicMock) -> None:
|
||||
"""Regression: probing mid-job used to stop CUPS and kill the print."""
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("processing") is None
|
||||
mock_usb.core.find.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_import_error(self, m: MagicMock) -> None:
|
||||
with patch.dict(
|
||||
"sys.modules", {"usb": None, "usb.core": None, "usb.util": None}
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_dev_none(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_usb.core.find.return_value = None
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_success_reattaches_driver(self, m: MagicMock) -> None:
|
||||
"""usblp must get its device back, or every later run hits the fallback."""
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = True
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
result = _query_usb_port_status_raw("idle")
|
||||
assert result is not None
|
||||
assert result.online is True
|
||||
mock_dev.reset.assert_not_called()
|
||||
mock_dev.attach_kernel_driver.assert_called_once_with(0)
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_kernel_driver_not_active(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = False
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
result = _query_usb_port_status_raw("idle")
|
||||
assert result is not None
|
||||
# Nothing was detached, so nothing should be re-attached.
|
||||
mock_dev.attach_kernel_driver.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_kernel_driver_usberror(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
usb_error_cls = type("USBError", (Exception,), {})
|
||||
mock_dev.is_kernel_driver_active.side_effect = usb_error_cls("err")
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = usb_error_cls
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is not None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_oserror_during_transfer(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = False
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
mock_usb.util.claim_interface.side_effect = OSError("usb fail")
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_attach_failure_is_survivable(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = True
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_dev.attach_kernel_driver.side_effect = OSError("cannot reattach")
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is not None
|
||||
|
||||
|
||||
class TestCupsIsBusy:
|
||||
def test_processing(self) -> None:
|
||||
assert _cups_is_busy("processing") is True
|
||||
|
||||
def test_printing_text(self) -> None:
|
||||
assert _cups_is_busy("now printing Brother-98") is True
|
||||
|
||||
def test_idle(self) -> None:
|
||||
assert _cups_is_busy("idle") is False
|
||||
|
||||
def test_empty(self) -> None:
|
||||
assert _cups_is_busy("") is False
|
||||
|
||||
|
||||
class TestPortStatusViaUsblpIoctlFailure:
|
||||
@patch(f"{MOD}.os.close")
|
||||
@patch(f"{MOD}.fcntl.ioctl", side_effect=OSError("not supported"))
|
||||
@patch(f"{MOD}.os.open", return_value=7)
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_ioctl_failure_still_closes_fd(
|
||||
self,
|
||||
mock_path: MagicMock,
|
||||
mock_open: MagicMock,
|
||||
mock_ioctl: MagicMock,
|
||||
mock_close: MagicMock,
|
||||
) -> None:
|
||||
"""A failed ioctl must not leak the fd, or usblp stays busy."""
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = ["/dev/usb/lp0"]
|
||||
assert _port_status_via_usblp() is None
|
||||
mock_close.assert_called_once_with(7)
|
||||
|
||||
@ -1,9 +1,4 @@
|
||||
"""Tests for brother_printer._cups_fallback - status mapping and discovery.
|
||||
|
||||
Split from test_cups_service_part2.py under the 250-line cap. These cover the
|
||||
mapping from what CUPS says went wrong onto the Brother PJL status codes the
|
||||
report displays, plus finding the Brother queue name.
|
||||
"""
|
||||
"""Tests for brother_printer._cups_fallback module - part 2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -12,18 +7,121 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._cups_fallback import (
|
||||
_cups_reasons_to_error,
|
||||
_get_cups_economode,
|
||||
_map_cups_to_status_code,
|
||||
_port_status_to_status_code,
|
||||
find_cups_printer_name,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
_CUPS_REASONS_TO_STATUS,
|
||||
DERIVED_CUPS_ERROR,
|
||||
get_status_info,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import USBPortStatus
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
USBPortStatus,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer._cups_fallback"
|
||||
|
||||
|
||||
# ── _get_cups_economode ──────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestGetCupsEconomode:
|
||||
"""Tests for _get_cups_economode."""
|
||||
|
||||
@patch(f"{MOD}.shutil.which", return_value=None)
|
||||
def test_no_lpoptions(self, m: MagicMock) -> None:
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_economode_on(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="BREconomode/Toner Save Mode: *True False\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == "ON"
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_economode_off(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="BREconomode/Toner Save Mode: True *False\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == "OFF"
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_no_economode_line(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="Resolution/Output Resolution: 600dpi *1200dpi\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_economode_no_star_match(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="BREconomode/Toner Save Mode: True False\n"
|
||||
)
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_timeout(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = subprocess.TimeoutExpired("lpoptions", 5)
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
@patch("python_pkg.brother_printer._query.subprocess.run")
|
||||
@patch(f"{MOD}.shutil.which", return_value="/usr/bin/lpoptions")
|
||||
def test_oserror(self, w: MagicMock, mock_run: MagicMock) -> None:
|
||||
mock_run.side_effect = OSError("fail")
|
||||
assert _get_cups_economode("Brother") == ""
|
||||
|
||||
|
||||
# ── _map_cups_to_status_code ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestMapCupsToStatusCode:
|
||||
"""Tests for _map_cups_to_status_code.
|
||||
|
||||
Every code here must exist in BROTHER_STATUS_CODES; mapping CUPS onto a
|
||||
code the table does not know silently degrades to "unknown status".
|
||||
"""
|
||||
|
||||
def test_reason_match(self) -> None:
|
||||
assert _map_cups_to_status_code("idle", "toner-low-report") == "40038"
|
||||
|
||||
def test_state_match(self) -> None:
|
||||
assert _map_cups_to_status_code("idle", "none") == "10001"
|
||||
|
||||
def test_processing_state(self) -> None:
|
||||
assert _map_cups_to_status_code("processing", "none") == "10023"
|
||||
|
||||
def test_stopped_state(self) -> None:
|
||||
assert _map_cups_to_status_code("stopped", "none") == "40079"
|
||||
|
||||
def test_unknown_state(self) -> None:
|
||||
assert _map_cups_to_status_code("mystery", "none") == "10001"
|
||||
|
||||
def test_state_with_parenthetical(self) -> None:
|
||||
assert _map_cups_to_status_code("idle (on fire)", "none") == "10001"
|
||||
|
||||
def test_every_mapped_code_is_resolvable(self) -> None:
|
||||
"""Guard the class of bug where a mapping points at a deleted code."""
|
||||
for state in ("idle", "processing", "stopped"):
|
||||
code = _map_cups_to_status_code(state, "none")
|
||||
_, text, _ = get_status_info(code)
|
||||
assert "Unknown" not in text
|
||||
for reason in _CUPS_REASONS_TO_STATUS:
|
||||
code = _map_cups_to_status_code("idle", reason)
|
||||
_, text, _ = get_status_info(code)
|
||||
assert "Unknown" not in text
|
||||
|
||||
|
||||
# ── _cups_reasons_to_error ───────────────────────────────────────────
|
||||
|
||||
|
||||
class TestCupsReasonsToError:
|
||||
"""Tests for _cups_reasons_to_error."""
|
||||
|
||||
@ -1,15 +1,12 @@
|
||||
"""Tests for brother_printer._cups_fallback - fallback with a healthy port.
|
||||
|
||||
Split from test_cups_service_part3.py under the 250-line cap. When the USB port
|
||||
reports no hardware fault, the status has to be derived from the page-count
|
||||
estimate or from the CUPS state, which is what these cover.
|
||||
"""
|
||||
"""Tests for brother_printer._cups_fallback module - part 3 (query_usb_via_cups)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._cups_fallback import query_usb_via_cups
|
||||
from python_pkg.brother_printer._cups_fallback import (
|
||||
query_usb_via_cups,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
DERIVED_TONER_END,
|
||||
DERIVED_TONER_LOW,
|
||||
@ -22,8 +19,96 @@ from python_pkg.brother_printer.data_classes import (
|
||||
MOD = "python_pkg.brother_printer._cups_fallback"
|
||||
|
||||
|
||||
class TestQueryUsbViaCupsPortOk:
|
||||
"""query_usb_via_cups when the USB port status reports no fault."""
|
||||
# ── query_usb_via_cups ───────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestQueryUsbViaCups:
|
||||
"""Tests for query_usb_via_cups."""
|
||||
|
||||
@patch(f"{MOD}.find_cups_printer_name", return_value="")
|
||||
@patch(f"{MOD}._ensure_cups_running", return_value=True)
|
||||
def test_no_printer(self, e: MagicMock, f: MagicMock) -> None:
|
||||
result = query_usb_via_cups()
|
||||
assert result.error != ""
|
||||
|
||||
def test_no_port_status_idle(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}._ensure_cups_running", return_value=True),
|
||||
patch(f"{MOD}.find_cups_printer_name", return_value="Brother"),
|
||||
patch(f"{MOD}._get_pyusb_device_info", return_value={}),
|
||||
patch(
|
||||
f"{MOD}.printer_info_from_cups",
|
||||
return_value={"product": "HL-1110", "serial": "ABC"},
|
||||
),
|
||||
patch(
|
||||
f"{MOD}._get_cups_ipp_status",
|
||||
return_value={
|
||||
"printer-state": "idle",
|
||||
"printer-state-reasons": "none",
|
||||
"printer-state-message": "Ready",
|
||||
},
|
||||
),
|
||||
patch(f"{MOD}._get_cups_economode", return_value="ON"),
|
||||
patch(f"{MOD}._query_usb_port_status_raw", return_value=None),
|
||||
):
|
||||
result = query_usb_via_cups()
|
||||
assert result.online == "TRUE"
|
||||
assert result.product == "HL-1110"
|
||||
assert result.economode == "ON"
|
||||
|
||||
def test_no_port_status_stopped(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}._ensure_cups_running", return_value=True),
|
||||
patch(f"{MOD}.find_cups_printer_name", return_value="Brother"),
|
||||
patch(f"{MOD}._get_pyusb_device_info", return_value={}),
|
||||
patch(
|
||||
f"{MOD}.printer_info_from_cups",
|
||||
return_value={"product": "", "serial": ""},
|
||||
),
|
||||
patch(
|
||||
f"{MOD}._get_cups_ipp_status",
|
||||
return_value={
|
||||
"printer-state": "stopped",
|
||||
"printer-state-reasons": "none",
|
||||
},
|
||||
),
|
||||
patch(f"{MOD}._get_cups_economode", return_value=""),
|
||||
patch(f"{MOD}._query_usb_port_status_raw", return_value=None),
|
||||
):
|
||||
result = query_usb_via_cups()
|
||||
assert result.online == "FALSE"
|
||||
assert result.product == "Brother Laser Printer"
|
||||
|
||||
def test_port_status_hw_error(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}._ensure_cups_running", return_value=True),
|
||||
patch(f"{MOD}.find_cups_printer_name", return_value="Brother"),
|
||||
patch(f"{MOD}._get_pyusb_device_info", return_value={}),
|
||||
patch(
|
||||
f"{MOD}.printer_info_from_cups",
|
||||
return_value={"product": "", "serial": ""},
|
||||
),
|
||||
patch(
|
||||
f"{MOD}._get_cups_ipp_status",
|
||||
return_value={
|
||||
"printer-state": "stopped",
|
||||
"printer-state-reasons": "none",
|
||||
},
|
||||
),
|
||||
patch(f"{MOD}._get_cups_economode", return_value=""),
|
||||
patch(
|
||||
f"{MOD}._query_usb_port_status_raw",
|
||||
return_value=USBPortStatus(
|
||||
error=True,
|
||||
paper_empty=True,
|
||||
online=False,
|
||||
raw_byte=0x20,
|
||||
),
|
||||
),
|
||||
):
|
||||
result = query_usb_via_cups()
|
||||
assert result.status_code == "41000"
|
||||
assert result.online == "FALSE"
|
||||
|
||||
def test_port_ok_toner_exhausted(self) -> None:
|
||||
with (
|
||||
@ -1,4 +1,4 @@
|
||||
"""Tests for brother_printer._cups_fallback - IPP attribute queries."""
|
||||
"""Tests for brother_printer._cups_fallback module - part 4 (IPP queries)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -1,233 +0,0 @@
|
||||
"""Tests for brother_printer.cups_service - USB port status via usblp.
|
||||
|
||||
Split from test_cups_service.py under the 250-line cap. These tests read the
|
||||
printer's IEEE 1284 status byte through an ioctl on /dev/usb/lp*, so they patch
|
||||
fcntl, os and Path on the module under test.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_service import (
|
||||
_cups_is_busy,
|
||||
_port_status_via_usblp,
|
||||
_query_usb_port_status_raw,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import USBPortStatus
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_service"
|
||||
|
||||
|
||||
class TestPortStatusViaUsblp:
|
||||
"""The zero-side-effect path: read the status byte from /dev/usb/lp*."""
|
||||
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_no_dev_dir(self, mock_path: MagicMock) -> None:
|
||||
mock_path.return_value.is_dir.return_value = False
|
||||
assert _port_status_via_usblp() is None
|
||||
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_no_devices(self, mock_path: MagicMock) -> None:
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = []
|
||||
assert _port_status_via_usblp() is None
|
||||
|
||||
@patch(f"{MOD}.os.close")
|
||||
@patch(f"{MOD}.fcntl.ioctl")
|
||||
@patch(f"{MOD}.os.open", return_value=7)
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_success(
|
||||
self,
|
||||
mock_path: MagicMock,
|
||||
mock_open: MagicMock,
|
||||
mock_ioctl: MagicMock,
|
||||
mock_close: MagicMock,
|
||||
) -> None:
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = ["/dev/usb/lp0"]
|
||||
|
||||
def fill(fd: int, req: int, buf: bytearray) -> None:
|
||||
buf[0] = 0x18
|
||||
|
||||
mock_ioctl.side_effect = fill
|
||||
result = _port_status_via_usblp()
|
||||
assert result is not None
|
||||
assert result.online is True
|
||||
assert result.error is False
|
||||
assert result.paper_empty is False
|
||||
# Must never block: the printer may be mid-job.
|
||||
assert mock_open.call_args[0][1] & os.O_NONBLOCK
|
||||
mock_close.assert_called_once_with(7)
|
||||
|
||||
@patch(f"{MOD}.os.open", side_effect=OSError("busy"))
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_open_fails(self, mock_path: MagicMock, mock_open: MagicMock) -> None:
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = ["/dev/usb/lp0"]
|
||||
assert _port_status_via_usblp() is None
|
||||
|
||||
|
||||
class TestQueryUsbPortStatusRaw:
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=USBPortStatus(raw_byte=0x18))
|
||||
def test_prefers_usblp(self, m: MagicMock) -> None:
|
||||
"""The free path wins; pyusb is never touched."""
|
||||
result = _query_usb_port_status_raw("idle")
|
||||
assert result is not None
|
||||
assert result.raw_byte == 0x18
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_never_probes_while_printing(self, m: MagicMock) -> None:
|
||||
"""Regression: probing mid-job used to stop CUPS and kill the print."""
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("processing") is None
|
||||
mock_usb.core.find.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_import_error(self, m: MagicMock) -> None:
|
||||
with patch.dict(
|
||||
"sys.modules", {"usb": None, "usb.core": None, "usb.util": None}
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_dev_none(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_usb.core.find.return_value = None
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_success_reattaches_driver(self, m: MagicMock) -> None:
|
||||
"""usblp must get its device back, or every later run hits the fallback."""
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = True
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
result = _query_usb_port_status_raw("idle")
|
||||
assert result is not None
|
||||
assert result.online is True
|
||||
mock_dev.reset.assert_not_called()
|
||||
mock_dev.attach_kernel_driver.assert_called_once_with(0)
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_kernel_driver_not_active(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = False
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
result = _query_usb_port_status_raw("idle")
|
||||
assert result is not None
|
||||
# Nothing was detached, so nothing should be re-attached.
|
||||
mock_dev.attach_kernel_driver.assert_not_called()
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_kernel_driver_usberror(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
usb_error_cls = type("USBError", (Exception,), {})
|
||||
mock_dev.is_kernel_driver_active.side_effect = usb_error_cls("err")
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = usb_error_cls
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is not None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_oserror_during_transfer(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = False
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
mock_usb.util.claim_interface.side_effect = OSError("usb fail")
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is None
|
||||
|
||||
@patch(f"{MOD}._port_status_via_usblp", return_value=None)
|
||||
def test_attach_failure_is_survivable(self, m: MagicMock) -> None:
|
||||
import sys as _sys
|
||||
|
||||
mock_usb = MagicMock()
|
||||
mock_dev = MagicMock()
|
||||
mock_dev.is_kernel_driver_active.return_value = True
|
||||
mock_dev.ctrl_transfer.return_value = [0x18]
|
||||
mock_dev.attach_kernel_driver.side_effect = OSError("cannot reattach")
|
||||
mock_usb.core.find.return_value = mock_dev
|
||||
mock_usb.core.USBError = type("USBError", (Exception,), {})
|
||||
with patch.dict(
|
||||
_sys.modules,
|
||||
{"usb": mock_usb, "usb.core": mock_usb.core, "usb.util": mock_usb.util},
|
||||
):
|
||||
assert _query_usb_port_status_raw("idle") is not None
|
||||
|
||||
|
||||
class TestCupsIsBusy:
|
||||
def test_processing(self) -> None:
|
||||
assert _cups_is_busy("processing") is True
|
||||
|
||||
def test_printing_text(self) -> None:
|
||||
assert _cups_is_busy("now printing Brother-98") is True
|
||||
|
||||
def test_idle(self) -> None:
|
||||
assert _cups_is_busy("idle") is False
|
||||
|
||||
def test_empty(self) -> None:
|
||||
assert _cups_is_busy("") is False
|
||||
|
||||
|
||||
class TestPortStatusViaUsblpIoctlFailure:
|
||||
@patch(f"{MOD}.os.close")
|
||||
@patch(f"{MOD}.fcntl.ioctl", side_effect=OSError("not supported"))
|
||||
@patch(f"{MOD}.os.open", return_value=7)
|
||||
@patch(f"{MOD}.Path")
|
||||
def test_ioctl_failure_still_closes_fd(
|
||||
self,
|
||||
mock_path: MagicMock,
|
||||
mock_open: MagicMock,
|
||||
mock_ioctl: MagicMock,
|
||||
mock_close: MagicMock,
|
||||
) -> None:
|
||||
"""A failed ioctl must not leak the fd, or usblp stays busy."""
|
||||
mock_path.return_value.is_dir.return_value = True
|
||||
mock_path.return_value.glob.return_value = ["/dev/usb/lp0"]
|
||||
assert _port_status_via_usblp() is None
|
||||
mock_close.assert_called_once_with(7)
|
||||
@ -8,15 +8,25 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
NetworkResult,
|
||||
SupplyReadings,
|
||||
USBPortStatus,
|
||||
USBResult,
|
||||
)
|
||||
from python_pkg.brother_printer.display import (
|
||||
_classify_percentage_level,
|
||||
_classify_supply_level,
|
||||
_collect_supply_items,
|
||||
_display_cups_fallback_note,
|
||||
_display_pjl_status,
|
||||
_display_report_header,
|
||||
_display_supply_levels,
|
||||
_display_supply_warnings,
|
||||
_display_usb_device_info,
|
||||
_format_status_detail,
|
||||
_format_supply_bar,
|
||||
_parse_supply_value,
|
||||
_process_supply_item,
|
||||
display_usb_results,
|
||||
)
|
||||
|
||||
@ -202,3 +212,152 @@ class TestDisplayUsbResults:
|
||||
pytest.raises(SystemExit),
|
||||
):
|
||||
display_usb_results(r)
|
||||
|
||||
|
||||
class TestClassifyPercentageLevel:
|
||||
def test_low(self) -> None:
|
||||
pct, _, _, _, replace = _classify_percentage_level("Toner", 5)
|
||||
assert pct == 5
|
||||
assert replace is True
|
||||
|
||||
def test_warn(self) -> None:
|
||||
_, _, _, warn, replace = _classify_percentage_level("Toner", 20)
|
||||
assert replace is False
|
||||
assert "order soon" in warn
|
||||
|
||||
def test_ok(self) -> None:
|
||||
_, _, _, warn, replace = _classify_percentage_level("Toner", 80)
|
||||
assert replace is False
|
||||
assert warn == ""
|
||||
|
||||
|
||||
class TestClassifySupplyLevel:
|
||||
def test_snmp_ok(self) -> None:
|
||||
_, text, _, _, replace = _classify_supply_level("Toner", 100, -3)
|
||||
assert text == "OK"
|
||||
assert replace is False
|
||||
|
||||
def test_snmp_low(self) -> None:
|
||||
_, text, _, _, replace = _classify_supply_level("Toner", 100, -2)
|
||||
assert text == "LOW"
|
||||
assert replace is True
|
||||
|
||||
def test_empty(self) -> None:
|
||||
_, text, _, _, replace = _classify_supply_level("Toner", 100, 0)
|
||||
assert text == "EMPTY"
|
||||
assert replace is True
|
||||
|
||||
def test_normal_percentage(self) -> None:
|
||||
pct, _, _, _, replace = _classify_supply_level("Toner", 100, 80)
|
||||
assert pct == 80
|
||||
assert replace is False
|
||||
|
||||
def test_no_max_val(self) -> None:
|
||||
pct, text, _, _, _ = _classify_supply_level("Toner", 0, 50)
|
||||
assert pct == -1
|
||||
assert text == ""
|
||||
|
||||
def test_over_100_capped(self) -> None:
|
||||
pct, _, _, _, _ = _classify_supply_level("Toner", 50, 100)
|
||||
assert pct == 100
|
||||
|
||||
|
||||
class TestFormatSupplyBar:
|
||||
def test_negative(self) -> None:
|
||||
assert _format_supply_bar(-1) == ""
|
||||
|
||||
def test_zero(self) -> None:
|
||||
bar = _format_supply_bar(0)
|
||||
assert "░" in bar
|
||||
|
||||
def test_full(self) -> None:
|
||||
bar = _format_supply_bar(100)
|
||||
assert "█" in bar
|
||||
|
||||
|
||||
class TestProcessSupplyItem:
|
||||
def test_normal(self) -> None:
|
||||
item = _process_supply_item("Toner", 100, 80)
|
||||
assert item.status_text == "80%"
|
||||
|
||||
def test_empty(self) -> None:
|
||||
item = _process_supply_item("Toner", 100, 0)
|
||||
assert item.needs_replacement is True
|
||||
|
||||
|
||||
class TestDisplaySupplyWarnings:
|
||||
def test_replacement_needed(self) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_warnings(
|
||||
needs_replacement=True,
|
||||
warnings=["Toner low"],
|
||||
)
|
||||
assert "ACTION NEEDED" in out.getvalue()
|
||||
|
||||
def test_warnings_only(self) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_warnings(
|
||||
needs_replacement=False,
|
||||
warnings=["Toner at 20%"],
|
||||
)
|
||||
assert "HEADS UP" in out.getvalue()
|
||||
|
||||
def test_all_healthy(self) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_warnings(
|
||||
needs_replacement=False,
|
||||
warnings=[],
|
||||
)
|
||||
assert "healthy" in out.getvalue()
|
||||
|
||||
|
||||
class TestParseSupplyValue:
|
||||
def test_valid(self) -> None:
|
||||
assert _parse_supply_value(["10", "20"], 0) == 10
|
||||
|
||||
def test_index_error(self) -> None:
|
||||
assert _parse_supply_value([], 0) == 0
|
||||
|
||||
def test_value_error(self) -> None:
|
||||
assert _parse_supply_value(["abc"], 0) == 0
|
||||
|
||||
|
||||
class TestCollectSupplyItems:
|
||||
def test_collect(self) -> None:
|
||||
result = NetworkResult(
|
||||
supplies=SupplyReadings(
|
||||
descriptions=["Toner", "Drum"],
|
||||
max_values=["100", "200"],
|
||||
levels=["80", "150"],
|
||||
),
|
||||
)
|
||||
items, descs = _collect_supply_items(result)
|
||||
assert len(items) == 2
|
||||
assert descs == ["Toner", "Drum"]
|
||||
|
||||
|
||||
class TestDisplaySupplyLevels:
|
||||
def test_with_items(self) -> None:
|
||||
result = NetworkResult(
|
||||
supplies=SupplyReadings(
|
||||
descriptions=["Toner"],
|
||||
max_values=["100"],
|
||||
levels=["80"],
|
||||
),
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_levels(result)
|
||||
assert "Toner" in out.getvalue()
|
||||
|
||||
def test_needs_replacement_and_warning(self) -> None:
|
||||
result = NetworkResult(
|
||||
supplies=SupplyReadings(
|
||||
descriptions=["Toner", "Drum"],
|
||||
max_values=["100", "100"],
|
||||
levels=["0", "15"],
|
||||
),
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_levels(result)
|
||||
text = out.getvalue()
|
||||
assert "ACTION NEEDED" in text
|
||||
|
||||
@ -1,152 +0,0 @@
|
||||
"""Tests for brother_printer._page_delivery - dropped-page detection.
|
||||
|
||||
Split from test_consumables_part2.py under the 250-line cap. These are exactly
|
||||
the tests whose functions moved to _page_delivery, so the file needs only that
|
||||
module's patch target rather than the two constants the combined file carried.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._page_delivery import (
|
||||
_snapshot_counters,
|
||||
check_page_delivery,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer._page_delivery"
|
||||
|
||||
|
||||
class TestCheckPageDelivery:
|
||||
"""Spotting pages the printer silently dropped.
|
||||
|
||||
CUPS calls a job successful once the data leaves the machine, so this
|
||||
comparison against the printer's own counter is the only signal that a page
|
||||
never actually came out.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_detects_dropped_pages(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
"""Replay of the real failure: CUPS sent 63, printer printed none."""
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2087,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.cups_pages == 63
|
||||
assert check.printer_pages == 0
|
||||
assert check.dropped == 63
|
||||
assert check.suspected is True
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_healthy_job_does_not_warn(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2024,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.dropped == 0
|
||||
assert check.suspected is False
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1780)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_small_gap_is_not_a_warning(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
"""A page or two of drift is timing, not a fault."""
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2087,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.dropped == 2
|
||||
assert check.suspected is False
|
||||
|
||||
def test_skipped_while_printing(self) -> None:
|
||||
"""Mid-job the counters legitimately disagree, so never compare."""
|
||||
assert check_page_delivery(2087, queue_idle=False).suspected is False
|
||||
|
||||
def test_skipped_without_printer_count(self) -> None:
|
||||
assert check_page_delivery(0, queue_idle=True).suspected is False
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_first_run_only_establishes_baseline(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {"last_printer_count": 0, "last_cups_total": 0}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.suspected is False
|
||||
mock_snap.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=10)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_log_rotation_draws_no_conclusion(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
"""A rotated page log makes the delta negative; do not cry wolf."""
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 2087,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.suspected is False
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
def test_printer_counter_reset_draws_no_conclusion(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
mock_cups: MagicMock,
|
||||
mock_snap: MagicMock,
|
||||
) -> None:
|
||||
mock_load.return_value = {
|
||||
"last_printer_count": 5000,
|
||||
"last_cups_total": 1778,
|
||||
}
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.suspected is False
|
||||
|
||||
|
||||
class TestSnapshotCounters:
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
def test_writes_new_snapshot(self, mock_save: MagicMock) -> None:
|
||||
state = {"last_printer_count": 2000, "last_cups_total": 1700}
|
||||
_snapshot_counters(state, 2087, 1778)
|
||||
saved = mock_save.call_args[0][0]
|
||||
assert saved["last_printer_count"] == 2087
|
||||
assert saved["last_cups_total"] == 1778
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
def test_unchanged_counters_skip_the_write(self, mock_save: MagicMock) -> None:
|
||||
"""Do not rewrite the file on every run when nothing moved."""
|
||||
state = {"last_printer_count": 2087, "last_cups_total": 1778}
|
||||
_snapshot_counters(state, 2087, 1778)
|
||||
mock_save.assert_not_called()
|
||||
@ -1,174 +0,0 @@
|
||||
"""Tests for the consumable supply level maths and its display.
|
||||
|
||||
Split from test_display.py under the 250-line cap. The classification and bar
|
||||
formatting live in _supply; the two functions that print the section stay in
|
||||
display, where test_display_part2.py patches them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
from unittest.mock import patch
|
||||
|
||||
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,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import NetworkResult, SupplyReadings
|
||||
from python_pkg.brother_printer.display import (
|
||||
_display_supply_levels,
|
||||
_display_supply_warnings,
|
||||
)
|
||||
|
||||
|
||||
class TestClassifyPercentageLevel:
|
||||
def test_low(self) -> None:
|
||||
pct, _, _, _, replace = _classify_percentage_level("Toner", 5)
|
||||
assert pct == 5
|
||||
assert replace is True
|
||||
|
||||
def test_warn(self) -> None:
|
||||
_, _, _, warn, replace = _classify_percentage_level("Toner", 20)
|
||||
assert replace is False
|
||||
assert "order soon" in warn
|
||||
|
||||
def test_ok(self) -> None:
|
||||
_, _, _, warn, replace = _classify_percentage_level("Toner", 80)
|
||||
assert replace is False
|
||||
assert warn == ""
|
||||
|
||||
|
||||
class TestClassifySupplyLevel:
|
||||
def test_snmp_ok(self) -> None:
|
||||
_, text, _, _, replace = _classify_supply_level("Toner", 100, -3)
|
||||
assert text == "OK"
|
||||
assert replace is False
|
||||
|
||||
def test_snmp_low(self) -> None:
|
||||
_, text, _, _, replace = _classify_supply_level("Toner", 100, -2)
|
||||
assert text == "LOW"
|
||||
assert replace is True
|
||||
|
||||
def test_empty(self) -> None:
|
||||
_, text, _, _, replace = _classify_supply_level("Toner", 100, 0)
|
||||
assert text == "EMPTY"
|
||||
assert replace is True
|
||||
|
||||
def test_normal_percentage(self) -> None:
|
||||
pct, _, _, _, replace = _classify_supply_level("Toner", 100, 80)
|
||||
assert pct == 80
|
||||
assert replace is False
|
||||
|
||||
def test_no_max_val(self) -> None:
|
||||
pct, text, _, _, _ = _classify_supply_level("Toner", 0, 50)
|
||||
assert pct == -1
|
||||
assert text == ""
|
||||
|
||||
def test_over_100_capped(self) -> None:
|
||||
pct, _, _, _, _ = _classify_supply_level("Toner", 50, 100)
|
||||
assert pct == 100
|
||||
|
||||
|
||||
class TestFormatSupplyBar:
|
||||
def test_negative(self) -> None:
|
||||
assert _format_supply_bar(-1) == ""
|
||||
|
||||
def test_zero(self) -> None:
|
||||
bar = _format_supply_bar(0)
|
||||
assert "░" in bar
|
||||
|
||||
def test_full(self) -> None:
|
||||
bar = _format_supply_bar(100)
|
||||
assert "█" in bar
|
||||
|
||||
|
||||
class TestProcessSupplyItem:
|
||||
def test_normal(self) -> None:
|
||||
item = _process_supply_item("Toner", 100, 80)
|
||||
assert item.status_text == "80%"
|
||||
|
||||
def test_empty(self) -> None:
|
||||
item = _process_supply_item("Toner", 100, 0)
|
||||
assert item.needs_replacement is True
|
||||
|
||||
|
||||
class TestDisplaySupplyWarnings:
|
||||
def test_replacement_needed(self) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_warnings(
|
||||
needs_replacement=True,
|
||||
warnings=["Toner low"],
|
||||
)
|
||||
assert "ACTION NEEDED" in out.getvalue()
|
||||
|
||||
def test_warnings_only(self) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_warnings(
|
||||
needs_replacement=False,
|
||||
warnings=["Toner at 20%"],
|
||||
)
|
||||
assert "HEADS UP" in out.getvalue()
|
||||
|
||||
def test_all_healthy(self) -> None:
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_warnings(
|
||||
needs_replacement=False,
|
||||
warnings=[],
|
||||
)
|
||||
assert "healthy" in out.getvalue()
|
||||
|
||||
|
||||
class TestParseSupplyValue:
|
||||
def test_valid(self) -> None:
|
||||
assert _parse_supply_value(["10", "20"], 0) == 10
|
||||
|
||||
def test_index_error(self) -> None:
|
||||
assert _parse_supply_value([], 0) == 0
|
||||
|
||||
def test_value_error(self) -> None:
|
||||
assert _parse_supply_value(["abc"], 0) == 0
|
||||
|
||||
|
||||
class TestCollectSupplyItems:
|
||||
def test_collect(self) -> None:
|
||||
result = NetworkResult(
|
||||
supplies=SupplyReadings(
|
||||
descriptions=["Toner", "Drum"],
|
||||
max_values=["100", "200"],
|
||||
levels=["80", "150"],
|
||||
),
|
||||
)
|
||||
items, descs = _collect_supply_items(result)
|
||||
assert len(items) == 2
|
||||
assert descs == ["Toner", "Drum"]
|
||||
|
||||
|
||||
class TestDisplaySupplyLevels:
|
||||
def test_with_items(self) -> None:
|
||||
result = NetworkResult(
|
||||
supplies=SupplyReadings(
|
||||
descriptions=["Toner"],
|
||||
max_values=["100"],
|
||||
levels=["80"],
|
||||
),
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_levels(result)
|
||||
assert "Toner" in out.getvalue()
|
||||
|
||||
def test_needs_replacement_and_warning(self) -> None:
|
||||
result = NetworkResult(
|
||||
supplies=SupplyReadings(
|
||||
descriptions=["Toner", "Drum"],
|
||||
max_values=["100", "100"],
|
||||
levels=["0", "15"],
|
||||
),
|
||||
)
|
||||
with patch("sys.stdout", new_callable=StringIO) as out:
|
||||
_display_supply_levels(result)
|
||||
text = out.getvalue()
|
||||
assert "ACTION NEEDED" in text
|
||||
@ -1,15 +1,22 @@
|
||||
"""Tests for brother_printer.usb_query - discovery and PJL response parsing."""
|
||||
"""Tests for brother_printer.usb_query module."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.data_classes import USBResult
|
||||
from python_pkg.brother_printer.usb_query import (
|
||||
_init_usb_result,
|
||||
_parse_pagecount,
|
||||
_parse_status,
|
||||
_parse_variables,
|
||||
_retry_pjl_query,
|
||||
_run_pjl_queries,
|
||||
find_brother_usb,
|
||||
find_usb_printer_dev,
|
||||
query_usb_pjl,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.usb_query"
|
||||
@ -119,3 +126,203 @@ class TestParseVariables:
|
||||
def test_not_found(self) -> None:
|
||||
result = USBResult()
|
||||
assert _parse_variables("nothing\n", result) is False
|
||||
|
||||
|
||||
class TestRetryPjlQuery:
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}.pjl_query")
|
||||
def test_success_first_attempt(
|
||||
self,
|
||||
mock_pjl: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
mock_pjl.return_value = "CODE=10001\n"
|
||||
_retry_pjl_query(42, "@PJL INFO STATUS", _parse_status, result, 2)
|
||||
assert result.status_code == "10001"
|
||||
assert mock_pjl.call_count == 1
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}.pjl_query")
|
||||
def test_retry_then_success(
|
||||
self,
|
||||
mock_pjl: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
mock_pjl.side_effect = ["garbage\n", "CODE=10001\n"]
|
||||
_retry_pjl_query(42, "@PJL INFO STATUS", _parse_status, result, 2)
|
||||
assert result.status_code == "10001"
|
||||
assert mock_pjl.call_count == 2
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}.pjl_query")
|
||||
def test_all_retries_fail(
|
||||
self,
|
||||
mock_pjl: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
mock_pjl.return_value = "garbage\n"
|
||||
_retry_pjl_query(42, "@PJL INFO STATUS", _parse_status, result, 2)
|
||||
assert result.status_code == ""
|
||||
assert mock_pjl.call_count == 3
|
||||
|
||||
|
||||
class TestRunPjlQueries:
|
||||
@patch(f"{MOD}._retry_pjl_query")
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}._write_with_deadline")
|
||||
def test_runs_status_pagecount_and_variables(
|
||||
self,
|
||||
mock_write: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
mock_retry: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
_run_pjl_queries(42, result, 2)
|
||||
assert mock_retry.call_count == 3
|
||||
queried = [call.args[1] for call in mock_retry.call_args_list]
|
||||
assert "@PJL INFO PAGECOUNT" in queried
|
||||
|
||||
|
||||
class TestParsePagecount:
|
||||
def test_found(self) -> None:
|
||||
result = USBResult()
|
||||
assert _parse_pagecount("PAGECOUNT=2014\n", result) is True
|
||||
assert result.page_count == "2014"
|
||||
|
||||
def test_not_found(self) -> None:
|
||||
result = USBResult()
|
||||
assert _parse_pagecount("nothing\n", result) is False
|
||||
assert result.page_count == ""
|
||||
|
||||
def test_non_numeric_rejected(self) -> None:
|
||||
"""A garbled reply must not become a page count."""
|
||||
result = USBResult()
|
||||
assert _parse_pagecount("PAGECOUNT=???\n", result) is False
|
||||
assert result.page_count == ""
|
||||
|
||||
|
||||
class TestInitUsbResult:
|
||||
@patch(f"{MOD}.printer_info_from_cups")
|
||||
def test_from_cups(self, mock_cups: MagicMock) -> None:
|
||||
mock_cups.return_value = {"product": "HL-1110", "serial": "SN1"}
|
||||
result = _init_usb_result("/dev/usb/lp0")
|
||||
assert result.device == "/dev/usb/lp0"
|
||||
assert result.product == "HL-1110"
|
||||
assert result.serial == "SN1"
|
||||
|
||||
@patch(f"{MOD}.printer_info_from_cups")
|
||||
def test_no_product(self, mock_cups: MagicMock) -> None:
|
||||
mock_cups.return_value = {"product": "", "serial": ""}
|
||||
result = _init_usb_result("/dev/usb/lp0")
|
||||
assert result.product == "Brother Laser Printer"
|
||||
|
||||
|
||||
class TestQueryUsbPjl:
|
||||
def test_success(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", return_value=10) as mock_open,
|
||||
patch(f"{MOD}._run_pjl_queries"),
|
||||
patch(f"{MOD}.os.close"),
|
||||
):
|
||||
mock_init.return_value = USBResult(
|
||||
device="/dev/usb/lp0",
|
||||
status_code="10001",
|
||||
)
|
||||
result = query_usb_pjl()
|
||||
assert result.device == "/dev/usb/lp0"
|
||||
assert result.error == ""
|
||||
# The whole point: a blocking open() hangs on an unwell printer.
|
||||
assert mock_open.call_args[0][1] & os.O_NONBLOCK
|
||||
|
||||
@patch(f"{MOD}.find_usb_printer_dev", return_value=None)
|
||||
def test_no_dev_falls_back_to_cups(self, f: MagicMock) -> None:
|
||||
with patch(
|
||||
"python_pkg.brother_printer._cups_fallback.query_usb_via_cups",
|
||||
) as mock_cups:
|
||||
mock_cups.return_value = USBResult(device="cups")
|
||||
result = query_usb_pjl()
|
||||
assert result.device == "cups"
|
||||
|
||||
@patch(f"{MOD}.os.access", return_value=False)
|
||||
@patch(f"{MOD}._init_usb_result")
|
||||
@patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0")
|
||||
def test_permission_denied(
|
||||
self,
|
||||
f: MagicMock,
|
||||
mock_init: MagicMock,
|
||||
a: MagicMock,
|
||||
) -> None:
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "Permission denied" in result.error
|
||||
|
||||
def test_silent_printer_is_reported_not_hidden(self) -> None:
|
||||
"""A printer that answers nothing must say so, not look healthy."""
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", return_value=10),
|
||||
patch(f"{MOD}._run_pjl_queries"),
|
||||
patch(f"{MOD}.os.close"),
|
||||
):
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "did not answer" in result.error
|
||||
|
||||
def test_busy_device_explains_why(self) -> None:
|
||||
"""EBUSY means CUPS holds the printer mid-job; say that."""
|
||||
exc = OSError("busy")
|
||||
exc.errno = errno.EBUSY
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", side_effect=exc),
|
||||
):
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "busy" in result.error.lower()
|
||||
|
||||
def test_eacces_suggests_sudo(self) -> None:
|
||||
exc = OSError("denied")
|
||||
exc.errno = errno.EACCES
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", side_effect=exc),
|
||||
):
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "sudo" in result.error
|
||||
|
||||
@patch(f"{MOD}.os.open", side_effect=OSError("no device"))
|
||||
@patch(f"{MOD}.os.access", return_value=True)
|
||||
@patch(f"{MOD}._init_usb_result")
|
||||
@patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0")
|
||||
def test_oserror_fd_none(
|
||||
self,
|
||||
f: MagicMock,
|
||||
mock_init: MagicMock,
|
||||
a: MagicMock,
|
||||
o: MagicMock,
|
||||
) -> None:
|
||||
"""os.open raises OSError before fd is set -> fd stays None."""
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "no device" in result.error
|
||||
|
||||
@ -1,224 +0,0 @@
|
||||
"""Tests for brother_printer.usb_query - running the PJL query sequence.
|
||||
|
||||
Split from test_usb_query.py under the 250-line cap. These patch the wire-level
|
||||
helpers on usb_query rather than on _pjl_io, because that is the module whose
|
||||
globals the retry and sequencing code resolves them through.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.data_classes import USBResult
|
||||
from python_pkg.brother_printer.usb_query import (
|
||||
_init_usb_result,
|
||||
_parse_pagecount,
|
||||
_parse_status,
|
||||
_retry_pjl_query,
|
||||
_run_pjl_queries,
|
||||
query_usb_pjl,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.usb_query"
|
||||
|
||||
|
||||
class TestRetryPjlQuery:
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}.pjl_query")
|
||||
def test_success_first_attempt(
|
||||
self,
|
||||
mock_pjl: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
mock_pjl.return_value = "CODE=10001\n"
|
||||
_retry_pjl_query(42, "@PJL INFO STATUS", _parse_status, result, 2)
|
||||
assert result.status_code == "10001"
|
||||
assert mock_pjl.call_count == 1
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}.pjl_query")
|
||||
def test_retry_then_success(
|
||||
self,
|
||||
mock_pjl: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
mock_pjl.side_effect = ["garbage\n", "CODE=10001\n"]
|
||||
_retry_pjl_query(42, "@PJL INFO STATUS", _parse_status, result, 2)
|
||||
assert result.status_code == "10001"
|
||||
assert mock_pjl.call_count == 2
|
||||
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}.pjl_query")
|
||||
def test_all_retries_fail(
|
||||
self,
|
||||
mock_pjl: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
mock_pjl.return_value = "garbage\n"
|
||||
_retry_pjl_query(42, "@PJL INFO STATUS", _parse_status, result, 2)
|
||||
assert result.status_code == ""
|
||||
assert mock_pjl.call_count == 3
|
||||
|
||||
|
||||
class TestRunPjlQueries:
|
||||
@patch(f"{MOD}._retry_pjl_query")
|
||||
@patch(f"{MOD}.time.sleep")
|
||||
@patch(f"{MOD}._drain_buffer")
|
||||
@patch(f"{MOD}._write_with_deadline")
|
||||
def test_runs_status_pagecount_and_variables(
|
||||
self,
|
||||
mock_write: MagicMock,
|
||||
d: MagicMock,
|
||||
s: MagicMock,
|
||||
mock_retry: MagicMock,
|
||||
) -> None:
|
||||
result = USBResult()
|
||||
_run_pjl_queries(42, result, 2)
|
||||
assert mock_retry.call_count == 3
|
||||
queried = [call.args[1] for call in mock_retry.call_args_list]
|
||||
assert "@PJL INFO PAGECOUNT" in queried
|
||||
|
||||
|
||||
class TestParsePagecount:
|
||||
def test_found(self) -> None:
|
||||
result = USBResult()
|
||||
assert _parse_pagecount("PAGECOUNT=2014\n", result) is True
|
||||
assert result.page_count == "2014"
|
||||
|
||||
def test_not_found(self) -> None:
|
||||
result = USBResult()
|
||||
assert _parse_pagecount("nothing\n", result) is False
|
||||
assert result.page_count == ""
|
||||
|
||||
def test_non_numeric_rejected(self) -> None:
|
||||
"""A garbled reply must not become a page count."""
|
||||
result = USBResult()
|
||||
assert _parse_pagecount("PAGECOUNT=???\n", result) is False
|
||||
assert result.page_count == ""
|
||||
|
||||
|
||||
class TestInitUsbResult:
|
||||
@patch(f"{MOD}.printer_info_from_cups")
|
||||
def test_from_cups(self, mock_cups: MagicMock) -> None:
|
||||
mock_cups.return_value = {"product": "HL-1110", "serial": "SN1"}
|
||||
result = _init_usb_result("/dev/usb/lp0")
|
||||
assert result.device == "/dev/usb/lp0"
|
||||
assert result.product == "HL-1110"
|
||||
assert result.serial == "SN1"
|
||||
|
||||
@patch(f"{MOD}.printer_info_from_cups")
|
||||
def test_no_product(self, mock_cups: MagicMock) -> None:
|
||||
mock_cups.return_value = {"product": "", "serial": ""}
|
||||
result = _init_usb_result("/dev/usb/lp0")
|
||||
assert result.product == "Brother Laser Printer"
|
||||
|
||||
|
||||
class TestQueryUsbPjl:
|
||||
def test_success(self) -> None:
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", return_value=10) as mock_open,
|
||||
patch(f"{MOD}._run_pjl_queries"),
|
||||
patch(f"{MOD}.os.close"),
|
||||
):
|
||||
mock_init.return_value = USBResult(
|
||||
device="/dev/usb/lp0",
|
||||
status_code="10001",
|
||||
)
|
||||
result = query_usb_pjl()
|
||||
assert result.device == "/dev/usb/lp0"
|
||||
assert result.error == ""
|
||||
# The whole point: a blocking open() hangs on an unwell printer.
|
||||
assert mock_open.call_args[0][1] & os.O_NONBLOCK
|
||||
|
||||
@patch(f"{MOD}.find_usb_printer_dev", return_value=None)
|
||||
def test_no_dev_falls_back_to_cups(self, f: MagicMock) -> None:
|
||||
with patch(
|
||||
"python_pkg.brother_printer._cups_fallback.query_usb_via_cups",
|
||||
) as mock_cups:
|
||||
mock_cups.return_value = USBResult(device="cups")
|
||||
result = query_usb_pjl()
|
||||
assert result.device == "cups"
|
||||
|
||||
@patch(f"{MOD}.os.access", return_value=False)
|
||||
@patch(f"{MOD}._init_usb_result")
|
||||
@patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0")
|
||||
def test_permission_denied(
|
||||
self,
|
||||
f: MagicMock,
|
||||
mock_init: MagicMock,
|
||||
a: MagicMock,
|
||||
) -> None:
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "Permission denied" in result.error
|
||||
|
||||
def test_silent_printer_is_reported_not_hidden(self) -> None:
|
||||
"""A printer that answers nothing must say so, not look healthy."""
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", return_value=10),
|
||||
patch(f"{MOD}._run_pjl_queries"),
|
||||
patch(f"{MOD}.os.close"),
|
||||
):
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "did not answer" in result.error
|
||||
|
||||
def test_busy_device_explains_why(self) -> None:
|
||||
"""EBUSY means CUPS holds the printer mid-job; say that."""
|
||||
exc = OSError("busy")
|
||||
exc.errno = errno.EBUSY
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", side_effect=exc),
|
||||
):
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "busy" in result.error.lower()
|
||||
|
||||
def test_eacces_suggests_sudo(self) -> None:
|
||||
exc = OSError("denied")
|
||||
exc.errno = errno.EACCES
|
||||
with (
|
||||
patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0"),
|
||||
patch(f"{MOD}._init_usb_result") as mock_init,
|
||||
patch(f"{MOD}.os.access", return_value=True),
|
||||
patch(f"{MOD}.os.open", side_effect=exc),
|
||||
):
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "sudo" in result.error
|
||||
|
||||
@patch(f"{MOD}.os.open", side_effect=OSError("no device"))
|
||||
@patch(f"{MOD}.os.access", return_value=True)
|
||||
@patch(f"{MOD}._init_usb_result")
|
||||
@patch(f"{MOD}.find_usb_printer_dev", return_value="/dev/usb/lp0")
|
||||
def test_oserror_fd_none(
|
||||
self,
|
||||
f: MagicMock,
|
||||
mock_init: MagicMock,
|
||||
a: MagicMock,
|
||||
o: MagicMock,
|
||||
) -> None:
|
||||
"""os.open raises OSError before fd is set -> fd stays None."""
|
||||
mock_init.return_value = USBResult(device="/dev/usb/lp0")
|
||||
result = query_usb_pjl()
|
||||
assert "no device" in result.error
|
||||
Loading…
Reference in New Issue
Block a user