diff --git a/README.md b/README.md index d458386..3233785 100644 --- a/README.md +++ b/README.md @@ -105,23 +105,21 @@ 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). -### Read a catalog product and write a verification report +### Verify a Thing Model on a real device and write a report -`--device /[@]` reads the baseline Thing Model of a product in the -[Open Modbus Catalog](https://github.com/top-maker/open-modbus-catalog) instead of a file. A branch or tag -(default `main`) is resolved to its commit, and the download is checked against the Git object id GitHub -reports for it. `--full-read` reads every point 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. `--report FILE` also writes the -verification report (`-` prints it): +`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): ```sh -modpoll --device advantech/adam-5017uh --tcp 192.168.1.20 --unit-id 3 --report report.json +modpoll verify --config examples/modsim.tm.json --tcp 192.168.1.20 --unit-id 3 --product advantech/adam-5017uh --report report.json ``` The report records, per point, whether the read worked (`ok`, a Modbus `exception` with its code, `no-response`, or `not-tested` when the answer could not be decoded) and your judgment of the value: `--confirm POINT...` (or `all`) and `--reject POINT...` for values you compared with the device, otherwise -`unchecked`. `--chassis`, `--firmware` and `--configuration` add context. The report holds no address, Unit +`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 @@ -138,11 +136,12 @@ signing in with either tool signs in both. `MODIOHUB_TOKEN` in the environment r 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. A full read of it writes a report that names the -Workspace model, and `--upload` shows the report and, after you confirm (or with `--yes`), uploads it: +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: ```sh -modpoll --config modiohub:k3x9f2m7q4a8n5bd@latest --tcp 192.168.1.20 --upload +modpoll verify --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 7d8637e..53a3087 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -2,13 +2,13 @@ Modpoll 2.0.0a7 pins modpoll-wot 0.5.0a1 and connects to ModioHub: -- `--device /[@commit]` reads the baseline Thing Model of a catalog product. -- `--full-read` reads every point once, read-only and without retries; `--report FILE` writes the - verification report (schema 3), which holds no address, Unit ID, serial number or value. +- `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. - `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 `--upload` shows - the report of a full read and uploads it after you confirm. +- `--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 2.0.0a6 preview diff --git a/docs/validation.rst b/docs/validation.rst index 5d332b2..0807e92 100644 --- a/docs/validation.rst +++ b/docs/validation.rst @@ -157,3 +157,20 @@ examples/modsim.csv`` and ``--config examples/modsim.tm.json`` exited 0 and exported byte-identical snapshots of all 37 points; the CSV and TM poller structures (four blocks, start addresses, quantities, endianness) match exactly. ``--precision`` stays in the default ``auto`` rendering mode. + + +Verification command consolidation +---------------------------------- + +On 2026-11-12 the full-read flags became the ``modpoll verify`` subcommand and +the catalog fetch was removed (maintainer decision, after the 2.0.0a7 +preview): ``modpoll verify --config MODEL --tcp HOST [--report FILE] +[--upload]`` replaces ``--full-read``/``--report``/``--upload`` at the top +level; ``--device`` is gone because ``--config`` already covers local files, +URLs and ``modiohub:`` Workspace references; ``--chassis``/``--firmware``/ +``--configuration`` are gone because the report schema treats the environment +as optional. Verification options used without ``verify`` exit 2 with a +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. diff --git a/modpoll/arg_parser.py b/modpoll/arg_parser.py index d8aede5..50ae3da 100644 --- a/modpoll/arg_parser.py +++ b/modpoll/arg_parser.py @@ -36,70 +36,47 @@ def get_parser(): ), nargs="+", ) - parser.add_argument( - "--device", - metavar="MANUFACTURER/MODEL[@COMMIT]", - help=( - "Read the baseline Thing Model of a product in the Open Modbus Catalog, " - "for example advantech/adam-5017uh, at a commit, tag or branch " - "(default: main). Use instead of -f." - ), + 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", ) - parser.add_argument( - "--full-read", - action="store_true", - help=( - "Read every point of the model once, read-only and without retries, " - "and report which points could be read. Implies --once." - ), - ) - parser.add_argument( + verification.add_argument( "--report", metavar="FILE", help=( - "Write the verification report of a full read to FILE ('-' prints it). " + "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. Implies --full-read." + "number or value; review it before sharing." ), ) - parser.add_argument( + verification.add_argument( "--upload", action="store_true", help=( - "After a full read, show the report and, once you confirm, upload it to " - "ModioHub (run modpoll login first). Implies --full-read." + "After the verification read, show the report and, once you confirm, " + "upload it to ModioHub (run modpoll login first)" ), ) - parser.add_argument( + verification.add_argument( "--yes", action="store_true", help="Upload without asking for confirmation after the report is shown", ) - parser.add_argument( + verification.add_argument( "--product", metavar="MANUFACTURER/MODEL", - help="Catalog product ID the report is for; needed with -f, taken from --device otherwise", - ) - parser.add_argument( - "--chassis", - metavar="MANUFACTURER/MODEL", - help="Chassis product ID, for the report", - ) - parser.add_argument( - "--firmware", help="Firmware version of the device, for the report" - ) - parser.add_argument( - "--configuration", - help="Short note on the device configuration, such as an input range, for the report", + help="Catalog product ID the report is for; needed when the model does not name one", ) - parser.add_argument( + verification.add_argument( "--confirm", nargs="+", default=[], metavar="POINT", help="Points whose values you checked and found right ('all' for every point), for the report", ) - parser.add_argument( + verification.add_argument( "--reject", nargs="+", default=[], diff --git a/modpoll/main.py b/modpoll/main.py index 6a57123..4cc6f4d 100644 --- a/modpoll/main.py +++ b/modpoll/main.py @@ -193,6 +193,9 @@ 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 = [] @@ -201,6 +204,7 @@ 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 19b7719..86e59e0 100644 --- a/modpoll/verification.py +++ b/modpoll/verification.py @@ -1,11 +1,11 @@ -"""Full read of a Thing Model on a real device and its verification report (POLL-02a). +"""Verification of a Thing Model against a real device and its report (POLL-02a). -A full read executes the whole ``modpoll:acquisition`` plan once: read-only, no retries and a bounded timeout. The +``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. """ -import base64 import hashlib import json import os @@ -22,151 +22,64 @@ from . import __version__ from .login import headers as api_headers -CATALOG_API = "https://api.github.com/repos/top-maker/open-modbus-catalog" 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}}))?$") -_COMMIT = re.compile(r"^[0-9a-f]{40}$") - - -def parse_device(text): - """``manufacturer/model-number[@ref]`` as (product ID, ref); the ref is a commit, tag or branch.""" - match = _DEVICE.match(text) - if not match: - raise ValueError( - "--device must be /, optionally followed by @" - ) - return match.group(1), match.group(2) or "main" def validate_args(args): - """Reject option combinations a full read cannot honour, before anything is connected.""" - args.full_read = args.full_read or bool(args.report) or args.upload + """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" + ) sources = list(args.config or []) - if args.device and sources: - raise ValueError("Use either --device or a configuration source, not both") - if not args.device and not sources: - raise ValueError("One of --config/-f or --device is required") - if args.device: - parse_device(args.device) + if not sources: + raise ValueError("One of --config/-f is required") if not args.full_read: - for option in ("confirm", "reject", "chassis", "firmware", "configuration"): - if getattr(args, option): - raise ValueError(f"--{option} needs --full-read or --report") return if args.mqtt_host: - raise ValueError("A full read does not publish to MQTT") + raise ValueError("modpoll verify does not publish to MQTT") if args.udp: - raise ValueError("A full read supports Modbus TCP and RTU, not UDP") + raise ValueError("modpoll verify supports Modbus TCP and RTU, not UDP") if args.serial and args.framer == "ascii": - raise ValueError("A full read supports Modbus RTU, not Modbus ASCII") - if args.device is None and len(sources) != 1: - raise ValueError("A full read reads one Thing Model") + raise ValueError("modpoll verify 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.device or args.product or workspace): + if (args.report or args.upload) and not (args.product or workspace): raise ValueError( - "--report with -f needs --product /" + "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 /") if args.timeout > MAX_TIMEOUT: - raise ValueError(f"--timeout is at most {MAX_TIMEOUT:g} seconds in a full read") - if args.chassis and not _DEVICE.match(args.chassis): - raise ValueError("--chassis must be /") - args.once = True - args.daemon = False - - -def git_blob_sha1(payload): - """The id Git gives a file, so a download can be checked against the catalog repository.""" - return hashlib.sha1(b"blob %d\0" % len(payload) + payload).hexdigest() - - -def _github(path, *, timeout, **kwargs): - headers = {"User-Agent": f"modpoll/{__version__}", **kwargs.pop("headers", {})} - try: - response = requests.get( - f"{CATALOG_API}/{path}", headers=headers, timeout=timeout, **kwargs - ) - except requests.RequestException as exc: - raise ValueError(f"Could not reach the catalog on GitHub: {exc}") from exc - return response - - -def fetch_catalog_model(product, ref, *, timeout): - """The baseline Thing Model of a catalog product at a commit: (bytes, 40-character commit). - - A branch or tag is resolved to its commit first, so a report names the exact version that was read. The file - is checked against the Git blob id GitHub reports for it. - """ - commit = ref - if not _COMMIT.match(ref): - response = _github( - f"commits/{requests.utils.quote(ref, safe='')}", - timeout=timeout, - headers={"Accept": "application/vnd.github.sha"}, - ) - if response.status_code in (404, 422): - raise ValueError(f"The catalog has no commit, tag or branch {ref}") - _check_github(response) - commit = response.text.strip() - if not _COMMIT.match(commit): - raise ValueError("GitHub answered with an unexpected commit id") - response = _github( - f"contents/products/{product}/model.tm.json", - timeout=timeout, - params={"ref": commit}, - ) - if response.status_code == 404: - raise ValueError( - f"The catalog has no Thing Model for {product} at {commit[:7]}" - ) - _check_github(response) - entry = response.json() - if entry.get("encoding") != "base64" or "content" not in entry: - raise ValueError( - f"The catalog's Thing Model for {product} is too large to fetch" - ) - payload = base64.b64decode(entry["content"]) - if git_blob_sha1(payload) != entry.get("sha"): raise ValueError( - f"The Thing Model for {product} does not match its Git object id" + f"--timeout is at most {MAX_TIMEOUT:g} seconds in a verification" ) - return payload, commit - - -def _check_github(response): - if ( - response.status_code == 403 - and response.headers.get("X-RateLimit-Remaining") == "0" - ): - raise ValueError( - "GitHub's anonymous request limit is used up; retry in an hour or use -f" - ) - if not response.ok: - raise ValueError(f"GitHub answered {response.status_code}") + args.once = True + args.daemon = False def resolve_models(args): - """Fetch the models that are not files: a catalog product (``--device``) or Workspace Thing Models. + """Fetch the Workspace Thing Models that are not files. - The bytes go to ``args.model_payloads`` for the handlers, and where a full-read model came from to - ``args.model_source`` for the report. + The bytes go to ``args.model_payloads`` for the handlers, and where a + verification model came from to ``args.model_source`` for the report. """ args.model_payloads = {} - if args.device: - product, ref = parse_device(args.device) - payload, commit = fetch_catalog_model(product, ref, timeout=args.timeout) - label = f"{product}@{commit[:7]}" - args.config = [label] - args.product = product - args.model_payloads[label] = payload - args.model_source = {"source": "catalog", "ref": commit} for location in args.config or []: if location.startswith(modpoll_wot.REFERENCE_PREFIX): payload, details = fetch_workspace_model(location, timeout=args.timeout) @@ -316,15 +229,6 @@ def build_report(handler, args): ) point["expected"] = judged.get(name, "unchecked") if read_ok else "unchecked" points.append(point) - environment = { - key: value - for key, value in ( - ("chassis", args.chassis), - ("firmware", args.firmware), - ("configuration", args.configuration), - ) - if value - } report = { "reportVersion": 3, "product": args.product, @@ -340,7 +244,6 @@ def build_report(handler, args): }, "transport": _transport(args), "date": datetime.now(timezone.utc).date().isoformat(), - **({"environment": environment} if environment else {}), "points": points, } modpoll_wot.validate_report(report, model=payload) diff --git a/tests/test_cli_errors.py b/tests/test_cli_errors.py index 6a30b60..463e740 100644 --- a/tests/test_cli_errors.py +++ b/tests/test_cli_errors.py @@ -36,9 +36,7 @@ def test_configuration_errors_exit_2_without_a_traceback(args, message): def test_missing_configuration_exits_2(): result = run("--once") assert result.returncode == 2 - assert "One of --config/-f or --device is required" in ( - result.stderr + result.stdout - ) + assert "One of --config/-f is required" in (result.stderr + result.stdout) assert "Traceback" not in result.stderr + result.stdout @@ -60,13 +58,29 @@ def test_config_accepts_csv_tm_and_td_by_content_detection(): assert message in output, output -def test_removed_flag_aliases_are_rejected(): - for flag in ("--tm", "--thing-model", "--thing-description", "--td"): +def test_removed_flags_are_rejected(): + for flag in ( + "--tm", + "--thing-model", + "--thing-description", + "--td", + "--device", + "--full-read", + "--chassis", + "--firmware", + "--configuration", + ): result = run(flag, "examples/modsim.tm.json", "--once") assert result.returncode == 2, flag 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") + assert result.returncode == 2 + assert "No communication method specified" 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 96448f4..fcd0dff 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -231,6 +231,7 @@ def test_full_read_of_a_workspace_model_names_the_workspace_as_its_source( run_app( monkeypatch, [ + "verify", "--config", f"modiohub:{ID}@2", "--tcp", @@ -264,7 +265,17 @@ def post(url, json=None, headers=None, timeout=None): monkeypatch.setattr(verification.requests, "post", post) run_app( monkeypatch, - ["-f", str(path), "--tcp", "x", "--product", PRODUCT, "--upload", "--yes"], + [ + "verify", + "-f", + str(path), + "--tcp", + "x", + "--product", + PRODUCT, + "--upload", + "--yes", + ], FakeClient(False, False), ) out = capsys.readouterr().out @@ -287,7 +298,16 @@ 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 = ["-f", str(path), "--tcp", "x", "--product", PRODUCT, "--upload"] + arguments = [ + "verify", + "-f", + str(path), + "--tcp", + "x", + "--product", + PRODUCT, + "--upload", + ] # Not a terminal and no --yes: nothing is sent. with pytest.raises(SystemExit) as exit_info: run_app(monkeypatch, arguments, FakeClient(False, False)) diff --git a/tests/test_verification.py b/tests/test_verification.py index e01625f..42328f0 100644 --- a/tests/test_verification.py +++ b/tests/test_verification.py @@ -1,11 +1,7 @@ -"""Full read and verification report (POLL-02a): per-group outcomes, report content, catalog fetch and options.""" +"""Verification read and report (POLL-02a): per-group outcomes, report content and options.""" -import base64 -import hashlib import json import sys -from argparse import Namespace - import modpoll_wot import pytest from pymodbus.exceptions import ModbusIOException @@ -26,7 +22,6 @@ def fresh_stop_event(): PRODUCT = "acme/meter" -COMMIT = "0123456789abcdef0123456789abcdef01234567" def three_group_model(): @@ -94,7 +89,9 @@ 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) - monkeypatch.setattr(sys, "argv", ["modpoll", "--interval", "0", *argv]) + # 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(main, "logger", None) main.app() @@ -113,6 +110,7 @@ def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, c run_app( monkeypatch, [ + "verify", "-f", str(path), "--tcp", @@ -127,10 +125,6 @@ def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, c "ok1", "--reject", "ok2", - "--firmware", - "1.2", - "--configuration", - "range 0-10 V", ], client, ) @@ -147,7 +141,7 @@ def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, c ] assert report["model"]["source"] == "local" and "ref" not in report["model"] assert report["product"] == PRODUCT and report["transport"] == "tcp" - assert report["environment"] == {"firmware": "1.2", "configuration": "range 0-10 V"} + assert "environment" not in report assert report["tool"]["name"] == "modpoll" modpoll_wot.validate_report(report, model=path.read_bytes()) # Nothing that identifies the device or what it answered is in the file. @@ -167,6 +161,7 @@ def test_full_read_of_a_healthy_device_succeeds_and_exports_a_snapshot( run_app( monkeypatch, [ + "verify", "-f", str(path), "--tcp", @@ -193,7 +188,17 @@ def test_report_goes_to_standard_output_with_dash(monkeypatch, tmp_path, capsys) path = write_model(tmp_path, three_group_model()) run_app( monkeypatch, - ["-f", str(path), "--tcp", "x", "--report", "-", "--product", PRODUCT], + [ + "verify", + "-f", + str(path), + "--tcp", + "x", + "--report", + "-", + "--product", + PRODUCT, + ], FakeClient(False, False), ) out = capsys.readouterr().out @@ -206,6 +211,7 @@ def test_a_point_that_was_not_read_cannot_be_judged(monkeypatch, tmp_path): run_app( monkeypatch, [ + "verify", "-f", str(path), "--tcp", @@ -226,27 +232,33 @@ def test_a_point_that_was_not_read_cannot_be_judged(monkeypatch, tmp_path): @pytest.mark.parametrize( "argv, message", [ + ([], "One of --config/-f is required"), ( - ["--device", PRODUCT, "-f", "x.json"], - "either --device or a configuration source", + ["-f", "x.json", "--report", "r.json", "--tcp", "x"], + "belong to the verify command", ), ( - [], - "One of --config/-f or --device is required", + ["-f", "x.json", "--confirm", "all", "--tcp", "x"], + "belong to the verify command", ), - (["--device", "Bad/Id"], "--device must be"), - (["-f", "x.json", "--report", "r.json", "--tcp", "x"], "needs --product"), ( - ["-f", "x.json", "--full-read", "--tcp", "x", "--timeout", "30"], + ["verify", "-f", "x.json", "--tcp", "x", "--report", "r.json"], + "needs --product", + ), + ( + ["verify", "-f", "x.json", "--tcp", "x", "--timeout", "30"], "at most 10", ), - (["-f", "x.json", "--full-read", "--udp", "x"], "not UDP"), + (["verify", "-f", "x.json", "--udp", "x"], "not UDP"), ( - ["-f", "x.json", "--full-read", "--rtu", "p", "--framer", "ascii"], + ["verify", "-f", "x.json", "--rtu", "p", "--framer", "ascii"], "not Modbus ASCII", ), - (["-f", "x.json", "--full-read", "--tcp", "x", "--mqtt-host", "h"], "MQTT"), - (["-f", "x.json", "--confirm", "all", "--tcp", "x"], "needs --full-read"), + (["verify", "-f", "x.json", "--tcp", "x", "--mqtt-host", "h"], "MQTT"), + ( + ["verify", "-f", "a.json", "b.json", "--tcp", "x"], + "reads one Thing Model", + ), ], ) def test_option_combinations_are_refused(argv, message, monkeypatch, caplog): @@ -258,95 +270,9 @@ def test_option_combinations_are_refused(argv, message, monkeypatch, caplog): assert message in caplog.text -def test_full_read_asks_each_group_once(): - args = get_parser().parse_args(["-f", "x", "--tcp", "h", "--full-read"]) +def test_verify_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} - assert ( - modbus_task._read_options(get_parser().parse_args(["-f", "x", "--tcp", "h"])) - == {} - ) - - -class Response: - def __init__(self, status=200, text="", body=None, headers=None): - self.status_code, self.text, self._body, self.headers = ( - status, - text, - body, - headers or {}, - ) - self.ok = status < 400 - - def json(self): - return self._body - - -def catalog_stub(monkeypatch, payload, *, commit=COMMIT, blob=None): - calls = [] - entry = { - "encoding": "base64", - "content": base64.encodebytes(payload).decode(), - "sha": blob or verification.git_blob_sha1(payload), - } - - def get(url, headers=None, timeout=None, params=None): - calls.append((url, params)) - if "/commits/" in url: - return ( - Response(text=commit + "\n") - if url.endswith("/main") or url.endswith("/v1") - else Response(404) - ) - return Response(body=entry) if "products/acme/meter/" in url else Response(404) - - monkeypatch.setattr(verification.requests, "get", get) - return calls - - -def test_a_branch_is_resolved_to_the_commit_the_report_names(monkeypatch, tmp_path): - payload = json.dumps(three_group_model()).encode() - calls = catalog_stub(monkeypatch, payload) - report_path = tmp_path / "report.json" - run_app( - monkeypatch, - ["--device", PRODUCT, "--tcp", "x", "--report", str(report_path)], - FakeClient(False, False), - ) - report = json.loads(report_path.read_text()) - assert report["product"] == PRODUCT - assert report["model"] == { - "sha256": hashlib.sha256(payload).hexdigest(), - "fingerprint": modpoll_wot.model_fingerprint(payload), - "source": "catalog", - "ref": COMMIT, - } - assert calls[-1][1] == {"ref": COMMIT} - - -def test_a_commit_is_used_as_given_and_a_download_is_checked(monkeypatch): - payload = b'{"title": "x"}' - calls = catalog_stub(monkeypatch, payload) - assert verification.fetch_catalog_model(PRODUCT, COMMIT, timeout=1) == ( - payload, - COMMIT, - ) - assert len(calls) == 1 - catalog_stub(monkeypatch, payload, blob="0" * 40) - with pytest.raises(ValueError, match="Git object id"): - verification.fetch_catalog_model(PRODUCT, COMMIT, timeout=1) - catalog_stub(monkeypatch, payload) - with pytest.raises(ValueError, match="no commit, tag or branch nope"): - verification.fetch_catalog_model(PRODUCT, "nope", timeout=1) - with pytest.raises(ValueError, match="no Thing Model for acme/other"): - verification.fetch_catalog_model("acme/other", COMMIT, timeout=1) - - -def test_device_syntax(): - assert verification.parse_device("advantech/adam-5017uh") == ( - "advantech/adam-5017uh", - "main", - ) - assert verification.parse_device(f"a/b@{COMMIT}") == ("a/b", COMMIT) - for bad in ("adam", "A/B", "a/b@", "a/b/c"): - with pytest.raises(ValueError): - verification.parse_device(bad) + args.full_read = False + assert modbus_task._read_options(args) == {}