| 1 | """The patent lane against USPTO Patent Public Search, replayed offline. |
| 2 | |
| 3 | The fixtures hold real responses recorded on 2026-11-13 for the window |
| 4 | 2026-10-14 to 2026-11-13. The lists are trimmed to their first rows, so the |
| 5 | fake answers ``numFound`` with the number of rows it holds unless a test says |
| 6 | otherwise. Rows and documents the live data did not have on that day are |
| 7 | built here from a recorded one. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import copy |
| 13 | import json |
| 14 | import re |
| 15 | from pathlib import Path |
| 16 | from types import SimpleNamespace |
| 17 | |
| 18 | import pytest |
| 19 | from lib import health, http, patent_digest, patents |
| 20 | from lib.company_names import name_key |
| 21 | |
| 22 | FIXTURES = Path(__file__).parent / "fixtures" |
| 23 | SESSION = json.loads((FIXTURES / "ppubs_session.json").read_text(encoding="utf-8")) |
| 24 | LISTS = json.loads((FIXTURES / "ppubs_lists.json").read_text(encoding="utf-8"))["lists"] |
| 25 | DETAILS = json.loads((FIXTURES / "ppubs_details.json").read_text(encoding="utf-8"))["details"] |
| 26 | |
| 27 | DATE_FROM = "2026-10-14" |
| 28 | DATE_TO = "2026-11-13" |
| 29 | PDF = "https://image-ppubs.uspto.gov/dirsearch-public/print/downloadPdf/" |
| 30 | APPLE = {"company": "Apple Inc."} |
| 31 | |
| 32 | |
| 33 | def recorded(name: str, database: str) -> list[dict]: |
| 34 | return copy.deepcopy(LISTS[f"{name}|{database}"]["patents"]) |
| 35 | |
| 36 | |
| 37 | def make_row( |
| 38 | guid: str, |
| 39 | published: str, |
| 40 | *, |
| 41 | name: str | list[str] | None = "Apple Inc.", |
| 42 | kind: str = "A1", |
| 43 | cpc: str | None = "G06F3/01", |
| 44 | filed: str = "2026-01-15", |
| 45 | related: list[str] | None = None, |
| 46 | ) -> dict: |
| 47 | """A list row in the recorded shape.""" |
| 48 | names = name if isinstance(name, list) or name is None else [name] |
| 49 | grant = not kind.startswith("A") |
| 50 | return { |
| 51 | "guid": guid, |
| 52 | "type": "USPAT" if grant else "US-PGPUB", |
| 53 | "kindCode": [kind], |
| 54 | "datePublished": f"{published}T00:00:00Z", |
| 55 | "inventionTitle": f"Title of {guid}", |
| 56 | "applicantName": names, |
| 57 | "assigneeName": names if grant else None, |
| 58 | "applicationNumber": "19/000001", |
| 59 | "applicationFilingDate": [f"{filed}T00:00:00Z"], |
| 60 | "relatedApplFilingDate": [f"{day}T00:00:00Z" for day in related] if related else None, |
| 61 | "priorityClaimsDate": None, |
| 62 | "cpcInventiveFlattened": cpc, |
| 63 | "familyIdentifierCur": 1, |
| 64 | "publicationReferenceDocumentNumber": guid.split("-")[1], |
| 65 | } |
| 66 | |
| 67 | |
| 68 | def original_detail(guid: str) -> dict: |
| 69 | """A document with no parent application, for guids that were not recorded.""" |
| 70 | return { |
| 71 | "guid": guid, |
| 72 | "abstractHtml": f"Abstract of {guid}.", |
| 73 | "claimsHtml": f"<b>1</b>. A thing of {guid}. <br /> <b>2</b>. The thing of claim 1.", |
| 74 | "applicantCity": ["Cupertino"], |
| 75 | "applicantState": ["CA"], |
| 76 | "applicantCountry": ["US"], |
| 77 | "cpcInventive": ["G06F3/01 20130101"], |
| 78 | "continuityData": None, |
| 79 | } |
| 80 | |
| 81 | |
| 82 | class FakeUSPTO: |
| 83 | """Stands in for ``lib.http`` and answers from the recorded fixtures. |
| 84 | |
| 85 | A search is answered with the recorded lists of every quoted name in the |
| 86 | query (or the rows given in ``lists``) when its dates are the run's |
| 87 | window, and with ``baseline`` otherwise. |
| 88 | """ |
| 89 | |
| 90 | def __init__( |
| 91 | self, |
| 92 | *, |
| 93 | lists: dict[str, list[dict]] | None = None, |
| 94 | baseline: list[dict] | None = None, |
| 95 | details: dict[str, dict] | None = None, |
| 96 | window: tuple[str, str] = (DATE_FROM, DATE_TO), |
| 97 | num_found: dict[str, int] | None = None, |
| 98 | session_headers: dict | None = None, |
| 99 | session_body: object = None, |
| 100 | errors: dict[tuple[str, int], Exception] | None = None, |
| 101 | seconds: dict[str, float] | None = None, |
| 102 | ): |
| 103 | self.lists = lists |
| 104 | self.baseline = baseline or [] |
| 105 | self.details = {**DETAILS, **(details or {})} |
| 106 | self.window = tuple(day.replace("-", "") for day in window) |
| 107 | self.num_found = num_found or {} |
| 108 | self.session_headers = SESSION["headers"] if session_headers is None else session_headers |
| 109 | self.session_body = SESSION["body"] if session_body is None else session_body |
| 110 | # ("session" | "search" | "baseline" | "detail", nth call of that kind) -> error |
| 111 | self.errors = errors or {} |
| 112 | # kind -> seconds each call of that kind takes. When given, the lane |
| 113 | # reads a clock only these calls move, and a call that ends at or past |
| 114 | # its deadline fails the way lib.http fails it. |
| 115 | self.seconds = seconds |
| 116 | self.now = 1000.0 |
| 117 | self.calls: list[dict] = [] |
| 118 | |
| 119 | def install(self, monkeypatch) -> FakeUSPTO: |
| 120 | monkeypatch.setattr( |
| 121 | patents, "http", SimpleNamespace(post=self.post, get=self.get, HTTPError=http.HTTPError), |
| 122 | ) |
| 123 | if self.seconds is not None: |
| 124 | monkeypatch.setattr(patents, "time", SimpleNamespace(monotonic=lambda: self.now)) |
| 125 | return self |
| 126 | |
| 127 | def of(self, kind: str) -> list[dict]: |
| 128 | return [call for call in self.calls if call["kind"] == kind] |
| 129 | |
| 130 | def _note(self, kind: str, **call) -> None: |
| 131 | self.calls.append({"kind": kind, **call}) |
| 132 | if self.seconds is not None: |
| 133 | self.now += self.seconds.get(kind, 0.0) |
| 134 | if self.now >= call["kwargs"]["deadline_monotonic"]: |
| 135 | raise http.DeadlineExceeded() |
| 136 | error = self.errors.get((kind, len(self.of(kind)))) |
| 137 | if error is not None: |
| 138 | raise error |
| 139 | |
| 140 | def post(self, url, json_data, headers=None, **kwargs): |
| 141 | if url.endswith("/api/users/me/session"): |
| 142 | self._note("session", url=url, body=json_data, headers=headers, kwargs=kwargs) |
| 143 | return self.session_body, self.session_headers |
| 144 | assert url == "https://ppubs.uspto.gov/api/searches/searchWithBeFamily", url |
| 145 | query = json_data["query"]["q"] |
| 146 | database = json_data["query"]["databaseFilters"][0]["databaseName"] |
| 147 | dates = tuple(re.search(r'@pd>="(\d{8})"<="(\d{8})"', query).groups()) |
| 148 | kind = "search" if dates == self.window else "baseline" |
| 149 | self._note( |
| 150 | kind, url=url, body=json_data, headers=headers, kwargs=kwargs, |
| 151 | query=query, database=database, start=json_data["start"], |
| 152 | ) |
| 153 | if kind == "baseline": |
| 154 | rows = self.baseline |
| 155 | elif self.lists is not None: |
| 156 | rows = self.lists.get(database, []) |
| 157 | else: |
| 158 | asked = {name_key(phrase) for phrase in re.findall(r'"([^"]+)"', query.split(" AND ")[0])} |
| 159 | rows = [ |
| 160 | row |
| 161 | for key, value in LISTS.items() |
| 162 | if key.endswith(f"|{database}") and name_key(key.split("|")[0]) in asked |
| 163 | for row in value["patents"] |
| 164 | ] |
| 165 | start, count = json_data["start"], json_data["pageCount"] |
| 166 | body = { |
| 167 | "numFound": self.num_found.get(database, len(rows)), |
| 168 | "patents": copy.deepcopy(rows[start:start + count]), |
| 169 | } |
| 170 | return (body, {}) if kwargs.get("return_headers") else body |
| 171 | |
| 172 | def get(self, url, headers=None, **kwargs): |
| 173 | match = re.fullmatch( |
| 174 | r"https://ppubs\.uspto\.gov/api/patents/highlight/([^?]+)" |
| 175 | r"\?queryId=1&source=(US-PGPUB|USPAT)&includeSections=true&uniqueId=", |
| 176 | url, |
| 177 | ) |
| 178 | assert match, url |
| 179 | guid = match.group(1) |
| 180 | self._note("detail", url=url, headers=headers, kwargs=kwargs, guid=guid, database=match.group(2)) |
| 181 | body = copy.deepcopy(self.details.get(guid) or original_detail(guid)) |
| 182 | return (body, {}) if kwargs.get("return_headers") else body |
| 183 | |
| 184 | def detail_guids(self) -> list[str]: |
| 185 | return [call["guid"] for call in self.of("detail")] |
| 186 | |
| 187 | |
| 188 | def run(company: dict = APPLE, **kwargs) -> dict: |
| 189 | return patents.fetch_patent_data(company, DATE_FROM, DATE_TO, **kwargs) |
| 190 | |
| 191 | |
| 192 | def guid_of(url: str) -> str: |
| 193 | return url.removeprefix(PDF) |
| 194 | |
| 195 | |
| 196 | # --- requests --------------------------------------------------------------- |
| 197 | |
| 198 | |
| 199 | def test_requests_follow_the_recorded_shapes(monkeypatch): |
| 200 | fake = FakeUSPTO().install(monkeypatch) |
| 201 | |
| 202 | result = run() |
| 203 | |
| 204 | assert "artifact" in result |
| 205 | [session] = fake.of("session") |
| 206 | assert session["url"] == "https://ppubs.uspto.gov/api/users/me/session" |
| 207 | assert session["body"] == -1 |
| 208 | assert session["kwargs"]["return_headers"] is True |
| 209 | applications, grants = fake.of("search") |
| 210 | assert applications["query"] == '("apple").aanm. AND @pd>="20261014"<="20261113"' |
| 211 | assert grants["query"] == '("apple").asnm. AND @pd>="20261014"<="20261113"' |
| 212 | assert (applications["database"], grants["database"]) == ("US-PGPUB", "USPAT") |
| 213 | body = applications["body"] |
| 214 | assert body["docFamilyFiltering"] == "noFiltering" |
| 215 | assert (body["start"], body["pageCount"], body["sort"]) == (0, 500, "date_publ desc") |
| 216 | assert body["query"]["caseId"] == SESSION["body"]["userCase"]["caseId"] |
| 217 | for call in fake.calls[1:]: |
| 218 | assert call["headers"]["X-Access-Token"] == "REDACTED-TOKEN" |
| 219 | assert fake.of("detail")[0]["database"] == "US-PGPUB" |
| 220 | assert len(fake.of("detail")) == 12 |
| 221 | |
| 222 | |
| 223 | def test_every_request_is_bounded_by_the_budget(monkeypatch): |
| 224 | fake = FakeUSPTO().install(monkeypatch) |
| 225 | |
| 226 | run(budget_seconds=5.0) |
| 227 | |
| 228 | assert fake.calls |
| 229 | lane = [call for call in fake.calls if call["kind"] != "baseline"] |
| 230 | deadlines = {call["kwargs"]["deadline_monotonic"] for call in lane} |
| 231 | assert len(deadlines) == 1 |
| 232 | # The baseline search has its own deadline, earlier than the lane's. |
| 233 | [baseline] = fake.of("baseline") |
| 234 | assert baseline["kwargs"]["deadline_monotonic"] < min(deadlines) |
| 235 | for call in fake.calls: |
| 236 | assert 0 < call["kwargs"]["timeout"] <= 5.0 |
| 237 | assert call["kwargs"]["retries"] <= 2 |
| 238 | # lib.http gives up on the 429 that brings the count to this number, |
| 239 | # so 2 means one honoured wait. |
| 240 | assert call["kwargs"]["max_429_retries"] == 2 |
| 241 | |
| 242 | |
| 243 | def test_request_timeout_is_at_most_eight_seconds(monkeypatch): |
| 244 | fake = FakeUSPTO().install(monkeypatch) |
| 245 | |
| 246 | run() |
| 247 | |
| 248 | assert max(call["kwargs"]["timeout"] for call in fake.calls) <= 8.0 |
| 249 | |
| 250 | |
| 251 | def test_a_spent_budget_is_an_error_and_sends_nothing(monkeypatch): |
| 252 | fake = FakeUSPTO().install(monkeypatch) |
| 253 | |
| 254 | result = run(budget_seconds=0) |
| 255 | |
| 256 | assert result["state"] == "error" |
| 257 | assert result["detail"] |
| 258 | assert fake.calls == [] |
| 259 | |
| 260 | |
| 261 | def test_a_past_window_sends_its_own_dates_and_a_baseline_that_ends_before_it(monkeypatch): |
| 262 | fake = FakeUSPTO(window=("2025-03-01", "2025-03-31")).install(monkeypatch) |
| 263 | |
| 264 | result = patents.fetch_patent_data(APPLE, "2025-03-01", "2025-03-31") |
| 265 | |
| 266 | assert result["artifact"]["window"] == {"from": "2025-03-01", "to": "2025-03-31"} |
| 267 | assert [call["query"] for call in fake.of("search")] == [ |
| 268 | '("apple").aanm. AND @pd>="20250301"<="20250331"', |
| 269 | '("apple").asnm. AND @pd>="20250301"<="20250331"', |
| 270 | ] |
| 271 | [baseline] = fake.of("baseline") |
| 272 | assert baseline["query"] == '("apple").aanm. AND @pd>="20240301"<="20250228"' |
| 273 | assert baseline["database"] == "US-PGPUB" |
| 274 | assert (baseline["start"], baseline["body"]["pageCount"]) == (0, 500) |
| 275 | |
| 276 | |
| 277 | def test_a_search_larger_than_two_pages_marks_the_counts_as_floors(monkeypatch): |
| 278 | fake = FakeUSPTO(num_found={"US-PGPUB": 1200}).install(monkeypatch) |
| 279 | |
| 280 | counts = run()["artifact"]["counts"] |
| 281 | |
| 282 | assert counts["floor"] is True |
| 283 | assert [(call["database"], call["start"]) for call in fake.of("search")] == [ |
| 284 | ("US-PGPUB", 0), ("US-PGPUB", 500), ("USPAT", 0), |
| 285 | ] |
| 286 | |
| 287 | |
| 288 | def test_a_search_that_fits_two_pages_reads_both_and_is_not_a_floor(monkeypatch): |
| 289 | rows = [make_row(f"US-2026030{n:04d}-A1", "2026-11-05") for n in range(600)] |
| 290 | fake = FakeUSPTO(lists={"US-PGPUB": rows}).install(monkeypatch) |
| 291 | |
| 292 | artifact = run()["artifact"] |
| 293 | |
| 294 | assert artifact["counts"]["floor"] is False |
| 295 | assert artifact["counts"]["applications"] == 600 |
| 296 | assert [call["start"] for call in fake.of("search")] == [0, 500, 0] |
| 297 | |
| 298 | |
| 299 | # --- sign-in and failures --------------------------------------------------- |
| 300 | |
| 301 | |
| 302 | def test_a_session_without_a_token_header_is_sign_in(monkeypatch): |
| 303 | fake = FakeUSPTO(session_headers={}).install(monkeypatch) |
| 304 | |
| 305 | result = run() |
| 306 | |
| 307 | assert result["state"] == "signin" |
| 308 | assert result["detail"] |
| 309 | assert [call["kind"] for call in fake.calls] == ["session"] |
| 310 | |
| 311 | |
| 312 | @pytest.mark.parametrize("status", [401, 403]) |
| 313 | def test_a_refused_session_is_sign_in(monkeypatch, status): |
| 314 | error = http.HTTPError(f"HTTP {status}: refused", status) |
| 315 | fake = FakeUSPTO(errors={("session", 1): error}).install(monkeypatch) |
| 316 | |
| 317 | result = run() |
| 318 | |
| 319 | assert set(result) == {"state", "detail"} |
| 320 | assert result["state"] == "signin" |
| 321 | assert [call["kind"] for call in fake.calls] == ["session"] |
| 322 | |
| 323 | |
| 324 | def test_a_session_without_a_case_id_is_sign_in(monkeypatch): |
| 325 | FakeUSPTO(session_body={"userCase": None, "sessionTimeOutTime": 1800}).install(monkeypatch) |
| 326 | |
| 327 | assert run()["state"] == "signin" |
| 328 | |
| 329 | |
| 330 | def test_a_sign_in_banner_beside_a_valid_token_proceeds(monkeypatch): |
| 331 | body = { |
| 332 | **SESSION["body"], |
| 333 | "message": "Patent Public Search will soon require sign in with a USPTO.gov account.", |
| 334 | } |
| 335 | FakeUSPTO(session_body=body).install(monkeypatch) |
| 336 | |
| 337 | assert run()["artifact"]["status"] == "digest" |
| 338 | |
| 339 | |
| 340 | def test_a_session_body_that_is_not_json_is_an_error(monkeypatch): |
| 341 | error = http.HTTPError( |
| 342 | "Invalid JSON response: Expecting value: line 1 column 1 (char 0)", |
| 343 | outcome_state=health.SCHEMA_DRIFT, |
| 344 | ) |
| 345 | FakeUSPTO(errors={("session", 1): error}).install(monkeypatch) |
| 346 | |
| 347 | result = run() |
| 348 | |
| 349 | assert result["state"] == "error" |
| 350 | assert "Invalid JSON" in result["detail"] |
| 351 | |
| 352 | |
| 353 | def test_a_session_body_that_is_not_an_object_is_an_error(monkeypatch): |
| 354 | FakeUSPTO(session_body="<html>Sign in</html>").install(monkeypatch) |
| 355 | |
| 356 | assert run()["state"] == "error" |
| 357 | |
| 358 | |
| 359 | def test_a_refused_search_is_sign_in(monkeypatch): |
| 360 | error = http.HTTPError("HTTP 403: Forbidden", 403) |
| 361 | FakeUSPTO(errors={("search", 2): error}).install(monkeypatch) |
| 362 | |
| 363 | assert run()["state"] == "signin" |
| 364 | |
| 365 | |
| 366 | def test_a_failed_search_is_an_error(monkeypatch): |
| 367 | error = http.HTTPError("HTTP 500: Internal Server Error", 500) |
| 368 | fake = FakeUSPTO(errors={("search", 1): error}).install(monkeypatch) |
| 369 | |
| 370 | result = run() |
| 371 | |
| 372 | assert result == {"state": "error", "detail": "HTTP 500: Internal Server Error"} |
| 373 | assert fake.of("detail") == [] |
| 374 | |
| 375 | |
| 376 | def test_a_search_answer_in_another_shape_is_an_error(monkeypatch): |
| 377 | fake = FakeUSPTO().install(monkeypatch) |
| 378 | monkeypatch.setattr( |
| 379 | patents.http, "post", |
| 380 | lambda url, json_data, headers=None, **kwargs: ( |
| 381 | fake.post(url, json_data, headers, **kwargs) |
| 382 | if url.endswith("/session") else ({"patents": "none"}, {}) |
| 383 | ), |
| 384 | ) |
| 385 | |
| 386 | assert run()["state"] == "error" |
| 387 | |
| 388 | |
| 389 | def test_a_deadline_that_passes_during_the_searches_is_an_error(monkeypatch): |
| 390 | FakeUSPTO(errors={("search", 2): http.DeadlineExceeded()}).install(monkeypatch) |
| 391 | |
| 392 | result = run() |
| 393 | |
| 394 | assert result["state"] == "error" |
| 395 | assert "deadline" in result["detail"].lower() |
| 396 | |
| 397 | |
| 398 | def test_a_detail_refused_before_any_entry_is_sign_in(monkeypatch): |
| 399 | error = http.HTTPError("HTTP 401: Unauthorized", 401) |
| 400 | FakeUSPTO(errors={("detail", 1): error}).install(monkeypatch) |
| 401 | |
| 402 | assert run()["state"] == "signin" |
| 403 | |
| 404 | |
| 405 | def test_a_detail_refused_after_entries_exist_is_partial(monkeypatch): |
| 406 | error = http.HTTPError("HTTP 401: Unauthorized", 401) |
| 407 | fake = FakeUSPTO(errors={("detail", 3): error}).install(monkeypatch) |
| 408 | |
| 409 | artifact = run()["artifact"] |
| 410 | |
| 411 | assert len(artifact["entries"]) == 2 |
| 412 | assert artifact["partial"] == {"missing_text": 10} |
| 413 | assert len(fake.of("detail")) == 3 |
| 414 | |
| 415 | |
| 416 | def test_a_429_on_the_fifth_detail_stops_fetching_and_keeps_the_counts(monkeypatch): |
| 417 | clean = FakeUSPTO().install(monkeypatch) |
| 418 | whole = run()["artifact"] |
| 419 | error = http.HTTPError("HTTP 429: Too Many Requests", 429) |
| 420 | fake = FakeUSPTO(errors={("detail", 5): error}).install(monkeypatch) |
| 421 | |
| 422 | artifact = run()["artifact"] |
| 423 | |
| 424 | assert len(fake.of("detail")) == 5 |
| 425 | assert [entry["guid"] for entry in artifact["entries"]] == clean.detail_guids()[:4] |
| 426 | assert artifact["partial"] == {"missing_text": 8} |
| 427 | # The candidates that lost their text lead the index, in selection order. |
| 428 | assert [guid_of(item["url"]) for item in artifact["index"][:8]] == [ |
| 429 | guid.split("-")[1] for guid in clean.detail_guids()[4:12] |
| 430 | ] |
| 431 | assert len(artifact["index"]) == patents.MAX_INDEX |
| 432 | assert artifact["counts"] == whole["counts"] |
| 433 | assert artifact["groups"] == whole["groups"] |
| 434 | assert artifact["status"] == "digest" |
| 435 | assert whole["partial"] is None |
| 436 | |
| 437 | |
| 438 | def test_a_deadline_that_passes_during_detail_fetches_is_partial(monkeypatch): |
| 439 | fake = FakeUSPTO(errors={("detail", 3): http.DeadlineExceeded()}).install(monkeypatch) |
| 440 | |
| 441 | artifact = run()["artifact"] |
| 442 | |
| 443 | assert len(artifact["entries"]) == 2 |
| 444 | assert artifact["partial"] == {"missing_text": 10} |
| 445 | assert len(fake.of("detail")) == 3 |
| 446 | |
| 447 | |
| 448 | def twelve_candidates() -> dict[str, list[dict]]: |
| 449 | return {"US-PGPUB": [make_row(f"US-202603500{n:02d}-A1", f"2026-11-{12 - n:02d}") for n in range(12)]} |
| 450 | |
| 451 | |
| 452 | def note_line(artifact: dict) -> str: |
| 453 | lines = patent_digest.digest_lines( |
| 454 | artifact, link=lambda _url, title: title, untrusted=lambda text, _limit: text, |
| 455 | ) |
| 456 | return next(line for line in lines if line.startswith("- Note:")) |
| 457 | |
| 458 | |
| 459 | def test_the_lane_and_the_fetch_default_have_a_ninety_second_budget(monkeypatch): |
| 460 | fake = FakeUSPTO(seconds={}).install(monkeypatch) |
| 461 | |
| 462 | run() |
| 463 | |
| 464 | assert patents.LANE_BUDGET_SECONDS == 90.0 |
| 465 | assert fake.of("session")[0]["kwargs"]["deadline_monotonic"] == fake.now + 90.0 |
| 466 | |
| 467 | |
| 468 | def test_a_read_that_times_out_mid_list_does_not_end_the_reading(monkeypatch): |
| 469 | timeout = http.HTTPError("Request timed out", outcome_state=health.TIMEOUT) |
| 470 | fake = FakeUSPTO(lists=twelve_candidates(), errors={("detail", 3): timeout}).install(monkeypatch) |
| 471 | |
| 472 | artifact = run()["artifact"] |
| 473 | |
| 474 | assert len(fake.of("detail")) == 12 |
| 475 | third = fake.detail_guids()[2] |
| 476 | assert len(artifact["entries"]) == 11 |
| 477 | assert third not in [entry["guid"] for entry in artifact["entries"]] |
| 478 | assert all(entry["abstract"] and entry["first_claim"] for entry in artifact["entries"]) |
| 479 | assert [guid_of(item["url"]) for item in artifact["index"]] == [third.split("-")[1]] |
| 480 | assert artifact["partial"] == {"missing_text": 1} |
| 481 | assert note_line(artifact).startswith( |
| 482 | "- Note: 1 of the filings listed by title only has no abstract or claim text", |
| 483 | ) |
| 484 | |
| 485 | |
| 486 | def test_a_budget_that_runs_out_after_five_reads_keeps_their_text(monkeypatch): |
| 487 | fake = FakeUSPTO(lists=twelve_candidates(), seconds={"detail": 17.0}).install(monkeypatch) |
| 488 | |
| 489 | artifact = run()["artifact"] |
| 490 | |
| 491 | # The sixth read ends past the lane's ninety seconds. |
| 492 | assert len(fake.of("detail")) == 6 |
| 493 | assert len(artifact["entries"]) == 5 |
| 494 | assert all(entry["abstract"] and entry["first_claim"] for entry in artifact["entries"]) |
| 495 | assert len(artifact["index"]) == 7 |
| 496 | assert artifact["partial"] == {"missing_text": 7} |
| 497 | assert note_line(artifact).startswith( |
| 498 | "- Note: 7 of the filings listed by title only have no abstract or claim text", |
| 499 | ) |
| 500 | |
| 501 | |
| 502 | def test_every_read_failing_leaves_a_titles_only_digest_that_says_so(monkeypatch): |
| 503 | error = http.HTTPError("HTTP 500: Internal Server Error", 500) |
| 504 | errors = {("detail", n): error for n in range(1, 13)} |
| 505 | fake = FakeUSPTO(lists=twelve_candidates(), errors=errors).install(monkeypatch) |
| 506 | |
| 507 | artifact = run()["artifact"] |
| 508 | |
| 509 | assert len(fake.of("detail")) == 12 |
| 510 | assert artifact["entries"] == [] |
| 511 | assert len(artifact["index"]) == 12 |
| 512 | assert artifact["status"] == "digest" |
| 513 | assert artifact["partial"] == {"missing_text": 12} |
| 514 | assert note_line(artifact).startswith( |
| 515 | "- Note: 12 of the filings listed by title only have no abstract or claim text", |
| 516 | ) |
| 517 | |
| 518 | |
| 519 | def test_a_failed_baseline_search_still_builds_the_digest(monkeypatch): |
| 520 | error = http.HTTPError("HTTP 500: Internal Server Error", 500) |
| 521 | FakeUSPTO(errors={("baseline", 1): error}).install(monkeypatch) |
| 522 | |
| 523 | artifact = run()["artifact"] |
| 524 | |
| 525 | assert len(artifact["entries"]) == 12 |
| 526 | published = [entry["published"] for entry in artifact["entries"]] |
| 527 | assert published == sorted(published, reverse=True) |
| 528 | |
| 529 | |
| 530 | @pytest.mark.parametrize("company", [None, "Apple", {}, {"company": ""}]) |
| 531 | def test_a_company_that_cannot_be_searched_is_an_error(monkeypatch, company): |
| 532 | fake = FakeUSPTO().install(monkeypatch) |
| 533 | |
| 534 | result = patents.fetch_patent_data(company, DATE_FROM, DATE_TO) |
| 535 | |
| 536 | assert result["state"] == "error" |
| 537 | assert fake.of("search") == [] |
| 538 | |
| 539 | |
| 540 | def test_an_unexpected_exception_becomes_the_error_state(monkeypatch): |
| 541 | def boom(*_args, **_kwargs): |
| 542 | raise RuntimeError("boom") |
| 543 | |
| 544 | monkeypatch.setattr( |
| 545 | patents, "http", SimpleNamespace(post=boom, get=boom, HTTPError=http.HTTPError), |
| 546 | ) |
| 547 | |
| 548 | assert run() == {"state": "error", "detail": "RuntimeError: boom"} |
| 549 | |
| 550 | |
| 551 | def test_bad_dates_are_an_error(monkeypatch): |
| 552 | FakeUSPTO().install(monkeypatch) |
| 553 | |
| 554 | assert patents.fetch_patent_data(APPLE, "last month", DATE_TO)["state"] == "error" |
| 555 | |
| 556 | |
| 557 | def test_without_a_test_transport_the_lane_sends_nothing_and_finds_nothing(): |
| 558 | """The suite-wide default: an engine run in a test must not reach USPTO.""" |
| 559 | assert patents.http is not http |
| 560 | |
| 561 | assert run() == {"state": "none", "other_names": []} |
| 562 | |
| 563 | |
| 564 | def test_source_name(): |
| 565 | assert patents.SOURCE == "patents" |
| 566 |