diff --git a/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md new file mode 100644 index 000000000..9fdc212b6 --- /dev/null +++ b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md @@ -0,0 +1,3 @@ +### Changed + +- **The JSON input flags share one reader and refuse a device.** `eval personas validate --file`, `eval questions generate --personas` and `--topics`, `eval questions analyze` and `review --questions`, `arms run` and `matrix-run --questions`, `report generate --eval`, `tools preference --groups`, `repo scan --baseline` and `--static` and `catalog trigger-probe --trigger-set` now read their file with `read_json_input`. A device or socket given to one of them (`/dev/zero`, `/dev/null`) exits 2 with ` : not a file`, before it is read; it used to be read in full, and `/dev/null` used to fail as invalid JSON. (`personas validate --file` and `questions generate --personas/--topics` already refused a device; only their message changes.) Their messages take the ` : ` form: `cannot read : ` and ` is not valid JSON: ` become ` : `, `File not found: `, `Cannot read ` and `Cannot parse ` (`personas validate`) become `--file : `, `cannot load matrix run inputs: ` (`matrix-run --questions` on an unreadable file) becomes `--questions : `, and `--trigger-set : ` names the file, and a shape error inside the set keeps its `--trigger-set: ` form. The reason is the OS error text (`No such file or directory`), not the full `[Errno 2] ...` string. An empty path exits 2 with ` "": no file given`. Exit codes stay 2, with one exception: a JSON file nested past the decoder's recursion limit now exits 2 naming the file, where `personas validate`, `report generate`, `catalog trigger-probe` and `questions generate --personas/--topics` used to exit 5 with a traceback. diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index 97703dc19..93b77bee2 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -16,7 +16,7 @@ from dokimi.commands.novelty_budget import fresh_partial_destination from dokimi.exit_codes import EXIT_FAILURE, EXIT_USAGE from dokimi.llm import ANSWER_PROVIDERS -from dokimi.utils import InputError, question_id +from dokimi.utils import InputError, question_id, read_json_input from dokimi.write_probe import can_write from dokimi.eval.judge import JUDGE_PROVIDERS from dokimi.defaults import ( @@ -85,8 +85,8 @@ def cmd_arms_run(args: argparse.Namespace) -> None: questions = _load_questions(args.questions) config = _with_named_cell(config, args.matrix_cells, args.matrix_cell) prepared = prepare_arms(config, specs, questions) - except EmptyQuestionError: - raise # a bad input record, not an arm setup error: cli.main reports it (exit 2) + except InputError: # EmptyQuestionError is one + raise # a bad input record or an unreadable file, not an arm setup error: cli.main reports it (exit 2) except ProbeError as exc: print(f"Error running arms: {exc}", file=sys.stderr) sys.exit(EXIT_FAILURE) @@ -521,7 +521,7 @@ def _load_questions(path: str) -> list[dict]: from dokimi.questions.artifact import load_questions _refuse_external_trigger_set(path) - questions = load_questions(path).questions + questions = load_questions(path, flag="--questions").questions # a device is refused here, not read whole ids = [question_id(q) for q in questions] for i, qid in enumerate(ids): # The records reader refuses any other id, so a run with one would be paid for and lost. @@ -538,13 +538,11 @@ def _refuse_external_trigger_set(path: str) -> None: lints them against the catalog the arm will offer; a questions loader that guessed at them would drop that lint and, for skill-creator, the target skill. """ - import json - from dokimi.external.trigger_set import FORMAT_QUESTIONS, detect_trigger_format try: - data = json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError): + data = read_json_input(path) + except InputError: return # the questions loader reports it fmt = detect_trigger_format(data) if fmt and fmt != FORMAT_QUESTIONS: diff --git a/dokimi/dokimi/commands/catalog_probe.py b/dokimi/dokimi/commands/catalog_probe.py index b9ce48b27..301b52cd4 100644 --- a/dokimi/dokimi/commands/catalog_probe.py +++ b/dokimi/dokimi/commands/catalog_probe.py @@ -15,7 +15,7 @@ from pathlib import Path from dokimi import cli_flags from dokimi.atomic_write import write_text_atomic -from dokimi.utils import InputError +from dokimi.utils import InputError, read_json_input from dokimi.write_probe import can_write @@ -156,8 +156,8 @@ def _labelled_queries(args: argparse.Namespace, names: set) -> list: """The labelled queries to run; a label naming no *names* skill is an input error.""" from dokimi.external import trigger_set as ts + data = read_json_input(args.trigger_set, flag="--trigger-set") # InputError names the file try: - data = json.loads(Path(args.trigger_set).read_text(encoding="utf-8")) _fmt, queries = ts.read_trigger_set(data, target=args.target) except (OSError, ValueError) as exc: raise InputError(f"--trigger-set: {exc}") from exc diff --git a/dokimi/dokimi/commands/personas.py b/dokimi/dokimi/commands/personas.py index 5cb412556..3d868d04c 100644 --- a/dokimi/dokimi/commands/personas.py +++ b/dokimi/dokimi/commands/personas.py @@ -6,7 +6,6 @@ from __future__ import annotations import argparse -import json import sys from pathlib import Path @@ -18,7 +17,7 @@ from dokimi.exit_codes import EXIT_INCONCLUSIVE from dokimi.personas.analyzer import PersonaAnalyzer from dokimi.personas.generator import PersonaGenerator, check_can_generate, estimate_generation -from dokimi.utils import InputError, refuse_device +from dokimi.utils import InputError, read_json_input def _usd_text(usd: float) -> str: @@ -139,17 +138,8 @@ def cmd_personas_approve(args: argparse.Namespace) -> None: """Mark persona file as approved (ready for question generation).""" persona_file = Path(args.file) - if not persona_file.exists(): - raise InputError(f"File not found: {persona_file}") - refuse_device(persona_file, "--file") - # Validate JSON structure - try: - personas = json.loads(persona_file.read_text(encoding="utf-8")) - except OSError as e: - raise InputError(f"Cannot read {persona_file}: {e}") from e - except ValueError as e: # JSONDecodeError and bad UTF-8 - raise InputError(f"Cannot parse {persona_file}: {e}") from e + personas = read_json_input(args.file, flag="--file") # the raw argument: "" is refused, not read as "." required_keys = {"product", "personas"} if not isinstance(personas, dict): diff --git a/dokimi/dokimi/commands/questions.py b/dokimi/dokimi/commands/questions.py index cd25be6aa..d224023cf 100644 --- a/dokimi/dokimi/commands/questions.py +++ b/dokimi/dokimi/commands/questions.py @@ -7,7 +7,6 @@ import argparse import hashlib -import json import sys from pathlib import Path from typing import Any, Dict @@ -15,15 +14,12 @@ from dokimi.llm import ANSWER_PROVIDERS, CALLER_CHOICES from dokimi.commands._output import exit_on_rejected, exit_on_unwritable from dokimi.defaults import DEFAULT_GENERATOR_MODEL, DEFAULT_GENERATOR_PROVIDER -from dokimi.utils import InputError, key_bytes, refuse_device, warn_recorded_self_judge +from dokimi.utils import InputError, key_bytes, read_json_input, warn_recorded_self_judge def _load_questions_json(path: str): - """Parse the questions file, or exit 2 naming it when it is missing, unreadable or not JSON.""" - try: - return json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError) as exc: - raise InputError(f"cannot read questions from {path}: {exc}") from exc + """Parse the questions file, or exit 2 naming it when it is missing, unreadable, a device or not JSON.""" + return read_json_input(path, flag="--questions") def _extract_questions(questions_data, source: str) -> list: @@ -39,18 +35,9 @@ def _extract_questions(questions_data, source: str) -> list: return raw -def _read_json_input(path: str, flag: str): - """The parsed JSON at ``path``, or exit 2 with a message naming the file (and ``flag``, for a device).""" - refuse_device(path, flag) # InputError: cli.main prints it and exits 2 - try: - return json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: # ValueError covers JSONDecodeError and bad UTF-8 - raise InputError(f"cannot read {path}: {exc}") from exc - - def _load_personas(path: str) -> list: """The ``personas`` list of a personas file, or exit 2 with a message naming the file.""" - data = _read_json_input(path, "--personas") + data = read_json_input(path, flag="--personas") personas = data.get("personas") if isinstance(data, dict) else None if not isinstance(personas, list): raise InputError(f"{path} must be a JSON object with a 'personas' list") @@ -299,7 +286,7 @@ def cmd_questions_generate(args: argparse.Namespace) -> None: # Get or extract topics if args.topics: - topics = _read_json_input(args.topics, "--topics") + topics = read_json_input(args.topics, flag="--topics") if not isinstance(topics, list): raise InputError(f"{args.topics} must be a JSON list of topics") else: diff --git a/dokimi/dokimi/commands/repo.py b/dokimi/dokimi/commands/repo.py index bb7bb806d..94a68ddcf 100644 --- a/dokimi/dokimi/commands/repo.py +++ b/dokimi/dokimi/commands/repo.py @@ -6,7 +6,6 @@ from __future__ import annotations import argparse -import json import re import sys from pathlib import Path @@ -21,7 +20,7 @@ from dokimi.exit_codes import EXIT_USAGE from dokimi.commands.repo_scan import (_loaded_with_default, _print_scan_text, _scan_gate, _scan_reason, _typecheck_or_exit) -from dokimi.utils import InputError +from dokimi.utils import InputError, read_json_input def _normalize_whitespace(text: str, max_len: int | None = 100) -> str: @@ -127,10 +126,7 @@ def cmd_repo_validate(args: argparse.Namespace) -> None: def _read_static(path: str) -> Any: - try: - return json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError) as exc: # ValueError: bad JSON or UTF-8 - raise InputError(f"--static {path}: {exc}") from exc + return read_json_input(path, flag="--static") def cmd_repo_scan(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/repo_scan.py b/dokimi/dokimi/commands/repo_scan.py index d032f0de7..b69dea515 100644 --- a/dokimi/dokimi/commands/repo_scan.py +++ b/dokimi/dokimi/commands/repo_scan.py @@ -7,16 +7,14 @@ from __future__ import annotations import argparse -import json import os -from pathlib import Path import posixpath import re import sys import shutil from dokimi.repos.l0.config import new_failures -from dokimi.utils import InputError +from dokimi.utils import InputError, read_json_input def _typecheck_or_exit(args: argparse.Namespace): @@ -279,10 +277,7 @@ def baseline_from(args: argparse.Namespace, payload: dict) -> None: if not getattr(args, "baseline", None): return - try: - doc = json.loads(Path(args.baseline).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError) as exc: # RecursionError: nesting past the decoder's limit - raise InputError(f"--baseline {args.baseline}: {exc}") from None + doc = read_json_input(args.baseline, flag="--baseline") doc = doc.get("data", doc) if isinstance(doc, dict) and doc.get("schema_version") == "cli_output.v1" else doc if not isinstance(doc, dict) or not isinstance(doc.get("claims"), list): raise InputError(f"--baseline {args.baseline}: not a repo_readiness.v1 report (no claims list)") diff --git a/dokimi/dokimi/commands/report.py b/dokimi/dokimi/commands/report.py index f3ef4ddda..e67b57837 100644 --- a/dokimi/dokimi/commands/report.py +++ b/dokimi/dokimi/commands/report.py @@ -7,12 +7,11 @@ import argparse import sys -import json from pathlib import Path from dokimi import cli_flags from dokimi.commands._output import exit_on_rejected from dokimi.exit_codes import EXIT_USAGE -from dokimi.utils import InputError +from dokimi.utils import InputError, read_json_input def _write_combined_report(args, regular_runs, golden_runs, run_ids, warnings) -> None: @@ -119,12 +118,7 @@ def cmd_report_generate(args: argparse.Namespace) -> None: from dokimi.report import ReportGenerator # Load eval and questions - try: - eval_data = json.loads(Path(args.eval).read_text(encoding="utf-8")) - except OSError as exc: - raise InputError(f"cannot read {args.eval}: {exc}") from exc - except ValueError as exc: # not UTF-8 or not JSON - raise InputError(f"{args.eval} is not valid JSON: {exc}") from exc + eval_data = read_json_input(args.eval, flag="--eval") # Every --format: a report of no evaluations has nothing to show, and an empty # eval means the run that wrote it judged nothing: a failed run, exit 1. evaluations = eval_data.get("evaluations", []) if isinstance(eval_data, dict) else eval_data diff --git a/dokimi/dokimi/commands/tools.py b/dokimi/dokimi/commands/tools.py index f6a8c3ba7..3c1bf17ca 100644 --- a/dokimi/dokimi/commands/tools.py +++ b/dokimi/dokimi/commands/tools.py @@ -18,7 +18,7 @@ from dokimi.cli_types import positive_usd from dokimi.defaults import DEFAULT_ANSWER_PROVIDER from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE, EXIT_USAGE -from dokimi.utils import InputError +from dokimi.utils import InputError, read_json_input PROVIDERS = list(API_PROVIDERS) # tool calling: no CLI backend @@ -143,9 +143,10 @@ def _check_out_json_writable(path: str) -> None: def cmd_tools_preference(args: argparse.Namespace) -> None: from dokimi import tool_preference as tp + data = read_json_input(args.groups, flag="--groups") # InputError names the file try: - doc = tp.load_groups(json.loads(Path(args.groups).read_text(encoding="utf-8"))) - except (OSError, RecursionError, ValueError, tp.GroupsError) as exc: + doc = tp.load_groups(data) + except (ValueError, tp.GroupsError) as exc: raise InputError(f"--groups {args.groups}: {exc}") from exc factors = list(dict.fromkeys(f for f in args.factors.split(",") if f)) if args.factors else list(tp.FACTORS) unknown = sorted(set(factors) - set(tp.FACTORS)) diff --git a/dokimi/tests/test_arms_output_errors.py b/dokimi/tests/test_arms_output_errors.py index e3ef28cd0..c33f0846a 100644 --- a/dokimi/tests/test_arms_output_errors.py +++ b/dokimi/tests/test_arms_output_errors.py @@ -172,7 +172,7 @@ def test_arms_run_exits_2_on_an_unreadable_questions_file(tmp_path, capsys, kind with refusal() as exc: args.func(args) assert exc.code == 2 - assert capsys.readouterr().err.startswith("Error: cannot build arms/plugins:") + assert capsys.readouterr().err.startswith(f"Error: --questions {questions}: ") @pytest.mark.parametrize("kind", ["directory", "deep"]) @@ -187,7 +187,7 @@ def test_matrix_run_exits_2_on_an_unreadable_questions_file(tmp_path, capsys, ki with refusal() as exc: args.func(args) assert exc.code == 2 - assert capsys.readouterr().err.startswith("Error: cannot load matrix run inputs:") + assert capsys.readouterr().err.startswith(f"Error: --questions {args.questions}: ") @pytest.mark.parametrize("error", [PermissionError("denied"), RecursionError("deep")], ids=lambda e: type(e).__name__) diff --git a/dokimi/tests/test_cli_refusal_parity.py b/dokimi/tests/test_cli_refusal_parity.py index 6ec611fc1..2c105bcfc 100644 --- a/dokimi/tests/test_cli_refusal_parity.py +++ b/dokimi/tests/test_cli_refusal_parity.py @@ -46,7 +46,7 @@ def _assert_helper_matches_main(argv, monkeypatch, capsys, expect): (lambda d: ["catalog", "check", "--root", str(d / "missing")], "--root is not a directory"), (lambda d: ["catalog", "list", "--kind", "subject", "--subjects-root", str(d / "missing")], "--subjects-root is not a directory"), - (lambda d: ["eval", "personas", "validate", "--file", str(d / "missing.json")], "File not found"), + (lambda d: ["eval", "personas", "validate", "--file", str(d / "missing.json")], "No such file or directory"), (lambda d: ["catalog", "list", "--kind", "product", "--registry", str(d / "missing.yaml")], "not a file"), ], ids=["data-export-missing-input", "judge-validate-escalation-needs-pairwise", "eval-tasks-list-root", "explore-list-root", "catalog-check-root", "catalog-list-subject-root", "personas-validate-missing-file", @@ -118,7 +118,7 @@ def _subject_run(d): (_subject_run, "no-such-harness"), (lambda d: ["catalog", "trigger-probe", "--catalog", str(_skill_catalog(d)), "--trigger-set", str(d / "missing.json"), "--claude", "python3", "--out", str(d / "probe.json")], - "--trigger-set: "), + "--trigger-set "), ], ids=["catalog-formats-root", "explore-run-command-arm-without-template", "explore-run-unknown-arm", "explore-run-no-arms", "explore-run-empty-arm", "tasks-run-no-tasks", "tasks-run-swebench-no-tasks", "tasks-run-no-harnesses", "subjects-run-unknown-work-harness", "trigger-probe-unreadable-trigger-set"]) diff --git a/dokimi/tests/test_input_devices.py b/dokimi/tests/test_input_devices.py index 1528b6068..c8a9ead93 100644 --- a/dokimi/tests/test_input_devices.py +++ b/dokimi/tests/test_input_devices.py @@ -113,6 +113,13 @@ def test_evaluate_refuses_a_device_as_custom_questions(monkeypatch, tmp_path, ca assert "Error: --custom-questions /dev/null: not a file" in capsys.readouterr().err +def test_arms_questions_loader_refuses_a_device_with_its_flag_name(): + from dokimi.commands.arms import _load_questions + + with pytest.raises(InputError, match=r"^--questions /dev/null: not a file$"): + _load_questions(DEVICE) + + def test_the_pipeline_refuses_a_device_as_questions_from(tmp_path): with pytest.raises(InputError, match=r"^--questions-from /dev/null: not a file$"): EvaluationPipeline(product="Demo", output_dir=tmp_path / "out", description="d", questions_from=DEVICE) @@ -162,6 +169,29 @@ def test_questions_generate_refuses_a_device_as_topics(monkeypatch, tmp_path, ca assert capsys.readouterr().err.strip() == "Error: --topics /dev/null: not a file" +# The file flags that read JSON through read_json_input: each refuses a device with its own flag name, before a read. +_JSON_FLAG_DEVICES = [ + (["report", "generate", "--product", "p", "--questions", "q.json", "--eval", DEVICE, + "--format", "markdown", "--out", "r.md"], "--eval"), + (["tools", "preference", "--groups", DEVICE, "--out", "x.json"], "--groups"), + (["eval", "questions", "analyze", "--product", "p", "--questions", DEVICE], "--questions"), + (["eval", "questions", "review", "--product", "p", "--questions", DEVICE], "--questions"), + (["repo", "scan", ".", "--baseline", DEVICE], "--baseline"), + (["repo", "scan", ".", "--static", DEVICE], "--static"), + (["catalog", "trigger-probe", "--catalog", ".", "--trigger-set", DEVICE, "--claude", "python3", + "--out", "p.json"], "--trigger-set"), + (["eval", "personas", "validate", "--file", DEVICE], "--file"), +] + + +@pytest.mark.parametrize("argv, flag", _JSON_FLAG_DEVICES, ids=["-".join(argv[:3]) for argv, _flag in _JSON_FLAG_DEVICES]) +def test_json_file_flags_refuse_a_device_with_their_flag_name(monkeypatch, tmp_path, capsys, argv, flag): + monkeypatch.chdir(tmp_path) + assert _main(monkeypatch, *argv) == 2 + err = capsys.readouterr().err + assert f"Error: {flag} {DEVICE}: not a file" in err and "Traceback" not in err + + def test_novelty_analyze_refuses_a_device_as_placebo_text(monkeypatch, capsys): assert _main(monkeypatch, "skill", "novelty", "analyze", "--artifact", "skill:data/skills/fastcontext", "--arms", "no_artifact,full,placebo", "--placebo-text", DEVICE) == 2 @@ -281,3 +311,20 @@ def test_trace_consistency_refuses_a_device_as_outcomes_or_contract(monkeypatch, good = _trace(tmp_path) assert _main(monkeypatch, "trace", "consistency", flag, DEVICE, good) == 2 assert f"Error: {flag} /dev/null: not a file" in capsys.readouterr().err + + +@pytest.mark.parametrize("argv, flag", [ + (["eval", "personas", "validate", "--file"], "--file"), + (["report", "generate", "--product", "p", "--questions", "q.json", "--format", "markdown", "--out", "r.md", + "--eval"], "--eval"), +], ids=["personas-validate", "report-generate"]) +def test_json_nested_past_the_decoder_limit_is_bad_json_not_a_crash(monkeypatch, tmp_path, capsys, argv, flag): + """Nesting past the JSON decoder's recursion limit exits 2 naming the file (the shared reader's contract); + it used to escape as a RecursionError, exit 5, at these sites.""" + deep = tmp_path / "deep.json" + deep.write_text("[" * 200000 + "]" * 200000, encoding="utf-8") + monkeypatch.chdir(tmp_path) + assert _main(monkeypatch, *argv, str(deep)) == 2 + err = capsys.readouterr().err + # The decoder's own words for the overflow vary by Python (3.14 says "Stack overflow"), so pin the file and the exit only. + assert f"Error: {flag} {deep}: " in err and "Traceback" not in err diff --git a/dokimi/tests/test_personas_approve.py b/dokimi/tests/test_personas_approve.py index afd7c72d1..43322da63 100644 --- a/dokimi/tests/test_personas_approve.py +++ b/dokimi/tests/test_personas_approve.py @@ -6,6 +6,7 @@ from __future__ import annotations import json +import os import pytest @@ -46,11 +47,31 @@ def test_approve_exits_2_with_a_message_on_an_invalid_file(tmp_path, monkeypatch err = capsys.readouterr().err assert err.startswith("Error: ") and "Traceback" not in err if content.startswith(b"\xff"): - assert f"Cannot parse {f}" in err + assert f"Error: --file {f}: 'utf-8' codec can't decode" in err if content.endswith(b'["not-an-object"]}'): assert "'not-an-object'" in err def test_approve_exits_2_when_the_path_is_a_directory(tmp_path, monkeypatch, capsys): assert _approve(tmp_path, monkeypatch) == 2 - assert f"Cannot read {tmp_path}" in capsys.readouterr().err + assert f"Error: --file {tmp_path}: Is a directory" in capsys.readouterr().err + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root reads under a mode 000 directory") +def test_approve_exits_2_naming_the_flag_on_a_file_it_cannot_reach(tmp_path, monkeypatch, capsys): + locked = tmp_path / "locked" + locked.mkdir() + f = locked / "personas.json" + f.write_text("{}", encoding="utf-8") + locked.chmod(0) + try: + assert _approve(f, monkeypatch) == 2 + finally: + locked.chmod(0o755) + assert capsys.readouterr().err.strip() == f"Error: --file {f}: Permission denied" + + +def test_approve_exits_2_naming_the_flag_on_a_missing_file(tmp_path, monkeypatch, capsys): + f = tmp_path / "missing.json" + assert _approve(f, monkeypatch) == 2 + assert capsys.readouterr().err.strip() == f"Error: --file {f}: No such file or directory" diff --git a/dokimi/tests/test_report_cli_inputs.py b/dokimi/tests/test_report_cli_inputs.py index d39579039..641f737ef 100644 --- a/dokimi/tests/test_report_cli_inputs.py +++ b/dokimi/tests/test_report_cli_inputs.py @@ -36,24 +36,24 @@ def _err(tmp_path, eval_path, capsys, fmt="markdown", code=2): def test_a_missing_eval_file_is_reported_as_unreadable(tmp_path, capsys): missing = tmp_path / "missing.json" - assert f"Error: cannot read {missing}" in _err(tmp_path, missing, capsys) + assert f"Error: --eval {missing}: No such file or directory" in _err(tmp_path, missing, capsys) def test_a_directory_as_eval_is_reported_as_unreadable(tmp_path, capsys): - assert f"Error: cannot read {tmp_path}" in _err(tmp_path, tmp_path, capsys) + assert f"Error: --eval {tmp_path}: Is a directory" in _err(tmp_path, tmp_path, capsys) -@pytest.mark.parametrize("text", ["", "{not json"]) -def test_an_eval_file_that_is_not_json_is_reported_as_invalid_json(tmp_path, capsys, text): +@pytest.mark.parametrize("text, reason", [("", "Expecting value"), ("{not json", "Expecting property name")]) +def test_an_eval_file_that_is_not_json_is_reported_as_invalid_json(tmp_path, capsys, text, reason): bad = tmp_path / "bad.json" bad.write_text(text, encoding="utf-8") - assert f"Error: {bad} is not valid JSON" in _err(tmp_path, bad, capsys) + assert f"Error: --eval {bad}: {reason}" in _err(tmp_path, bad, capsys) def test_a_non_utf8_eval_file_is_reported_as_invalid_utf8_json(tmp_path, capsys): binary = tmp_path / "bin.json" binary.write_bytes(bytes([0xFF, 0xFE])) - assert f"Error: {binary} is not valid JSON" in _err(tmp_path, binary, capsys) + assert f"Error: --eval {binary}: 'utf-8' codec can't decode" in _err(tmp_path, binary, capsys) @pytest.mark.parametrize("text", ["[1, 2]", "null", "5", '"x"'])