forked from ChelseaKR/mrf-honest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
594 lines (520 loc) · 18.4 KB
/
Copy pathtest_cli.py
File metadata and controls
594 lines (520 loc) · 18.4 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
from __future__ import annotations
import json
from pathlib import Path
import pytest
import mrf_honest.cli as cli
from mrf_honest.fetch import FetchOutcome, FetchStatus
from mrf_honest.lakehouse import LakehouseScopeRefusal
class _Result:
def __init__(self, payload: dict[str, object]) -> None:
self.payload = payload
def to_dict(self) -> dict[str, object]:
return self.payload
class _AssessmentResult(_Result):
def __init__(self, payload: dict[str, object], *, operationally_complete: bool) -> None:
super().__init__(payload)
self.operationally_complete = operationally_complete
def test_inspect_json_passes_explicit_context_and_findings_exit_zero(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
observed: dict[str, object] = {}
def fake_inspect(path: Path, publisher: object, *, as_of: object) -> _Result:
observed.update(path=path, publisher=publisher, as_of=as_of)
return _Result(
{
"findings": [{"code": "CMS_V3_EXAMPLE", "severity": "ERROR"}],
"source_path": str(path),
}
)
monkeypatch.setattr(cli, "inspect_hospital_file", fake_inspect)
status = cli.main(
[
"inspect",
"prices.json",
"--publisher-id",
"example-health",
"--as-of",
"2026-08-09",
"--format",
"json",
]
)
captured = capsys.readouterr()
assert status == 0
assert json.loads(captured.out)["findings"][0]["severity"] == "ERROR"
assert captured.err == ""
assert observed["path"] == Path("prices.json")
assert str(observed["as_of"]) == "2026-08-09"
publisher = observed["publisher"]
assert publisher.identifier == "example-health" # type: ignore[attr-defined]
def test_inspect_human_is_readable_and_keeps_progress_on_stderr(
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
source = tmp_path / "prices.json"
source.write_text('{"standard_charge_information": []}', encoding="utf-8")
status = cli.main(
[
"inspect",
str(source),
"--as-of",
"2026-08-09",
]
)
captured = capsys.readouterr()
assert status == 0
assert "conformance: FINDINGS" in captured.out
assert "[ERROR] CMS_V3_ENVELOPE_HOSPITAL_NAME_MISSING" in captured.out
assert "Inspecting" in captured.err
def test_ingest_json_is_stable_and_passes_operator_identity(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
observed: dict[str, object] = {}
def fake_ingest(
source: Path,
warehouse: Path,
*,
publisher: object,
memory_limit: str,
threads: int,
as_of: object,
) -> _Result:
observed.update(
source=source,
warehouse=warehouse,
publisher=publisher,
memory_limit=memory_limit,
threads=threads,
as_of=as_of,
)
return _Result({"status": "success", "run_id": "run-1", "reused": False})
monkeypatch.setattr(cli, "ingest_hospital_file", fake_ingest)
status = cli.main(
[
"ingest",
"prices.json",
"--publisher-id",
"example-health",
"--publisher-name",
"Example Health",
"--source-url",
"https://example.test/prices.json",
"--warehouse",
str(tmp_path / "warehouse"),
"--memory-limit",
"512MB",
"--threads",
"3",
"--as-of",
"2026-08-09",
"--format",
"json",
]
)
captured = capsys.readouterr()
assert status == 0
assert captured.out == '{"reused":false,"run_id":"run-1","status":"success"}\n'
assert captured.err == ""
assert observed["source"] == Path("prices.json")
assert observed["warehouse"] == tmp_path / "warehouse"
assert observed["memory_limit"] == "512MB"
assert observed["threads"] == 3
assert str(observed["as_of"]) == "2026-08-09"
publisher = observed["publisher"]
assert publisher.identifier == "example-health" # type: ignore[attr-defined]
assert publisher.name == "Example Health" # type: ignore[attr-defined]
assert publisher.source_url == "https://example.test/prices.json" # type: ignore[attr-defined]
def test_ingest_human_progress_does_not_pollute_stdout(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
monkeypatch.setattr(
cli,
"ingest_hospital_file",
lambda *args, **kwargs: _Result({"status": "success", "counts": {"items": 2}}),
)
assert (
cli.main(
[
"ingest",
"prices.json",
"--publisher-id",
"example",
"--warehouse",
str(tmp_path),
]
)
== 0
)
captured = capsys.readouterr()
assert captured.out == 'status: success\ncounts: {"items": 2}\n'
assert captured.err == "Ingesting prices.json ...\n"
def test_ingest_scope_refusal_is_emitted_as_evidence_and_still_fails(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
"""A refused ingest must leave a document behind, not just a non-zero exit.
``compare --ingest-result`` is the only channel that carries warehouse evidence into the
published comparison. If a refusal produces nothing on stdout, the reason cannot reach the
site, and the file page states an absence of contract evidence with no reason for it.
"""
def refuse(*args: object, **kwargs: object) -> object:
raise LakehouseScopeRefusal(
"unsupported hospital JSON template version: '2.0.0'",
implemented_scope="CMS hospital JSON template version 3.0.0",
observed_scope="CMS hospital JSON template version 2.0.0",
source_file_id="a" * 64,
)
monkeypatch.setattr(cli, "ingest_hospital_file", refuse)
status = cli.main(
[
"ingest",
"prices.json",
"--publisher-id",
"example-health",
"--warehouse",
str(tmp_path / "warehouse"),
"--format",
"json",
]
)
captured = capsys.readouterr()
assert status == 1 # no snapshot was produced; the command still fails
assert json.loads(captured.out) == {
"status": "refused",
"source_file_id": "a" * 64,
"publisher_id": "example-health",
"reason": "unsupported hospital JSON template version: '2.0.0'",
"implemented_scope": "CMS hospital JSON template version 3.0.0",
"observed_scope": "CMS hospital JSON template version 2.0.0",
}
assert captured.err == "" # json mode keeps stdout parsable and stderr quiet
def test_ingest_scope_refusal_human_format_names_the_reason(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
def refuse(*args: object, **kwargs: object) -> object:
raise LakehouseScopeRefusal(
"unsupported hospital JSON template version: '2.0.0'",
implemented_scope="CMS hospital JSON template version 3.0.0",
observed_scope="CMS hospital JSON template version 2.0.0",
source_file_id="a" * 64,
)
monkeypatch.setattr(cli, "ingest_hospital_file", refuse)
status = cli.main(
[
"ingest",
"prices.json",
"--publisher-id",
"example-health",
"--warehouse",
str(tmp_path / "warehouse"),
]
)
captured = capsys.readouterr()
assert status == 1
assert "status: refused" in captured.out
assert "unsupported hospital JSON template version" in captured.out
assert "refused: unsupported hospital JSON template version" in captured.err
def test_profile_outputs_the_order_returned_by_the_lakehouse(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
rows = [
{"methodology": "fee schedule", "observation_count": 4},
{"methodology": "other", "observation_count": 1},
]
monkeypatch.setattr(cli, "query_file_profile", lambda warehouse, run_id: rows)
assert cli.main(["profile", "warehouse", "run-1"]) == 0
assert json.loads(capsys.readouterr().out) == rows
@pytest.mark.parametrize(
("fetch_status", "expected_status"),
[(FetchStatus.FETCHED, 0), (FetchStatus.NETWORK_ERROR, 1)],
)
def test_fetch_uses_a_bounded_identified_policy_without_real_network(
fetch_status: FetchStatus,
expected_status: int,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
observed: dict[str, object] = {}
def fake_fetch(
url: str, cache_dir: Path, *, policy: object, politeness: object
) -> FetchOutcome:
observed.update(url=url, cache_dir=cache_dir, policy=policy, politeness=politeness)
return FetchOutcome(
url=url,
status=fetch_status,
attempted_at="2026-08-09T00:00:00Z",
attempts=1,
error="offline" if fetch_status is FetchStatus.NETWORK_ERROR else None,
)
monkeypatch.setattr(cli, "fetch_url", fake_fetch)
status = cli.main(
[
"fetch",
"https://example.test/prices.json",
"--cache-dir",
str(tmp_path),
"--contact",
"operator@example.test",
"--max-bytes",
"2048",
]
)
assert status == expected_status
payload = json.loads(capsys.readouterr().out)
assert payload["status"] == fetch_status.value
assert observed["url"] == "https://example.test/prices.json"
policy = observed["policy"]
assert policy.contact == "operator@example.test" # type: ignore[attr-defined]
assert policy.max_bytes == 2048 # type: ignore[attr-defined]
def test_discover_records_each_domain_and_treats_findings_as_data(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
observed: list[tuple[str, object, Path, object]] = []
def fake_discover(
domain: str,
*,
registry: object,
cache_dir: Path,
policy: object,
politeness: object,
) -> _Result:
observed.append((domain, registry, cache_dir, policy))
return _Result({"domain": domain, "problems": ["no mrf-url"]})
monkeypatch.setattr(cli, "discover_domain", fake_discover)
registry_path = tmp_path / "registry.jsonl"
cache_dir = tmp_path / "cache"
status = cli.main(
[
"discover",
"one.test",
"two.test",
"--registry",
str(registry_path),
"--cache-dir",
str(cache_dir),
"--contact",
"operator@example.test",
]
)
captured = capsys.readouterr()
assert status == 0
assert [record["domain"] for record in json.loads(captured.out)] == ["one.test", "two.test"]
assert captured.err == "Discovering one.test ...\nDiscovering two.test ...\n"
assert [call[0] for call in observed] == ["one.test", "two.test"]
assert observed[0][1] is observed[1][1]
assert observed[0][1].path == registry_path # type: ignore[attr-defined]
assert observed[0][2] == cache_dir
assert observed[0][3].contact == "operator@example.test" # type: ignore[attr-defined]
@pytest.mark.parametrize(
("operationally_complete", "expected_status"),
[(True, 0), (False, 1)],
)
def test_scorecard_persists_explicit_subject_and_only_local_failures_are_nonzero(
operationally_complete: bool,
expected_status: int,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
observed: dict[str, object] = {}
def fake_assess(
subject: object,
cache_dir: Path,
*,
policy: object,
politeness: object,
registry: object,
profile: object,
) -> _AssessmentResult:
observed.update(
subject=subject,
cache_dir=cache_dir,
policy=policy,
registry=registry,
profile=profile,
)
return _AssessmentResult(
{
"assessment_id": "assessment-1",
"coverage": {"targeted": True, "remotely_observed": False},
"scorecard": {"retrievability": {"status": "FINDINGS"}},
},
operationally_complete=operationally_complete,
)
monkeypatch.setattr(cli, "assess_hospital_url", fake_assess)
registry_path = tmp_path / "scorecards.jsonl"
cache_dir = tmp_path / "cache"
status = cli.main(
[
"scorecard",
"https://files.example.test/prices.json",
"--publisher-id",
"example-health",
"--publisher-name",
"Example Health",
"--publisher-type",
"hospital",
"--location-id",
"main-campus",
"--url-provenance",
"cms_hpt",
"--registry",
str(registry_path),
"--cache-dir",
str(cache_dir),
"--contact",
"operator@example.test",
"--max-bytes",
"4096",
"--format",
"json",
]
)
assert status == expected_status
assert json.loads(capsys.readouterr().out)["assessment_id"] == "assessment-1"
subject = observed["subject"]
assert subject.publisher.identifier == "example-health" # type: ignore[attr-defined]
assert subject.publisher.name == "Example Health" # type: ignore[attr-defined]
assert subject.publisher_type == "hospital" # type: ignore[attr-defined]
assert subject.location_id == "main-campus" # type: ignore[attr-defined]
assert subject.url_provenance == "cms_hpt" # type: ignore[attr-defined]
assert observed["cache_dir"] == cache_dir
assert observed["registry"].path == registry_path # type: ignore[attr-defined]
assert observed["policy"].max_bytes == 4096 # type: ignore[attr-defined]
assert observed["profile"].name == "cms-hospital-json-v3" # type: ignore[attr-defined]
def test_grade_is_a_scorecard_alias(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
monkeypatch.setattr(
cli,
"assess_hospital_url",
lambda *args, **kwargs: _AssessmentResult(
{"assessment_id": "alias"}, operationally_complete=True
),
)
assert (
cli.main(
[
"grade",
"https://example.test/prices.json",
"--publisher-id",
"example",
"--publisher-type",
"hospital",
"--location-id",
"one",
"--url-provenance",
"operator",
"--registry",
str(tmp_path / "scorecards.jsonl"),
"--cache-dir",
str(tmp_path / "cache"),
"--contact",
"operator@example.test",
"--format",
"json",
]
)
== 0
)
assert json.loads(capsys.readouterr().out)["assessment_id"] == "alias"
def test_scorecard_human_output_redacts_url_tokens_on_stdout_and_stderr(
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
status = cli.main(
[
"scorecard",
"https://[broken?token=private#fragment",
"--publisher-id",
"example",
"--publisher-type",
"hospital",
"--location-id",
"one",
"--url-provenance",
"operator",
"--registry",
str(tmp_path / "scorecards.jsonl"),
"--cache-dir",
str(tmp_path / "cache"),
"--contact",
"operator@example.test",
]
)
captured = capsys.readouterr()
assert status == 0
assert "private" not in captured.out + captured.err
assert "fragment" not in captured.out + captured.err
assert "https://[broken" in captured.out
def test_explain_emits_the_authoritative_catalog_entry(
capsys: pytest.CaptureFixture[str],
) -> None:
assert cli.main(["explain", "FRESHNESS_DATE_IN_FUTURE"]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["code"] == "FRESHNESS_DATE_IN_FUTURE"
assert payload["dimension"] == "freshness"
assert payload["severity"] == "WARNING"
assert payload["description"]
assert payload["citations"]
def test_explain_includes_remote_retrieval_findings(
capsys: pytest.CaptureFixture[str],
) -> None:
assert cli.main(["explain", "MRF_AUTOMATION_BARRIER_OBSERVED"]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["dimension"] == "retrievability"
assert payload["severity"] == "ERROR"
assert payload["citations"]
def test_explain_unknown_code_is_a_clean_usage_failure(
capsys: pytest.CaptureFixture[str],
) -> None:
assert cli.main(["explain", "NOT_A_FINDING"]) == 1
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == "error: unknown finding code: NOT_A_FINDING\n"
def test_operational_failure_is_concise_and_nonzero(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
def fail(_warehouse: Path, _run_id: str) -> list[dict[str, object]]:
raise RuntimeError("warehouse is locked")
monkeypatch.setattr(cli, "query_file_profile", fail)
assert cli.main(["profile", "warehouse", "run-1"]) == 1
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == "error: warehouse is locked\n"
@pytest.mark.parametrize(
"argv",
[
[
"fetch",
"https://example.test/a",
"--cache-dir",
"cache",
"--contact",
"a@b.test",
"--max-bytes",
"0",
],
["ingest", "a.json", "--publisher-id", "x", "--warehouse", "w", "--threads", "-1"],
["inspect", "a.json", "--as-of", "09/08/2026"],
],
)
def test_invalid_typed_options_are_usage_errors(argv: list[str]) -> None:
with pytest.raises(SystemExit) as raised:
cli.main(argv)
assert raised.value.code == 2