| 1 | """When a run starts the patent lane, on which company, and what it records. |
| 2 | |
| 3 | Every test drives the command line's own main runner. ``patents.fetch_patent_data`` |
| 4 | is a stand-in that records its arguments, so nothing here opens a socket. |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import copy |
| 10 | import sys |
| 11 | import threading |
| 12 | import time |
| 13 | from types import SimpleNamespace |
| 14 | from unittest import mock |
| 15 | |
| 16 | import pytest |
| 17 | |
| 18 | import last30days as cli |
| 19 | from lib import hosted, patents, pipeline, resolve, schema |
| 20 | |
| 21 | from tests.test_company_resolve import FakeWikidata, _subsidiary_label_requests |
| 22 | |
| 23 | COMPANY = { |
| 24 | "company": "MainBrand Inc.", |
| 25 | "company_site": "https://mainbrand.example/", |
| 26 | "company_names": ["MainBrand Labs", "MainBrand Licensing LLC"], |
| 27 | } |
| 28 | ARTIFACT = { |
| 29 | "company": "MainBrand Inc.", |
| 30 | "company_via_person": False, |
| 31 | "window": {"from": "2026-06-01", "to": "2026-06-30"}, |
| 32 | "groups": [ |
| 33 | {"name": "MainBrand Inc.", "kind": "confirmed", "applications": 4, "grants": 2}, |
| 34 | {"name": "MainBrand Licensing LLC", "kind": "name-matched", "applications": 1, "grants": 0}, |
| 35 | ], |
| 36 | "other_names": [], |
| 37 | "counts": { |
| 38 | "applications": 4, "grants": 2, "name_matched_applications": 1, |
| 39 | "name_matched_grants": 0, "first_publications": 2, |
| 40 | "name_matched_first_publications": 1, "continuing": 2, |
| 41 | "previously_published_grants": 2, "designs": 0, "other_kinds": 0, "floor": False, |
| 42 | }, |
| 43 | "entries": [], |
| 44 | "index": [], |
| 45 | "partial": None, |
| 46 | "status": "digest", |
| 47 | } |
| 48 | PLAN = { |
| 49 | "intent": "opinion", "freshness_mode": "balanced_recent", "cluster_mode": "debate", |
| 50 | "subqueries": [{ |
| 51 | "label": "primary", "search_query": "test topic", "ranking_query": "test topic", |
| 52 | "sources": ["hackernews"], "weight": 1.0, |
| 53 | }], |
| 54 | } |
| 55 | |
| 56 | |
| 57 | class FakeLane: |
| 58 | """Stands in for ``patents.fetch_patent_data``.""" |
| 59 | |
| 60 | def __init__(self, outcome=None, wait_for: threading.Event | None = None): |
| 61 | self.outcome = {"artifact": ARTIFACT} if outcome is None else outcome |
| 62 | self.wait_for = wait_for |
| 63 | self.calls: list[dict] = [] |
| 64 | |
| 65 | def __call__(self, company, date_from, date_to, config=None, *, budget_seconds=90.0): |
| 66 | self.calls.append({ |
| 67 | "company": company, "date_from": date_from, "date_to": date_to, |
| 68 | "budget_seconds": budget_seconds, |
| 69 | }) |
| 70 | if self.wait_for is not None: |
| 71 | self.wait_for.wait(10) |
| 72 | return self.outcome |
| 73 | |
| 74 | |
| 75 | def _stub_report(**kwargs) -> schema.Report: |
| 76 | topic = kwargs["topic"] |
| 77 | return schema.Report( |
| 78 | topic=topic, range_from="2026-06-01", range_to="2026-06-30", |
| 79 | generated_at="2026-06-30T12:00:00Z", |
| 80 | provider_runtime=schema.ProviderRuntime("local", "none", "none"), |
| 81 | query_plan=schema.QueryPlan("general", "recent", "none", topic, [], {}), |
| 82 | clusters=[], ranked_candidates=[], items_by_source={}, errors_by_source={}, |
| 83 | ) |
| 84 | |
| 85 | |
| 86 | def _real_window_report(real_run): |
| 87 | """The pipeline's own run, offline: its report carries the window the |
| 88 | pipeline itself derives from the lookback and the as-of date.""" |
| 89 | |
| 90 | def research(**kwargs): |
| 91 | with mock.patch.object(pipeline, "_retrieve_stream", return_value=([], {})): |
| 92 | return real_run(**{ |
| 93 | **kwargs, "mock": True, "web_backend": "none", "external_plan": PLAN, |
| 94 | "config": dict(kwargs["config"]), |
| 95 | }) |
| 96 | |
| 97 | return research |
| 98 | |
| 99 | |
| 100 | def _run( |
| 101 | monkeypatch, tmp_path, *, topic="MainBrand", args=(), config=None, companies=None, |
| 102 | lane=None, competitors_list=None, real_window=False, wikidata=None, |
| 103 | ): |
| 104 | """Run the command line. ``wikidata`` swaps the company stand-in for the |
| 105 | real resolver answering from that recorded Wikidata.""" |
| 106 | lane = lane or FakeLane() |
| 107 | reports: dict[str, schema.Report] = {} |
| 108 | build = _real_window_report(pipeline.run) if real_window else _stub_report |
| 109 | |
| 110 | def research(**kwargs): |
| 111 | reports[kwargs["topic"]] = build(**kwargs) |
| 112 | return reports[kwargs["topic"]] |
| 113 | |
| 114 | companies = {"MainBrand": COMPANY} if companies is None else companies |
| 115 | if wikidata is None: |
| 116 | company_resolver = mock.Mock( |
| 117 | side_effect=lambda name, **_kwargs: copy.deepcopy(companies.get(name, {})) |
| 118 | ) |
| 119 | else: |
| 120 | company_resolver = mock.Mock(wraps=cli.company_resolve.resolve_company) |
| 121 | monkeypatch.setattr(cli.company_resolve.http, "get", wikidata) |
| 122 | monkeypatch.setattr(patents, "fetch_patent_data", lane) |
| 123 | monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {} if config is None else config) |
| 124 | monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path / "config") |
| 125 | monkeypatch.setattr(cli.env, "CONFIG_FILE", tmp_path / "config" / ".env") |
| 126 | monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_a, **_k: {"available_sources": ["reddit"]}) |
| 127 | monkeypatch.setattr(cli.pipeline, "run", research) |
| 128 | monkeypatch.setattr(resolve, "_has_backend", lambda _config: False) |
| 129 | monkeypatch.setattr(resolve, "auto_resolve", lambda _topic, _config: {}) |
| 130 | monkeypatch.setattr( |
| 131 | resolve, "official_site_socials", lambda _site: {"x_handle": "", "github_user": ""}, |
| 132 | ) |
| 133 | monkeypatch.setattr(cli.company_resolve, "resolve_company", company_resolver) |
| 134 | monkeypatch.setattr(cli.yahoo_finance, "_is_available", lambda: False) |
| 135 | monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1") |
| 136 | monkeypatch.setenv("LAST30DAYS_MEMORY_DIR", "") |
| 137 | monkeypatch.setenv("LAST30DAYS_STORE", "") |
| 138 | argv = ["last30days.py", topic] |
| 139 | if competitors_list: |
| 140 | argv.extend(["--competitors-list", competitors_list]) |
| 141 | argv.extend(["--emit=json", "--json-profile=raw", "--save-dir=", *args]) |
| 142 | monkeypatch.setattr(sys, "argv", argv) |
| 143 | |
| 144 | assert cli.main() == 0 |
| 145 | return SimpleNamespace( |
| 146 | lane=lane, reports=reports, report=reports.get(topic), company_resolver=company_resolver, |
| 147 | ) |
| 148 | |
| 149 | |
| 150 | # --- which runs, and on which company --------------------------------------- |
| 151 | |
| 152 | |
| 153 | def test_resolved_company_run_starts_the_lane_with_that_company_and_attaches_the_artifact( |
| 154 | monkeypatch, tmp_path, |
| 155 | ): |
| 156 | observed = _run(monkeypatch, tmp_path) |
| 157 | |
| 158 | assert [call["company"] for call in observed.lane.calls] == [COMPANY] |
| 159 | assert observed.lane.calls[0]["company"]["company_names"] == COMPANY["company_names"] |
| 160 | assert observed.report.artifacts["patents"] == ARTIFACT |
| 161 | assert "patents" not in observed.report.source_status |
| 162 | |
| 163 | |
| 164 | def test_resolved_company_run_with_a_host_ticker_attaches_the_artifact_too(monkeypatch, tmp_path): |
| 165 | observed = _run(monkeypatch, tmp_path, args=["--ticker", "MAIN:MainBrand"]) |
| 166 | |
| 167 | assert [call["company"]["company"] for call in observed.lane.calls] == ["MainBrand Inc."] |
| 168 | assert observed.report.artifacts["patents"] == ARTIFACT |
| 169 | assert observed.report.artifacts["resolved"]["ticker_source"] == "host" |
| 170 | |
| 171 | |
| 172 | @pytest.mark.parametrize( |
| 173 | ("kwargs", "env_vars"), |
| 174 | [ |
| 175 | ({"competitors_list": "PeerOne,PeerTwo"}, {}), |
| 176 | ({"args": ["--mock"]}, {}), |
| 177 | ({"args": ["--hiring-signals"]}, {}), |
| 178 | ({"args": ["--quick"]}, {}), |
| 179 | ({"config": {"EXCLUDE_SOURCES": "patents"}}, {}), |
| 180 | ({}, {"LAST30DAYS_NO_PATENT_DIGEST": "1"}), |
| 181 | ], |
| 182 | ids=["comparison", "mock", "hiring-signals", "quick", "excluded", "no-patent-digest-env"], |
| 183 | ) |
| 184 | def test_runs_that_never_ask_for_patents(monkeypatch, tmp_path, kwargs, env_vars): |
| 185 | for name, value in env_vars.items(): |
| 186 | monkeypatch.setenv(name, value) |
| 187 | companies = {name: {"company": f"{name} Inc."} for name in ("MainBrand", "PeerOne", "PeerTwo")} |
| 188 | |
| 189 | observed = _run(monkeypatch, tmp_path, companies=companies, **kwargs) |
| 190 | |
| 191 | assert observed.lane.calls == [] |
| 192 | assert observed.reports |
| 193 | for report in observed.reports.values(): |
| 194 | assert "patents" not in report.artifacts |
| 195 | assert "patents" not in report.source_status |
| 196 | |
| 197 | |
| 198 | @pytest.mark.parametrize( |
| 199 | ("kwargs", "env_vars"), |
| 200 | [ |
| 201 | ({"competitors_list": "Stripe,IBM"}, {}), |
| 202 | ({"args": ["--hiring-signals"]}, {}), |
| 203 | ({"args": ["--quick"]}, {}), |
| 204 | ({}, {"LAST30DAYS_NO_PATENT_DIGEST": "1"}), |
| 205 | ], |
| 206 | ids=["comparison", "hiring-signals", "quick", "no-patent-digest-env"], |
| 207 | ) |
| 208 | def test_runs_that_never_ask_for_patents_never_read_the_company_names( |
| 209 | monkeypatch, tmp_path, kwargs, env_vars, |
| 210 | ): |
| 211 | for name, value in env_vars.items(): |
| 212 | monkeypatch.setenv(name, value) |
| 213 | wikidata = FakeWikidata() |
| 214 | |
| 215 | observed = _run(monkeypatch, tmp_path, topic="Alphabet", wikidata=wikidata, **kwargs) |
| 216 | |
| 217 | # Alphabet, Stripe and IBM each list subsidiaries; none is asked for. |
| 218 | assert wikidata.calls |
| 219 | assert _subsidiary_label_requests(wikidata) == [] |
| 220 | asked = observed.company_resolver.call_args_list |
| 221 | assert asked |
| 222 | assert [call.kwargs.get("names", False) for call in asked] == [False] * len(asked) |
| 223 | for report in observed.reports.values(): |
| 224 | assert report.artifacts["resolved"]["company"] |
| 225 | assert "company_names" not in report.artifacts["resolved"] |
| 226 | assert observed.lane.calls == [] |
| 227 | |
| 228 | |
| 229 | def test_a_company_run_reads_the_company_names_for_the_patent_lane(monkeypatch, tmp_path): |
| 230 | wikidata = FakeWikidata() |
| 231 | |
| 232 | observed = _run(monkeypatch, tmp_path, topic="Alphabet", wikidata=wikidata) |
| 233 | |
| 234 | observed.company_resolver.assert_called_once_with("Alphabet", names=True, config=mock.ANY) |
| 235 | assert len(_subsidiary_label_requests(wikidata)) == 1 |
| 236 | (call,) = observed.lane.calls |
| 237 | assert {"Google", "Waymo"} <= set(call["company"]["company_names"]) |
| 238 | |
| 239 | |
| 240 | def test_a_company_run_with_a_host_ticker_reads_the_company_names_too(monkeypatch, tmp_path): |
| 241 | observed = _run(monkeypatch, tmp_path, args=["--ticker", "MAIN:MainBrand"]) |
| 242 | |
| 243 | observed.company_resolver.assert_called_once_with( |
| 244 | "MainBrand", listing=False, names=True, config=mock.ANY, |
| 245 | ) |
| 246 | |
| 247 | |
| 248 | def test_hosted_run_never_asks_for_patents(monkeypatch): |
| 249 | lane = FakeLane() |
| 250 | monkeypatch.setattr(patents, "fetch_patent_data", lane) |
| 251 | monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_DUMMY_TEST_KEY_00000") |
| 252 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1") |
| 253 | monkeypatch.setattr(hosted, "run_hosted", lambda *_args, **_kwargs: 0) |
| 254 | monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {}) |
| 255 | monkeypatch.setattr( |
| 256 | cli.pipeline, "run", mock.Mock(side_effect=AssertionError("local pipeline must not run")), |
| 257 | ) |
| 258 | monkeypatch.setattr(sys, "argv", ["last30days.py", "MainBrand"]) |
| 259 | |
| 260 | assert cli.main() == 0 |
| 261 | assert lane.calls == [] |
| 262 | |
| 263 | |
| 264 | def test_topic_with_no_company_makes_no_call(monkeypatch, tmp_path): |
| 265 | observed = _run( |
| 266 | monkeypatch, tmp_path, topic="Kanye West", companies={}, |
| 267 | # Neither the ticker's company nor the official site is the patent company. |
| 268 | args=["--ticker", "MAIN:MainBrand", "--official-site", "mainbrand.example"], |
| 269 | ) |
| 270 | |
| 271 | assert observed.lane.calls == [] |
| 272 | assert "patents" not in observed.report.artifacts |
| 273 | |
| 274 | |
| 275 | def test_host_company_is_used_when_the_resolver_named_none(monkeypatch, tmp_path): |
| 276 | observed = _run( |
| 277 | monkeypatch, tmp_path, topic="Palmer Luckey", companies={}, |
| 278 | args=["--company", "Anduril:anduril.com,Oculus"], |
| 279 | ) |
| 280 | |
| 281 | assert [call["company"] for call in observed.lane.calls] == [{"company": "Anduril"}] |
| 282 | assert observed.report.artifacts["patents"] == ARTIFACT |
| 283 | |
| 284 | |
| 285 | def test_resolved_company_wins_over_a_host_company(monkeypatch, tmp_path): |
| 286 | observed = _run(monkeypatch, tmp_path, args=["--company", "Anduril"]) |
| 287 | |
| 288 | assert [call["company"] for call in observed.lane.calls] == [COMPANY] |
| 289 | |
| 290 | |
| 291 | def test_person_topic_passes_the_company_they_lead(monkeypatch, tmp_path): |
| 292 | led = {**COMPANY, "company_via_person": True} |
| 293 | observed = _run(monkeypatch, tmp_path, topic="Jensen Huang", companies={"Jensen Huang": led}) |
| 294 | |
| 295 | assert [call["company"] for call in observed.lane.calls] == [led] |
| 296 | assert observed.lane.calls[0]["company"]["company_via_person"] is True |
| 297 | |
| 298 | |
| 299 | # --- the window -------------------------------------------------------------- |
| 300 | |
| 301 | |
| 302 | @pytest.mark.parametrize( |
| 303 | ("args", "expected"), |
| 304 | [ |
| 305 | ([], None), |
| 306 | (["--as-of", "2026-03-15", "--days", "14"], ("2026-03-01", "2026-03-15")), |
| 307 | ], |
| 308 | ids=["default", "past-as-of"], |
| 309 | ) |
| 310 | def test_lane_window_is_the_reports_own_range(monkeypatch, tmp_path, args, expected): |
| 311 | observed = _run(monkeypatch, tmp_path, args=args, real_window=True) |
| 312 | |
| 313 | (call,) = observed.lane.calls |
| 314 | report = observed.report |
| 315 | assert (call["date_from"], call["date_to"]) == (report.range_from, report.range_to) |
| 316 | if expected: |
| 317 | assert (call["date_from"], call["date_to"]) == expected |
| 318 | |
| 319 | |
| 320 | # --- what a run records ------------------------------------------------------ |
| 321 | |
| 322 | |
| 323 | def test_lane_gets_the_budget_it_is_waited_for(monkeypatch, tmp_path): |
| 324 | observed = _run(monkeypatch, tmp_path) |
| 325 | |
| 326 | assert observed.lane.calls[0]["budget_seconds"] == patents.LANE_BUDGET_SECONDS == 90.0 |
| 327 | |
| 328 | |
| 329 | def test_lane_still_running_after_its_budget_is_dropped_without_a_trace(monkeypatch, tmp_path): |
| 330 | release = threading.Event() |
| 331 | monkeypatch.setattr(patents, "LANE_BUDGET_SECONDS", 0.05) |
| 332 | started = time.monotonic() |
| 333 | try: |
| 334 | observed = _run(monkeypatch, tmp_path, lane=FakeLane(wait_for=release)) |
| 335 | elapsed = time.monotonic() - started |
| 336 | finally: |
| 337 | release.set() |
| 338 | |
| 339 | assert len(observed.lane.calls) == 1 |
| 340 | assert elapsed < 5 |
| 341 | assert "patents" not in observed.report.artifacts |
| 342 | assert "patents" not in observed.report.source_status |
| 343 | |
| 344 | |
| 345 | def test_lane_thread_cannot_keep_the_process_alive(monkeypatch): |
| 346 | release = threading.Event() |
| 347 | monkeypatch.setattr(patents, "fetch_patent_data", FakeLane(wait_for=release)) |
| 348 | try: |
| 349 | handle = patents.start(COMPANY, "2026-06-01", "2026-06-30", {}) |
| 350 | assert handle["thread"].daemon is True |
| 351 | finally: |
| 352 | release.set() |
| 353 | |
| 354 | |
| 355 | def test_success_logs_one_summary_line(monkeypatch, tmp_path, capsys): |
| 356 | _run(monkeypatch, tmp_path) |
| 357 | |
| 358 | lines = [line for line in capsys.readouterr().err.splitlines() if "[Patents]" in line] |
| 359 | assert len(lines) == 1 |
| 360 | assert "5 applications" in lines[0] and "2 grants" in lines[0] |
| 361 | assert "3 first publications" in lines[0] |
| 362 | assert "MainBrand Inc." in lines[0] and "MainBrand Licensing LLC" in lines[0] |
| 363 | |
| 364 | |
| 365 | def test_failed_lane_records_a_degraded_outcome(monkeypatch, tmp_path): |
| 366 | detail = "HTTP 500: Internal Server Error" |
| 367 | observed = _run(monkeypatch, tmp_path, lane=FakeLane({"state": "error", "detail": detail})) |
| 368 | |
| 369 | outcome = observed.report.source_status["patents"] |
| 370 | assert (outcome.source, outcome.detail, outcome.fix_hint) == ("patents", detail, "doctor") |
| 371 | assert outcome.state == cli.http.classify_failure(message=detail) |
| 372 | assert "patents" not in observed.report.artifacts |
| 373 | |
| 374 | |
| 375 | def test_sign_in_wall_records_nothing_and_says_so_once(monkeypatch, tmp_path, capsys): |
| 376 | observed = _run( |
| 377 | monkeypatch, tmp_path, |
| 378 | lane=FakeLane({"state": "signin", "detail": "USPTO Patent Public Search gave no anonymous session"}), |
| 379 | ) |
| 380 | |
| 381 | assert "patents" not in observed.report.source_status |
| 382 | assert "patents" not in observed.report.artifacts |
| 383 | lines = [line for line in capsys.readouterr().err.splitlines() if "[Patents]" in line] |
| 384 | assert len(lines) == 1 |
| 385 | assert "sign-in" in lines[0] and "skipped" in lines[0] |
| 386 | |
| 387 | |
| 388 | def test_no_filings_records_nothing_and_names_up_to_three_other_names(monkeypatch, tmp_path, capsys): |
| 389 | others = ["Mainbrand Foods", "Main Brand Co", "MainBrandt GmbH", "Fourth Name"] |
| 390 | observed = _run( |
| 391 | monkeypatch, tmp_path, lane=FakeLane({"state": "none", "other_names": others}), |
| 392 | ) |
| 393 | |
| 394 | assert "patents" not in observed.report.source_status |
| 395 | assert "patents" not in observed.report.artifacts |
| 396 | lines = [line for line in capsys.readouterr().err.splitlines() if "[Patents]" in line] |
| 397 | assert len(lines) == 1 |
| 398 | assert all(name in lines[0] for name in others[:3]) |
| 399 | assert "Fourth Name" not in lines[0] |
| 400 | |
| 401 | |
| 402 | # --- the company lookup ------------------------------------------------------ |
| 403 | |
| 404 | |
| 405 | def test_company_lookup_is_skipped_only_with_every_company_lane_excluded(monkeypatch, tmp_path): |
| 406 | every = _run( |
| 407 | monkeypatch, tmp_path, config={"EXCLUDE_SOURCES": "jobs, yahoo_finance, patents"}, |
| 408 | ) |
| 409 | assert every.company_resolver.call_count == 0 |
| 410 | assert every.lane.calls == [] |
| 411 | assert "company" not in every.report.artifacts["resolved"] |
| 412 | |
| 413 | two = _run(monkeypatch, tmp_path, config={"EXCLUDE_SOURCES": "jobs, yahoo_finance"}) |
| 414 | two.company_resolver.assert_called_once_with("MainBrand", names=True, config=mock.ANY) |
| 415 | assert [call["company"] for call in two.lane.calls] == [COMPANY] |
| 416 | assert two.report.artifacts["patents"] == ARTIFACT |
| 417 | |
| 418 | |
| 419 | def test_company_lookup_is_skipped_when_the_remaining_lane_cannot_run(monkeypatch, tmp_path): |
| 420 | # Patents is the only lane left, and this run never starts it. |
| 421 | monkeypatch.setenv("LAST30DAYS_NO_PATENT_DIGEST", "1") |
| 422 | observed = _run(monkeypatch, tmp_path, config={"EXCLUDE_SOURCES": "jobs, yahoo_finance"}) |
| 423 | |
| 424 | assert observed.company_resolver.call_count == 0 |
| 425 | assert observed.lane.calls == [] |
| 426 |