From aa4259eacef691be7e977df5327c21f57486df35 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Fri, 13 Nov 2026 07:25:08 +0800 Subject: [PATCH] feat: verify a Thing Model through --report/--upload on a normal read The verify subcommand is gone (the tools have no subcommand tradition): --report FILE writes the verification report after a normal read switches to the verification semantics (each point once, read-only, no retries, bounded timeout). Bare --report asks interactively where to save (default report-.json), whether the values look right (judged as confirm-all or reject-all over the answered points) and whether to upload; --upload signs in inline with the browser flow when there is no session and prints a thank-you afterwards. --product is removed with report schema 4 (modpoll-wot 0.6.0a1): the receiving service resolves the product from the model fingerprint, which is identical for a TM, its TD exports and unmodified forks. --confirm/--reject/--yes are refused without --report/--upload. --- README.md | 23 ++++++----- docs/preview-notes.md | 9 ++-- docs/validation.rst | 19 +++++++++ modpoll/arg_parser.py | 25 ++++++----- modpoll/main.py | 85 +++++++++++++++++++++++++++++++------- modpoll/verification.py | 55 ++++++++---------------- pyproject.toml | 2 +- tests/test_cli_errors.py | 10 ++++- tests/test_login.py | 63 ++++++++++++++++------------ tests/test_verification.py | 79 +++++++++++++++++++---------------- uv.lock | 8 ++-- 11 files changed, 229 insertions(+), 149 deletions(-) diff --git a/README.md b/README.md index 3233785..9b0def8 100644 --- a/README.md +++ b/README.md @@ -105,15 +105,16 @@ meter (2026-10-28). See [validation](docs/validation.rst) for the evidence scope For a complete local simulator/MQTT demonstration, use the repository's [Docker Compose example](examples/README.md). -### Verify a Thing Model on a real device and write a report +### Read a device and write a verification report -`modpoll verify --config MODEL --tcp HOST` reads every point of a Thing Model once: read-only, without -retries and with a timeout of at most 10 seconds, so a lost request is a result and not something to repeat. -MODEL is a local TM/TD file, an http(s) URL or a `modiohub:@` Workspace reference. `--report -FILE` also writes the verification report (`-` prints it): +Adding `--report` to a normal read verifies the Thing Model on real hardware: every point is read once, +read-only, without retries and with a timeout of at most 10 seconds, so a lost request is a result and not +something to repeat. MODEL is a local TM/TD file, an http(s) URL or a `modiohub:@` Workspace +reference. `--report FILE` writes the verification report (`-` prints it); bare `--report` asks where to +save, whether the values look right, and whether to upload: ```sh -modpoll verify --config examples/modsim.tm.json --tcp 192.168.1.20 --unit-id 3 --product advantech/adam-5017uh --report report.json +modpoll --config examples/modsim.tm.json --tcp 192.168.1.20 --unit-id 3 --report report.json ``` The report records, per point, whether the read worked (`ok`, a Modbus `exception` with its code, @@ -122,8 +123,8 @@ The report records, per point, whether the read worked (`ok`, a Modbus `exceptio `unchecked`. The report holds no address, Unit ID, serial number or value; review it before sharing. It is checked with [modpoll-wot](https://github.com/top-maker/modpoll-wot) (`modpoll-wot validate-report report.json --model -model.tm.json`), and `--export` still writes the snapshot of the same read. With `-f` for a local Thing -Model, add `--product /`; the report then names the model as local. The exit +model.tm.json`), and `--export` still writes the snapshot of the same read. ModioHub resolves the product +from the model fingerprint, so you never name the product. The exit code is 1 unless every point was read. ### Sign in to ModioHub, read a Workspace Thing Model and upload the report @@ -137,11 +138,11 @@ revoke the session in your ModioHub settings to end it on the server. Once signed in, `--config modiohub:@` (the version is a number or `latest`) reads one of your custom Thing Models. A shared one needs no login. Verifying it names the Workspace model in the -report, and `modpoll verify --config ... --upload` shows the report and, after you confirm (or with `--yes`), -uploads it: +report, and `modpoll --config ... --upload` shows the report and, after you confirm (or with `--yes`), +uploads it; without a login the sign-in flow starts right there: ```sh -modpoll verify --config modiohub:k3x9f2m7q4a8n5bd@latest --tcp 192.168.1.20 --upload +modpoll --config modiohub:k3x9f2m7q4a8n5bd@latest --tcp 192.168.1.20 --upload ``` ### MQTT data and write behavior diff --git a/docs/preview-notes.md b/docs/preview-notes.md index 53a3087..d13ee70 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -2,13 +2,14 @@ Modpoll 2.0.0a7 pins modpoll-wot 0.5.0a1 and connects to ModioHub: -- `modpoll verify --config MODEL --tcp HOST` reads every point of a Thing Model once, read-only and without - retries, and reports which points could be read; `--report FILE` writes the verification report (schema 3), - which holds no address, Unit ID, serial number or value. +- `--report` on a normal read verifies a Thing Model on real hardware: every point read once, read-only and + without retries; the verification report (schema 4) holds no address, Unit ID, serial number or value, and + ModioHub resolves the product from the model fingerprint. - `modpoll login` signs in with your browser and `modpoll logout` forgets the login. The 7-day tool session is kept in `~/.config/modiohub/credentials.json` and is shared with modsim 2.0.0a9. - `--config modiohub:@` reads a custom Thing Model from your ModioHub Workspace, and - `modpoll verify --config ... --upload` shows the report and uploads it after you confirm. + `modpoll --config ... --upload` shows the report and uploads it after you confirm (the sign-in flow + starts inline when needed). ## Modpoll 2.0.0a6 preview diff --git a/docs/validation.rst b/docs/validation.rst index 0807e92..6f0e3c5 100644 --- a/docs/validation.rst +++ b/docs/validation.rst @@ -174,3 +174,22 @@ pointer to the command. After the change ``make check`` passed and the offline suite passed 235 tests with 58 integration tests deselected, including new refusal cases for the removed spellings and the verify subcommand reaching the transport check. + + +Interactive report and upload on a normal read +---------------------------------------------- + +On 2026-11-13 the ``verify`` subcommand was replaced by plain flags on the +normal read (maintainer decision: the tools have no subcommand tradition, and +verification is a by-product of reading a device). ``--report`` without FILE +asks where to save (default ``report-.json``), whether the values look +right (yes/no/not checked, judged as confirm-all or reject-all over the points +the device answered), and whether to upload; ``--upload`` signs in inline with +the browser flow when there is no session. ``--product`` is gone with schema 4 +(modpoll-wot 0.6.0a1): the receiving service resolves the product from the +model fingerprint. After the change ``make check`` passed and the offline +suite passed 238 tests with 58 integration tests deselected, including the +interactive save/judgment flow, the inline sign-in, and refusal cases for +``--confirm``/``--yes`` without ``--report``/``--upload``. End-to-end against a +local modsim: ``--config examples/modsim.tm.json --tcp ... --report -`` prints +a schema-4 report with all 37 points ``ok``. diff --git a/modpoll/arg_parser.py b/modpoll/arg_parser.py index 50ae3da..00b0277 100644 --- a/modpoll/arg_parser.py +++ b/modpoll/arg_parser.py @@ -38,17 +38,21 @@ def get_parser(): ) verification = parser.add_argument_group( "verification", - "modpoll verify --config MODEL --tcp HOST reads every point of one Thing " - "Model once, read-only and without retries, and reports which points " - "could be read", + "--report/--upload read every point of one Thing Model once, read-only " + "and without retries, and report which points could be read", ) verification.add_argument( "--report", + nargs="?", + const="", + default=None, metavar="FILE", help=( - "Write the verification report to FILE ('-' prints it). " - "It lists each point's result and carries no address, Unit ID, serial " - "number or value; review it before sharing." + "Read every point of the model once and write the verification " + "report to FILE ('-' prints it). Without FILE the save location, " + "your judgment of the values and the upload are asked " + "interactively. The report lists each point's result and carries " + "no address, Unit ID, serial number or value." ), ) verification.add_argument( @@ -56,18 +60,13 @@ def get_parser(): action="store_true", help=( "After the verification read, show the report and, once you confirm, " - "upload it to ModioHub (run modpoll login first)" + "upload it to ModioHub; signs you in with the browser when needed" ), ) verification.add_argument( "--yes", action="store_true", - help="Upload without asking for confirmation after the report is shown", - ) - verification.add_argument( - "--product", - metavar="MANUFACTURER/MODEL", - help="Catalog product ID the report is for; needed when the model does not name one", + help="Upload without being asked", ) verification.add_argument( "--confirm", diff --git a/modpoll/main.py b/modpoll/main.py index 4cc6f4d..41a9e28 100644 --- a/modpoll/main.py +++ b/modpoll/main.py @@ -3,6 +3,7 @@ import signal import sys import time +from datetime import datetime, timezone from modpoll_wot import AcquisitionError @@ -128,26 +129,82 @@ def process_mqtt_command(topic, payload, retained, topic_pattern, handlers): return success +def _ask(prompt): + return input(prompt).strip().lower() + + def _finish_full_read(args, handler): - """Summarize the full read and write its report; the result is whether every point was read.""" + """Summarize the verification read, save the report, and upload it when asked. + + On a terminal without --yes the save location, the judgment of the values + and the upload are asked interactively. The result is whether every point + was read. + """ try: report = verification.build_report(handler, args) - if args.report: - verification.write_report(report, args.report) except (ValueError, OSError, AcquisitionError) as exc: logger.error("%s", exc) logger.debug("Report error details", exc_info=True) return False print(f"\n{verification.summary(report)}", flush=True) + full = verification.is_full_read(report) + if sys.stdin.isatty() and not args.yes: + if not full and _ask( + "Not every point was read, so this report does not count as a " + "full read. Continue? [y/N] " + ) not in ("y", "yes"): + return False + verdict = _ask( + "Do the values in the table above look right? " + "[y]es, [n]o, [Enter] not checked: " + ) + if verdict in ("y", "yes", "n", "no"): + # Judge only the points the device actually answered. + judged = [ + point["property"] for point in report["points"] if point["read"] == "ok" + ] + if verdict in ("y", "yes"): + args.confirm = judged + else: + args.reject = judged + try: + report = verification.build_report(handler, args) + except (ValueError, OSError, AcquisitionError) as exc: + logger.error("%s", exc) + logger.debug("Report error details", exc_info=True) + return False + if args.report == "": + if not sys.stdin.isatty(): + logger.error("Add --report FILE when not running interactively.") + return False + default = f"report-{datetime.now(timezone.utc).date().isoformat()}.json" + args.report = input(f"Save the report to [{default}]: ").strip() or default + if args.report: + try: + verification.write_report(report, args.report) + except (ValueError, OSError) as exc: + logger.error("%s", exc) + logger.debug("Report write details", exc_info=True) + return False + if args.report != "-": + print( + f"Report written to {args.report}. It has no addresses, Unit IDs, " + "serial numbers or values; review it before sharing.", + flush=True, + ) if args.upload and not _upload(args, report): return False - if args.report and args.report != "-": - print( - f"Report written to {args.report}. It has no addresses, Unit IDs, serial " - "numbers or values; review it before sharing.", - flush=True, - ) - return verification.is_full_read(report) + return full + + +def _ensure_login(): + """A session for the upload; without one, sign in with the browser right here.""" + import modpoll_wot + + server = modpoll_wot.server_url() + if modpoll_wot.load_session(server) is None: + print(f"Sign in to {server} to upload.", flush=True) + login.login(server) def _upload(args, report): @@ -164,8 +221,9 @@ def _upload(args, report): print("Not uploaded.", flush=True) return False try: + _ensure_login() stored = verification.upload_report(report, timeout=args.timeout) - except ValueError as exc: + except (ValueError, login.LoginError, OSError) as exc: logger.error("%s", exc) return False print( @@ -177,6 +235,7 @@ def _upload(args, report): ), flush=True, ) + print("Thank you for verifying the Thing Model on real hardware.", flush=True) return True @@ -193,9 +252,6 @@ def setup_logging(level, format): def app(name="modpoll"): if sys.argv[1:2] in (["login"], ["logout"]): sys.exit(login.command(sys.argv[1:])) - verify_mode = sys.argv[1:2] == ["verify"] - if verify_mode: - sys.argv = [sys.argv[0], *sys.argv[2:]] mqtt_handler = None modbus_handlers = [] @@ -204,7 +260,6 @@ def app(name="modpoll"): # parse args args = get_parser().parse_args() - args.verify = verify_mode print( f"\nModpoll v{__version__} - A New Command-line Tool for Modbus and MQTT\n", diff --git a/modpoll/verification.py b/modpoll/verification.py index 86e59e0..eac5798 100644 --- a/modpoll/verification.py +++ b/modpoll/verification.py @@ -1,15 +1,16 @@ """Verification of a Thing Model against a real device and its report (POLL-02a). -``modpoll verify`` executes the whole ``modpoll:acquisition`` plan once: -read-only, no retries and a bounded timeout. The -result per point is recorded in a verification report whose format and validation belong to modpoll-wot. The report -holds no address, Unit ID, serial number or value; the user reviews it before anything leaves the machine. +With ``--report`` or ``--upload`` the read executes the whole +``modpoll:acquisition`` plan once: read-only, no retries and a bounded +timeout. The result per point is recorded in a verification report whose +format and validation belong to modpoll-wot. The report holds no address, +Unit ID, serial number or value; the receiving service resolves the catalog +product from the model fingerprint, so the user never names the product. """ import hashlib import json import os -import re import tempfile import uuid from datetime import datetime, timezone @@ -23,51 +24,31 @@ from .login import headers as api_headers MAX_TIMEOUT = 10.0 -_SLUG = r"[a-z0-9]+(?:-[a-z0-9]+)*" -_DEVICE = re.compile(rf"^({_SLUG}/{_SLUG})(?:@([A-Za-z0-9][A-Za-z0-9._/-]{{0,99}}))?$") def validate_args(args): """Reject option combinations a command cannot honour, before anything is connected.""" - verify_options = ("report", "upload", "yes", "confirm", "reject", "product") - if args.verify: - args.full_read = True - else: - args.full_read = False - if any(getattr(args, option) for option in verify_options): - raise ValueError( - "Verification options belong to the verify command; for example: " - "modpoll verify --config model.tm.json --tcp HOST --upload" - ) + args.full_read = args.report is not None or args.upload + if args.yes and not args.upload: + raise ValueError("--yes needs --upload") + if (args.confirm or args.reject) and not args.full_read: + raise ValueError("--confirm and --reject need --report or --upload") sources = list(args.config or []) if not sources: raise ValueError("One of --config/-f is required") if not args.full_read: return if args.mqtt_host: - raise ValueError("modpoll verify does not publish to MQTT") + raise ValueError("A verification report is not published to MQTT") if args.udp: - raise ValueError("modpoll verify supports Modbus TCP and RTU, not UDP") + raise ValueError("A verification report supports Modbus TCP and RTU, not UDP") if args.serial and args.framer == "ascii": - raise ValueError("modpoll verify supports Modbus RTU, not Modbus ASCII") + raise ValueError("A verification report supports Modbus RTU, not Modbus ASCII") if len(sources) != 1: - raise ValueError("modpoll verify reads one Thing Model") - workspace = any( - location.startswith(modpoll_wot.REFERENCE_PREFIX) - for location in args.config or [] - ) - if (args.report or args.upload) and not (args.product or workspace): - raise ValueError( - "modpoll verify --report needs --product / " - "when the model does not name one" - ) - if args.yes and not args.upload: - raise ValueError("--yes needs --upload") - if args.product and not _DEVICE.match(args.product): - raise ValueError("--product must be /") + raise ValueError("A verification report reads one Thing Model") if args.timeout > MAX_TIMEOUT: raise ValueError( - f"--timeout is at most {MAX_TIMEOUT:g} seconds in a verification" + f"--timeout is at most {MAX_TIMEOUT:g} seconds for a verification report" ) args.once = True args.daemon = False @@ -85,7 +66,6 @@ def resolve_models(args): payload, details = fetch_workspace_model(location, timeout=args.timeout) args.model_payloads[location] = payload if args.full_read: - args.product = args.product or details["product"] args.model_source = {"source": "workspace", "ref": details["ref"]} @@ -230,8 +210,7 @@ def build_report(handler, args): point["expected"] = judged.get(name, "unchecked") if read_ok else "unchecked" points.append(point) report = { - "reportVersion": 3, - "product": args.product, + "reportVersion": 4, "model": { "sha256": hashlib.sha256(payload).hexdigest(), "fingerprint": modpoll_wot.model_fingerprint(payload), diff --git a/pyproject.toml b/pyproject.toml index adda1fd..14d4270 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ dependencies = [ "paho-mqtt>=2.1.0,<3.0.0", "prettytable>=3.9.0,<4.0.0", "requests>=2.32.5,<3.0.0", - "modpoll-wot==0.5.0a1", + "modpoll-wot==0.6.0a1", ] [project.optional-dependencies] diff --git a/tests/test_cli_errors.py b/tests/test_cli_errors.py index 463e740..9cefa78 100644 --- a/tests/test_cli_errors.py +++ b/tests/test_cli_errors.py @@ -75,12 +75,18 @@ def test_removed_flags_are_rejected(): assert "unrecognized arguments" in result.stderr + result.stdout -def test_verify_command_reaches_the_transport_check(): - result = run("verify", "--config", "examples/modsim.tm.json", "--once") +def test_report_flag_reaches_the_transport_check(): + result = run("--config", "examples/modsim.tm.json", "--report", "-", "--once") assert result.returncode == 2 assert "No communication method specified" in result.stderr + result.stdout +def test_confirm_without_report_is_refused(): + result = run("--config", "examples/modsim.tm.json", "--confirm", "all", "--once") + assert result.returncode == 2 + assert "need --report or --upload" in result.stderr + result.stdout + + def test_csv_rejects_typed_parameters(): result = run( "--config", diff --git a/tests/test_login.py b/tests/test_login.py index fcd0dff..e5d5cc5 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -14,7 +14,6 @@ from .test_verification import ( # noqa: F401 (the fixture clears the process-wide stop event) FakeClient, - PRODUCT, fresh_stop_event, run_app, three_group_model, @@ -22,6 +21,7 @@ SERVER = "https://hub.test" ID = "k3x9f2m7q4a8n5bd" +PRODUCT = "acme/meter" @pytest.fixture(autouse=True) @@ -231,7 +231,6 @@ def test_full_read_of_a_workspace_model_names_the_workspace_as_its_source( run_app( monkeypatch, [ - "verify", "--config", f"modiohub:{ID}@2", "--tcp", @@ -242,7 +241,7 @@ def test_full_read_of_a_workspace_model_names_the_workspace_as_its_source( FakeClient(), ) report = json.loads(report_path.read_text()) - assert report["product"] == PRODUCT + assert "product" not in report assert ( report["model"]["source"] == "workspace" and report["model"]["ref"] == f"{ID}@2" ) @@ -265,24 +264,15 @@ def post(url, json=None, headers=None, timeout=None): monkeypatch.setattr(verification.requests, "post", post) run_app( monkeypatch, - [ - "verify", - "-f", - str(path), - "--tcp", - "x", - "--product", - PRODUCT, - "--upload", - "--yes", - ], + ["-f", str(path), "--tcp", "x", "--upload", "--yes"], FakeClient(False, False), ) out = capsys.readouterr().out assert "Report to upload:" in out and "Uploaded. This is a full read" in out assert ( - sent["url"] == f"{SERVER}/api/v1/reports" and sent["body"]["reportVersion"] == 3 + sent["url"] == f"{SERVER}/api/v1/reports" and sent["body"]["reportVersion"] == 4 ) + assert "product" not in sent["body"] assert ( sent["headers"]["Authorization"] == "Bearer tok" and sent["headers"]["Idempotency-Key"] @@ -298,16 +288,7 @@ def test_upload_asks_first_and_needs_a_login(monkeypatch, tmp_path, capsys): "post", lambda *args, **kwargs: posted.append(args) or Reply(201, {"fullRead": True}), ) - arguments = [ - "verify", - "-f", - str(path), - "--tcp", - "x", - "--product", - PRODUCT, - "--upload", - ] + arguments = ["-f", str(path), "--tcp", "x", "--upload"] # Not a terminal and no --yes: nothing is sent. with pytest.raises(SystemExit) as exit_info: run_app(monkeypatch, arguments, FakeClient(False, False)) @@ -319,9 +300,14 @@ def test_upload_asks_first_and_needs_a_login(monkeypatch, tmp_path, capsys): with pytest.raises(SystemExit): run_app(monkeypatch, arguments, FakeClient(False, False)) assert "Not uploaded." in capsys.readouterr().out and not posted - # Agreeing without a login. + # Agreeing without a login starts the sign-in flow; when it fails, nothing is sent. utils._thread_event.clear() monkeypatch.setattr("builtins.input", lambda prompt: "y") + monkeypatch.setattr( + login, + "login", + lambda *a, **k: (_ for _ in ()).throw(login.LoginError("no browser here")), + ) with pytest.raises(SystemExit): run_app(monkeypatch, arguments, FakeClient(False, False)) assert not posted @@ -339,3 +325,28 @@ def test_a_refused_upload_reports_why(monkeypatch): monkeypatch.setattr(verification.requests, "post", lambda *a, **k: Reply(401, {})) with pytest.raises(ValueError, match="modpoll login"): verification.upload_report({}, timeout=3) + + +def test_upload_signs_in_inline_when_there_is_no_session(monkeypatch, tmp_path, capsys): + """--upload without a login starts the browser flow and continues with the session.""" + path = tmp_path / "meter.tm.json" + path.write_text(json.dumps(three_group_model())) + posted = [] + monkeypatch.setattr( + verification.requests, + "post", + lambda *args, **kwargs: posted.append(args) or Reply(201, {"fullRead": True}), + ) + + def fake_login(server, **kwargs): + modpoll_wot.save_session(server, "tok", expires_in=3600) + return modpoll_wot.load_session(server) + + monkeypatch.setattr(login, "login", fake_login) + run_app( + monkeypatch, + ["-f", str(path), "--tcp", "x", "--upload", "--yes"], + FakeClient(False, False), + ) + assert posted + assert "Sign in to" in capsys.readouterr().out diff --git a/tests/test_verification.py b/tests/test_verification.py index 42328f0..6832616 100644 --- a/tests/test_verification.py +++ b/tests/test_verification.py @@ -21,9 +21,6 @@ def fresh_stop_event(): utils._thread_event.clear() -PRODUCT = "acme/meter" - - def three_group_model(): """Points `ok1` and `ok2` in one group, `refused` and `silent` each in their own.""" model = meter_model("meter") @@ -89,9 +86,7 @@ def read_holding_registers(self, address, count, device_id): def run_app(monkeypatch, argv, client): monkeypatch.setattr(modbus_task, "_create_modbus_client", lambda args: client) - # The verify subcommand must be argv[1], as on a real command line. - head, rest = (argv[:1], argv[1:]) if argv[:1] == ["verify"] else ([], argv) - monkeypatch.setattr(sys, "argv", ["modpoll", *head, "--interval", "0", *rest]) + monkeypatch.setattr(sys, "argv", ["modpoll", "--interval", "0", *argv]) monkeypatch.setattr(main, "logger", None) main.app() @@ -110,7 +105,6 @@ def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, c run_app( monkeypatch, [ - "verify", "-f", str(path), "--tcp", @@ -119,8 +113,6 @@ def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, c "7", "--report", str(report_path), - "--product", - PRODUCT, "--confirm", "ok1", "--reject", @@ -140,7 +132,7 @@ def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, c ("silent", "no-response", None, "unchecked"), ] assert report["model"]["source"] == "local" and "ref" not in report["model"] - assert report["product"] == PRODUCT and report["transport"] == "tcp" + assert "product" not in report and report["transport"] == "tcp" assert "environment" not in report assert report["tool"]["name"] == "modpoll" modpoll_wot.validate_report(report, model=path.read_bytes()) @@ -161,15 +153,12 @@ def test_full_read_of_a_healthy_device_succeeds_and_exports_a_snapshot( run_app( monkeypatch, [ - "verify", "-f", str(path), "--tcp", "192.0.2.10", "--report", str(report_path), - "--product", - PRODUCT, "--export", str(snapshot), "--confirm", @@ -189,20 +178,17 @@ def test_report_goes_to_standard_output_with_dash(monkeypatch, tmp_path, capsys) run_app( monkeypatch, [ - "verify", "-f", str(path), "--tcp", "x", "--report", "-", - "--product", - PRODUCT, ], FakeClient(False, False), ) out = capsys.readouterr().out - assert json.loads(out[out.index("{") : out.rindex("}") + 1])["reportVersion"] == 3 + assert json.loads(out[out.index("{") : out.rindex("}") + 1])["reportVersion"] == 4 def test_a_point_that_was_not_read_cannot_be_judged(monkeypatch, tmp_path): @@ -211,15 +197,12 @@ def test_a_point_that_was_not_read_cannot_be_judged(monkeypatch, tmp_path): run_app( monkeypatch, [ - "verify", "-f", str(path), "--tcp", "x", "--report", str(tmp_path / "r.json"), - "--product", - PRODUCT, "--confirm", "refused", ], @@ -233,30 +216,26 @@ def test_a_point_that_was_not_read_cannot_be_judged(monkeypatch, tmp_path): "argv, message", [ ([], "One of --config/-f is required"), - ( - ["-f", "x.json", "--report", "r.json", "--tcp", "x"], - "belong to the verify command", - ), ( ["-f", "x.json", "--confirm", "all", "--tcp", "x"], - "belong to the verify command", - ), - ( - ["verify", "-f", "x.json", "--tcp", "x", "--report", "r.json"], - "needs --product", + "need --report or --upload", ), + (["-f", "x.json", "--tcp", "x", "--yes"], "--yes needs --upload"), ( - ["verify", "-f", "x.json", "--tcp", "x", "--timeout", "30"], + ["-f", "x.json", "--report", "r.json", "--tcp", "x", "--timeout", "30"], "at most 10", ), - (["verify", "-f", "x.json", "--udp", "x"], "not UDP"), + (["-f", "x.json", "--report", "r.json", "--udp", "x"], "not UDP"), ( - ["verify", "-f", "x.json", "--rtu", "p", "--framer", "ascii"], + ["-f", "x.json", "--report", "r.json", "--rtu", "p", "--framer", "ascii"], "not Modbus ASCII", ), - (["verify", "-f", "x.json", "--tcp", "x", "--mqtt-host", "h"], "MQTT"), ( - ["verify", "-f", "a.json", "b.json", "--tcp", "x"], + ["-f", "x.json", "--report", "r.json", "--tcp", "x", "--mqtt-host", "h"], + "not published to MQTT", + ), + ( + ["-f", "a.json", "b.json", "--report", "r.json", "--tcp", "x"], "reads one Thing Model", ), ], @@ -270,9 +249,39 @@ def test_option_combinations_are_refused(argv, message, monkeypatch, caplog): assert message in caplog.text -def test_verify_asks_each_group_once(): +def test_a_report_read_asks_each_group_once(): args = get_parser().parse_args(["-f", "x", "--tcp", "h"]) args.full_read = True assert modbus_task._read_options(args) == {"retries": 0} args.full_read = False assert modbus_task._read_options(args) == {} + + +def test_bare_report_interactively_saves_and_judges(monkeypatch, tmp_path, capsys): + """--report without FILE asks where to save and whether the values look right.""" + path = write_model(tmp_path, three_group_model()) + monkeypatch.chdir(tmp_path) + answers = iter(["y", ""]) # values look right; save to the default name + monkeypatch.setattr(sys.stdin, "isatty", lambda: True) + monkeypatch.setattr("builtins.input", lambda prompt: next(answers)) + run_app( + monkeypatch, + ["-f", str(path), "--tcp", "192.0.2.10", "--report"], + FakeClient(False, False), + ) + (saved,) = tmp_path.glob("report-*.json") + report = json.loads(saved.read_text()) + assert {p["expected"] for p in report["points"]} == {"confirmed"} + assert "product" not in report + + +def test_bare_report_without_a_terminal_names_a_file(monkeypatch, tmp_path, caplog): + path = write_model(tmp_path, three_group_model()) + with pytest.raises(SystemExit) as exit_info: + run_app( + monkeypatch, + ["-f", str(path), "--tcp", "x", "--report"], + FakeClient(False, False), + ) + assert exit_info.value.code == 1 + assert "Add --report FILE" in caplog.text diff --git a/uv.lock b/uv.lock index 5c002bb..80c1854 100644 --- a/uv.lock +++ b/uv.lock @@ -717,7 +717,7 @@ docs = [ [package.metadata] requires-dist = [ - { name = "modpoll-wot", specifier = "==0.5.0a1" }, + { name = "modpoll-wot", specifier = "==0.6.0a1" }, { name = "paho-mqtt", specifier = ">=2.1.0,<3.0.0" }, { name = "prettytable", specifier = ">=3.9.0,<4.0.0" }, { name = "pymodbus", specifier = "~=3.16.1" }, @@ -745,15 +745,15 @@ docs = [ [[package]] name = "modpoll-wot" -version = "0.5.0a1" +version = "0.6.0a1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" }, { name = "referencing", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2b/a4/477adeef74d9b4ce969ab377e9d00c90c115ab006aea6bb15dd3dd4c3176/modpoll_wot-0.5.0a1.tar.gz", hash = "sha256:c510a352bedf2c01a8d42abf21b394cacab208e46277c82e4531ea3799195cb1", size = 59242, upload-time = "2026-11-12T12:24:59.788Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4c/e2/a6e59b2c0842771a4acf02fea71d4e1fb5400683402fae7bb1baf71dc699/modpoll_wot-0.6.0a1.tar.gz", hash = "sha256:ad37696d3b665188d8562a24b0b73167ea9965dedf832c0735932590586d4cb3", size = 60153, upload-time = "2026-11-12T23:09:10.321Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/89/3a/a24f047c949d4b866ea0f511a2d1f7f1c15bbb13249755dfcfb0bdf8e3f3/modpoll_wot-0.5.0a1-py3-none-any.whl", hash = "sha256:59dcd551d95ebd549de3e3e04170d7dec2fe8ea58e643e2b6d5ab6d91b0acb21", size = 50246, upload-time = "2026-11-12T12:24:58.568Z" }, + { url = "https://files.pythonhosted.org/packages/d6/25/1781ae245ae3e8323d07e4d908c965276de61f06216b2e86eaf42d175aca/modpoll_wot-0.6.0a1-py3-none-any.whl", hash = "sha256:e1e7f5cb12a2bb102cedb96205db8415bc2b95fb5955b4195a73a86ce0e52ac2", size = 51938, upload-time = "2026-11-12T23:09:09.4Z" }, ] [[package]]