forked from ChelseaKR/mrf-honest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_registry.py
More file actions
315 lines (270 loc) · 10.4 KB
/
Copy pathtest_registry.py
File metadata and controls
315 lines (270 loc) · 10.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
from __future__ import annotations
import json
from datetime import UTC, datetime
from pathlib import Path
from urllib.request import Request
import pytest
import robots_fixtures
from mrf_honest.fetch import FetchPolicy, FetchStatus, ResponseLike
from mrf_honest.registry import (
AttemptKind,
Registry,
RegistryError,
discover_domain,
fetch_and_record,
)
NOW = datetime(2026, 8, 9, tzinfo=UTC)
class Response:
def __init__(
self,
body: bytes,
*,
status: int = 200,
headers: dict[str, str] | None = None,
url: str = "https://hospital.test/cms-hpt.txt",
) -> None:
self.body = body
self.status = status
self.headers = headers or {}
self.url = url
self.position = 0
self.read_calls = 0
def read(self, amount: int = -1) -> bytes:
self.read_calls += 1
if amount < 0:
amount = len(self.body) - self.position
chunk = self.body[self.position : self.position + amount]
self.position += len(chunk)
return chunk
def geturl(self) -> str:
return self.url
def close(self) -> None:
pass
class OneResponse:
def __init__(self, response: ResponseLike) -> None:
self.response = response
self.request: Request | None = None
def __call__(self, request: Request, *, timeout: float) -> ResponseLike:
self.request = request
return self.response
def policy(*, max_bytes: int = 1 << 30) -> FetchPolicy:
return FetchPolicy(contact="owner@example.test", retries=0, max_bytes=max_bytes)
def clock() -> datetime:
return NOW
def test_discover_domain_composes_fetch_parser_and_append_only_log(tmp_path: Path) -> None:
text = b"\n".join(
[
b"location-name: Hospital",
b"source-page-url: https://hospital.test/prices",
b"mrf-url: https://hospital.test/123456789_hospital_standardcharges.json",
b"contact-name: Hospital MRF Team",
b"contact-email: mrf@hospital.test",
]
)
opener = OneResponse(Response(text))
registry = Registry(tmp_path / "registry.jsonl")
record = discover_domain(
"hospital.test",
registry=registry,
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(),
opener=opener,
clock=clock,
)
assert record.kind is AttemptKind.DISCOVERY
assert record.url == "https://hospital.test/cms-hpt.txt"
assert record.ok and record.discovery is not None
assert record.discovery.location_name == "Hospital"
assert record.discovery.mrf_url is not None
assert record.discovery.contact_name == "Hospital MRF Team"
assert record.discovery.contact_email == "mrf@hospital.test"
assert opener.request is not None
assert tuple(registry) == (record,)
assert registry.path.read_text(encoding="utf-8").count("\n") == 1
def test_registry_round_trips_multiple_discovery_entries_and_extras(tmp_path: Path) -> None:
text = b"\n".join(
[
b"location-name: Hospital East",
b"source-page-url: https://hospital.test/prices",
b"mrf-url: https://hospital.test/east.json",
b"contact-name: East Team",
b"contact-email: east@hospital.test",
b"vendor-id: east-1",
b"",
b"location-name: Hospital West",
b"source-page-url: https://hospital.test/prices",
b"mrf-url: https://hospital.test/west.json",
b"contact-name: West Team",
b"contact-email: west@hospital.test",
b"vendor-id: west-2",
]
)
registry = Registry(tmp_path / "registry.jsonl")
record = discover_domain(
"hospital.test",
registry=registry,
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(),
opener=OneResponse(Response(text)),
clock=clock,
)
loaded = registry.records()[0]
assert loaded == record
assert loaded.discovery is not None
assert len(loaded.discovery.entries) == 2
assert loaded.discovery.entries[0].contact_email == "east@hospital.test"
assert loaded.discovery.entries[0].extra_fields == (("vendor-id", "east-1"),)
assert loaded.discovery.entries[1].contact_name == "West Team"
assert loaded.discovery.entries[1].extra_fields == (("vendor-id", "west-2"),)
assert loaded.to_dict()["version"] == 2
def test_discovery_with_missing_required_contact_fields_is_not_ok(tmp_path: Path) -> None:
record = discover_domain(
"hospital.test",
registry=Registry(tmp_path / "registry.jsonl"),
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(),
opener=OneResponse(
Response(
b"\n".join(
[
b"location-name: Hospital",
b"source-page-url: https://hospital.test/prices",
b"mrf-url: https://hospital.test/prices.json",
]
)
)
),
clock=clock,
)
assert record.discovery is not None and record.discovery.usable
assert "no contact-name field" in record.discovery.problems
assert "no contact-email field" in record.discovery.problems
assert not record.ok
def test_registry_reads_legacy_v1_single_discovery_without_inventing_contacts(
tmp_path: Path,
) -> None:
registry = Registry(tmp_path / "registry.jsonl")
record = discover_domain(
"hospital.test",
registry=registry,
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(),
opener=OneResponse(
Response(
b"\n".join(
[
b"location-name: Hospital",
b"source-page-url: https://hospital.test/prices",
b"mrf-url: https://hospital.test/prices.json",
b"contact-name: MRF Team",
b"contact-email: mrf@hospital.test",
]
)
)
),
clock=clock,
)
current = record.to_dict()
current["version"] = 1
current_discovery = current["discovery"]
assert isinstance(current_discovery, dict)
current_entries = current_discovery["entries"]
assert isinstance(current_entries, list)
current_entry = current_entries[0]
assert isinstance(current_entry, dict)
current["discovery"] = {
"domain": current_discovery["domain"],
"location_name": current_entry["location_name"],
"source_page_url": current_entry["source_page_url"],
"mrf_url": current_entry["mrf_url"],
"extra_fields": [["legacy-key", "legacy-value"]],
"problems": ["legacy parse problem"],
}
registry.path.write_text(json.dumps(current) + "\n", encoding="utf-8")
loaded = registry.records()[0]
assert loaded.discovery is not None
assert len(loaded.discovery.entries) == 1
assert loaded.discovery.contact_name is None
assert loaded.discovery.contact_email is None
assert loaded.discovery.extra_fields == (("legacy-key", "legacy-value"),)
assert loaded.discovery.problems == ("legacy parse problem",)
assert not loaded.ok
def test_failed_fetch_is_still_dated_and_recorded(tmp_path: Path) -> None:
registry = Registry(tmp_path / "registry.jsonl")
record = fetch_and_record(
"hospital.test",
"https://hospital.test/missing.json",
registry=registry,
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(),
opener=OneResponse(
Response(b"missing", status=404, url="https://hospital.test/missing.json")
),
clock=clock,
)
assert record.kind is AttemptKind.FETCH
assert record.fetch.status is FetchStatus.HTTP_ERROR
assert not record.ok
assert record.attempted_at == "2026-08-09T00:00:00Z"
assert registry.records() == (record,)
def test_discovery_has_a_small_independent_download_ceiling(tmp_path: Path) -> None:
response = Response(b"unused", headers={"Content-Length": str((1 << 20) + 1)})
record = discover_domain(
"hospital.test",
registry=Registry(tmp_path / "registry.jsonl"),
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(max_bytes=1 << 30),
opener=OneResponse(response),
clock=clock,
)
assert record.fetch.status is FetchStatus.TOO_LARGE
assert response.read_calls == 0
assert record.discovery is None
def test_invalid_utf8_discovery_is_recorded_as_a_parse_problem(tmp_path: Path) -> None:
record = discover_domain(
"hospital.test",
registry=Registry(tmp_path / "registry.jsonl"),
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(),
opener=OneResponse(Response(b"\xff\xfe")),
clock=clock,
)
assert record.fetch.ok
assert record.discovery is None
assert "UTF-8" in record.problems[0]
def test_empty_and_malformed_registries_are_distinguished(tmp_path: Path) -> None:
path = tmp_path / "registry.jsonl"
registry = Registry(path)
assert registry.records() == ()
path.write_text("not-json\n", encoding="utf-8")
with pytest.raises(RegistryError, match="line 1"):
registry.records()
def test_invalid_utf8_registry_is_a_named_read_error(tmp_path: Path) -> None:
path = tmp_path / "registry.jsonl"
path.write_bytes(b"\xff\n")
with pytest.raises(RegistryError, match="could not read registry"):
Registry(path).records()
def test_registry_rejects_nested_identity_mismatch(tmp_path: Path) -> None:
registry = Registry(tmp_path / "registry.jsonl")
record = fetch_and_record(
"hospital.test",
"https://hospital.test/prices.json",
registry=registry,
cache_dir=tmp_path / "cache",
politeness=robots_fixtures.politeness(),
policy=policy(),
opener=OneResponse(Response(b"{}", url="https://hospital.test/prices.json")),
clock=clock,
)
data = record.to_dict()
data["url"] = "https://different.test/prices.json"
registry.path.write_text(json.dumps(data) + "\n", encoding="utf-8")
with pytest.raises(RegistryError, match="identity do not match"):
registry.records()