-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
373 lines (321 loc) · 12.3 KB
/
Copy pathtest_cli.py
File metadata and controls
373 lines (321 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""CLI behavior and value-minimizing error tests."""
import json
from pathlib import Path
import pytest
from contextsafe.cli import EXIT_USAGE_ERROR, main
from contextsafe.evidence import CANONICAL_JSON_MEDIA_TYPE, CANONICAL_JSON_SOURCE_TYPE
from contextsafe.plan import ExecutionPlan
ROOT = Path(__file__).resolve().parents[1]
REFERENCE = ROOT / "fixtures" / "reference"
def _args(command: str) -> list[str]:
return [
command,
"--case",
str(REFERENCE / "case.json"),
"--observations",
str(REFERENCE / "observations.json"),
"--rules",
str(REFERENCE / "rules.json"),
]
def _evidence_preflight_args(plan_path: Path) -> list[str]:
return [
"evidence",
"preflight",
"--source",
str(REFERENCE / "evidence-source.json"),
"--plan",
str(plan_path),
"--case-token",
"CSYN-CTP-I01",
"--checkpoint",
"ehr",
"--source-type",
CANONICAL_JSON_SOURCE_TYPE,
"--media-type",
CANONICAL_JSON_MEDIA_TYPE,
]
def test_validate_cli_emits_machine_readable_summary(capsys: object) -> None:
assert main(_args("validate")) == 0
captured = capsys.readouterr()
report = json.loads(captured.out)
assert report["valid"] is True
assert report["observation_count"] == 5
assert captured.err == ""
def test_evaluate_cli_can_write_receipt(tmp_path: Path, capsys: object) -> None:
output = tmp_path / "receipt.json"
assert main([*_args("evaluate"), "--output", str(output)]) == 0
captured = capsys.readouterr()
assert captured.out == ""
document = json.loads(output.read_text(encoding="utf-8"))
assert set(document) == {"envelope", "payload", "payload_sha256", "schema_version"}
assert document["payload"]["summary"]["pass"] == 5
assert document["envelope"]["claimed_generated_at"] is None
assert document["envelope"]["signature_status"] == "not_signed"
def test_evaluate_cli_claimed_time_stays_outside_the_payload(
tmp_path: Path, capsys: object
) -> None:
baseline = tmp_path / "baseline.json"
claimed = tmp_path / "claimed.json"
assert main([*_args("evaluate"), "--output", str(baseline)]) == 0
assert (
main(
[
*_args("evaluate"),
"--output",
str(claimed),
"--claimed-generated-at",
"2026-07-17T01:02:03Z",
]
)
== 0
)
baseline_document = json.loads(baseline.read_text(encoding="utf-8"))
claimed_document = json.loads(claimed.read_text(encoding="utf-8"))
assert claimed_document["envelope"]["claimed_generated_at"] == (
"2026-07-17T01:02:03Z"
)
assert claimed_document["payload"] == baseline_document["payload"]
assert claimed_document["payload_sha256"] == baseline_document["payload_sha256"]
def test_evaluate_cli_rejects_noncanonical_claimed_time_without_echo(
capsys: object,
) -> None:
for value, code in (
("2026-07-17T01:02:03+00:00", "invalid_format"),
("2026-07-17T01:02:03.500Z", "invalid_format"),
("2026-13-17T01:02:03Z", "invalid_timestamp"),
):
assert main([*_args("evaluate"), "--claimed-generated-at", value]) == 2
captured = capsys.readouterr()
assert json.loads(captured.err)["error"]["code"] == code
assert value not in captured.err
assert captured.out == ""
def test_cli_prohibited_field_fails_without_echoing_value(
tmp_path: Path, capsys: object
) -> None:
case = json.loads((REFERENCE / "case.json").read_text(encoding="utf-8"))
case["narrative"] = "never echo this patient-like content"
path = tmp_path / "case.json"
path.write_text(json.dumps(case), encoding="utf-8")
args = _args("validate")
args[2] = str(path)
assert main(args) == 2
captured = capsys.readouterr()
error = json.loads(captured.err)["error"]
assert error["code"] == "prohibited_field"
assert "patient-like" not in captured.err
def test_cli_rejects_invalid_json_duplicate_keys_and_utf8(
tmp_path: Path, capsys: object
) -> None:
args = _args("validate")
invalid = tmp_path / "invalid.json"
invalid.write_text("{", encoding="utf-8")
args[2] = str(invalid)
assert main(args) == 2
assert json.loads(capsys.readouterr().err)["error"]["code"] == "invalid_json"
invalid.write_text('{"schema_version":"a","schema_version":"b"}', encoding="utf-8")
assert main(args) == 2
assert json.loads(capsys.readouterr().err)["error"]["code"] == "duplicate_json_key"
invalid.write_bytes(b"\xff")
assert main(args) == 2
assert json.loads(capsys.readouterr().err)["error"]["code"] == "invalid_utf8"
def test_cli_rejects_nonstandard_and_oversized_numbers(
tmp_path: Path, capsys: object
) -> None:
args = _args("validate")
invalid = tmp_path / "invalid-number.json"
args[2] = str(invalid)
for numeric_literal in ("NaN", "1" * 5_000):
invalid.write_text(f'{{"value":{numeric_literal}}}', encoding="utf-8")
assert main(args) == 2
error = json.loads(capsys.readouterr().err)["error"]
assert error["code"] == "invalid_json"
def test_cli_rejects_non_scalar_unicode_without_crashing(
tmp_path: Path, capsys: object
) -> None:
case = json.loads((REFERENCE / "case.json").read_text(encoding="utf-8"))
case["concepts"]["pronouns"]["value"] = json.loads('"\\ud800"')
path = tmp_path / "case.json"
path.write_text(json.dumps(case), encoding="utf-8")
args = _args("validate")
args[2] = str(path)
assert main(args) == 2
error = json.loads(capsys.readouterr().err)["error"]
assert error["code"] == "invalid_unicode"
def test_cli_rejects_unreadable_and_oversized_inputs(
tmp_path: Path, capsys: object
) -> None:
args = _args("validate")
args[2] = str(tmp_path / "missing.json")
assert main(args) == 2
assert json.loads(capsys.readouterr().err)["error"]["code"] == "input_io_error"
large = tmp_path / "large.json"
large.write_bytes(b" " * 1_048_577)
args[2] = str(large)
assert main(args) == 2
assert json.loads(capsys.readouterr().err)["error"]["code"] == "input_too_large"
def test_cli_rejects_excessively_nested_json_without_crashing(
tmp_path: Path, capsys: object
) -> None:
args = _args("validate")
deeply_nested = tmp_path / "deep.json"
deeply_nested.write_text("[" * 2_000 + "0" + "]" * 2_000, encoding="utf-8")
args[2] = str(deeply_nested)
assert main(args) == 2
error = json.loads(capsys.readouterr().err)["error"]
assert error["code"] == "input_too_deep"
def test_cli_reports_output_failure(tmp_path: Path, capsys: object) -> None:
assert main([*_args("evaluate"), "--output", str(tmp_path)]) == 2
assert json.loads(capsys.readouterr().err)["error"]["code"] == "output_io_error"
def test_evidence_preflight_reports_output_failure(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
execution_plan: ExecutionPlan,
) -> None:
plan_path = tmp_path / "plan.json"
plan_path.write_text(json.dumps(execution_plan.to_dict()), encoding="utf-8")
args = [*_evidence_preflight_args(plan_path), "--output", str(tmp_path)]
assert main(args) == 2
error = json.loads(capsys.readouterr().err)["error"]
assert error["code"] == "output_io_error"
def test_quiet_suppresses_stdout_success_payload(
capsys: pytest.CaptureFixture[str],
) -> None:
assert main([*_args("validate"), "--quiet"]) == 0
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == ""
def test_quiet_still_writes_output_file(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
output = tmp_path / "receipt.json"
assert main([*_args("evaluate"), "--quiet", "--output", str(output)]) == 0
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == ""
receipt = json.loads(output.read_text(encoding="utf-8"))
assert receipt["payload"]["summary"]["pass"] == 5
def test_evidence_preflight_cli_can_write_result(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
execution_plan: ExecutionPlan,
) -> None:
plan_path = tmp_path / "plan.json"
plan_path.write_text(json.dumps(execution_plan.to_dict()), encoding="utf-8")
output = tmp_path / "preflight-result.json"
args = [*_evidence_preflight_args(plan_path), "--output", str(output)]
assert main(args) == 0
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == ""
result = json.loads(output.read_text(encoding="utf-8"))
assert result["boundary_check_status"] == "passed"
assert result["persisted"] is False
assert result["raw_sha256"]
def test_evidence_preflight_quiet_still_writes_output_file(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
execution_plan: ExecutionPlan,
) -> None:
plan_path = tmp_path / "plan.json"
plan_path.write_text(json.dumps(execution_plan.to_dict()), encoding="utf-8")
output = tmp_path / "preflight-result.json"
args = [*_evidence_preflight_args(plan_path), "--quiet", "--output", str(output)]
assert main(args) == 0
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == ""
result = json.loads(output.read_text(encoding="utf-8"))
assert result["boundary_check_status"] == "passed"
def test_evidence_preflight_without_output_still_prints_result(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
execution_plan: ExecutionPlan,
) -> None:
plan_path = tmp_path / "plan.json"
plan_path.write_text(json.dumps(execution_plan.to_dict()), encoding="utf-8")
assert main(_evidence_preflight_args(plan_path)) == 0
captured = capsys.readouterr()
assert captured.err == ""
result = json.loads(captured.out)
assert result["boundary_check_status"] == "passed"
def test_quiet_preserves_structured_stderr_error(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
args = _args("validate")
args[2] = str(tmp_path / "missing.json")
assert main([*args, "--quiet"]) == 2
captured = capsys.readouterr()
assert captured.out == ""
assert json.loads(captured.err)["error"]["code"] == "input_io_error"
def test_usage_errors_exit_with_dedicated_code(
capsys: pytest.CaptureFixture[str],
) -> None:
usage_errors: list[list[str]] = [
[],
["validate"],
[*_args("validate"), "--unknown-flag"],
["pack"],
["evidence", "preflight"],
]
for argv in usage_errors:
with pytest.raises(SystemExit) as raised:
main(argv)
assert raised.value.code == EXIT_USAGE_ERROR
captured = capsys.readouterr()
assert captured.out == ""
assert "error:" in captured.err
def test_help_exits_zero_and_documents_exit_codes(
capsys: pytest.CaptureFixture[str],
) -> None:
with pytest.raises(SystemExit) as raised:
main(["--help"])
assert raised.value.code == 0
help_text = capsys.readouterr().out
assert "exit codes" in help_text
assert "64" in help_text
def test_no_color_accepted_and_output_never_contains_ansi(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
execution_plan: ExecutionPlan,
) -> None:
plan_path = tmp_path / "plan.json"
plan_path.write_text(json.dumps(execution_plan.to_dict()), encoding="utf-8")
draft_pack = str(REFERENCE / "pack-draft.json")
invocations: list[tuple[int, list[str]]] = [
(0, [*_args("validate"), "--no-color"]),
(0, [*_args("evaluate"), "--no-color"]),
(
2,
[
"pack",
"validate",
"--no-color",
"--pack",
draft_pack,
"--as-of",
"2026-07-13",
],
),
(
2,
[
"plan",
"validate",
"--no-color",
"--engagement",
draft_pack,
"--plan",
str(plan_path),
"--pack",
draft_pack,
"--as-of",
"2026-07-13",
],
),
(0, [*_evidence_preflight_args(plan_path), "--no-color"]),
]
for expected_exit, argv in invocations:
assert main(argv) == expected_exit
captured = capsys.readouterr()
assert "\x1b" not in captured.out
assert "\x1b" not in captured.err