返回 last30days-skill
test_trustpilot_source.py
根目录 / tests / test_trustpilot_source.py
1 """Tests for the Trustpilot source adapter (lib/trustpilot.py).
2
3 Covers the brand-shape gate (the primary quiet-keeper), the browser opt-out,
4 field mapping from the info envelope, and graceful degradation.
5 """
6
7 from __future__ import annotations
8
9 import pytest
10
11 from lib import pipeline, trustpilot
12
13
14 # ---- opt-in availability gating (off by default) ----
15
16 def test_not_available_by_default(monkeypatch):
17 monkeypatch.setattr(pipeline, "which", lambda name: f"/usr/bin/{name}")
18 avail = pipeline.available_sources({})
19 assert "trustpilot" not in avail # opt-in: absent without INCLUDE_SOURCES
20 # the zero-auth pair stays default-on
21 assert "arxiv" in avail and "techmeme" in avail
22
23
24 def test_available_when_included(monkeypatch):
25 monkeypatch.setattr(pipeline, "which", lambda name: f"/usr/bin/{name}")
26 avail = pipeline.available_sources({"INCLUDE_SOURCES": "trustpilot"})
27 assert "trustpilot" in avail
28
29
30 def test_available_when_requested(monkeypatch):
31 monkeypatch.setattr(pipeline, "which", lambda name: f"/usr/bin/{name}")
32 avail = pipeline.available_sources({}, requested_sources=["trustpilot"])
33 assert "trustpilot" in avail
34
35
36 # ---- brand-shape gate ----
37
38 @pytest.mark.parametrize("topic", ["ChowNow", "chownow.com", "Nothing Phone", "OpenAI", "nothing.tech"])
39 def test_brand_shaped_topics_fire(topic):
40 assert trustpilot.is_brand_shaped(topic)
41
42
43 @pytest.mark.parametrize("topic", [
44 "AI coding agents", # 3 words, generic
45 "agent memory", # lowercase, generic token
46 "Golden State Warriors", # 3 words -> not company-shaped
47 "best phones", # generic + lowercase
48 "how to use claude", # generic question
49 "", # empty
50 ])
51 def test_non_brand_topics_stay_quiet(topic):
52 assert not trustpilot.is_brand_shaped(topic)
53
54
55 @pytest.mark.parametrize("topic", [
56 "Python", "React", "Docker", "Rust", "Linux", "Swift", "Java",
57 "Kubernetes", "PostgreSQL", "Node",
58 ])
59 def test_single_word_tech_names_are_not_brands(topic):
60 # A bare capitalized language/framework/tool name is a technology query,
61 # not a company-review intent -- it must not trigger the Trustpilot CLI.
62 assert not trustpilot.is_brand_shaped(topic)
63
64
65 def test_tech_company_still_reachable_by_domain():
66 # The conservative tech-token gate does not block explicit company intent:
67 # a domain still resolves (e.g. wanting docker.com's reviews specifically).
68 assert trustpilot.is_brand_shaped("docker.com")
69
70
71 def test_company_identifier_prefers_domain():
72 assert trustpilot._company_identifier("reviews of chownow.com please") == "chownow.com"
73 assert trustpilot._company_identifier("ChowNow") == "ChowNow"
74
75
76 # ---- gate short-circuits the CLI (no Chrome on non-brand topics) ----
77
78 def test_non_brand_topic_never_calls_cli(monkeypatch):
79 called = []
80 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
81 monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {})
82 out = trustpilot.search_trustpilot("AI coding agents", "2026-06-01", "2026-06-27")
83 assert out == {"results": []}
84 assert called == [] # CLI (and any Chrome harvest) never invoked
85
86
87 # ---- browser opt-out ----
88
89 def test_browser_opt_out_skips_even_for_brand(monkeypatch):
90 called = []
91 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
92 monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {})
93 config = {trustpilot.NO_BROWSER_ENV: "1"}
94 out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27", config=config)
95 assert out == {"results": []}
96 assert called == [] # opt-out prevents the harvest-prone CLI call
97
98
99 def test_browser_opt_out_via_env_var_no_config(monkeypatch):
100 """The production path: the env var is set but never propagated into the
101 config dict. The os.environ fallback must still skip the harvest."""
102 called = []
103 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
104 monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {})
105 monkeypatch.setenv(trustpilot.NO_BROWSER_ENV, "1")
106 # config is None / lacks the key, mirroring env.get_config's allowlist gap.
107 out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27", config=None)
108 assert out == {"results": []}
109 assert called == []
110
111
112 # ---- happy path + field mapping ----
113
114 def test_happy_path_maps_info_envelope():
115 info = {
116 "name": "ChowNow",
117 "trustScore": 1.2,
118 "reviewCount": 49,
119 "aiSummary": "Most reviewers were let down: food never arriving, wrong address.",
120 "domain": "chownow.com",
121 }
122 items = trustpilot.parse_trustpilot_response({"results": [info]}, query="ChowNow")
123 assert len(items) == 1
124 it = items[0]
125 assert it["name"] == "ChowNow"
126 assert it["trustScore"] == 1.2
127 assert it["reviewCount"] == 49
128 assert "food never arriving" in it["summary"]
129 assert it["engagement"]["reviews"] == 49
130 assert it["url"].endswith("chownow.com")
131
132
133 def test_search_returns_info_for_brand(monkeypatch):
134 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
135 monkeypatch.setattr(
136 trustpilot, "_run_cli",
137 lambda cmd, **k: {"isFresh": True} if cmd[1] == "auth" else
138 {"name": "ChowNow", "trustScore": 1.2, "reviewCount": 49, "aiSummary": "Bad."},
139 )
140 out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27")
141 assert len(out["results"]) == 1
142 assert out["results"][0]["name"] == "ChowNow"
143
144
145 # ---- degradation paths ----
146
147 def test_cli_error_degrades_to_empty(monkeypatch):
148 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
149 monkeypatch.setattr(
150 trustpilot, "_run_cli",
151 lambda cmd, **k: {"isFresh": True} if cmd[1] == "auth" else {"error": "HTTP 500"},
152 )
153 out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27")
154 assert out == {"results": []}
155
156
157 def test_binary_absent_returns_empty(monkeypatch):
158 monkeypatch.setattr(trustpilot.shutil, "which", lambda _bin: None)
159 out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27")
160 assert out["results"] == []
161
162
163 def test_parse_handles_empty_and_malformed():
164 assert trustpilot.parse_trustpilot_response({"results": []}, query="x") == []
165 assert trustpilot.parse_trustpilot_response({}, query="x") == []
166 assert trustpilot.parse_trustpilot_response({"results": [{}]}, query="x") == []
167
168
169 # ---- shared scaffolding for domain-resolution and warm-up tests ----
170
171 D1, D2 = "2026-06-01", "2026-06-27"
172
173 THRIFTBOOKS_HITS = {
174 "hits": [
175 {"displayName": "ThriftBooks", "domain": "www.thriftbooks.com", "numberOfReviews": 2843175},
176 {"displayName": "Thrift Books", "domain": "thriftbook.com", "numberOfReviews": 130},
177 {"displayName": "Thriftybooks", "domain": "thriftybooks.com", "numberOfReviews": 6},
178 ]
179 }
180
181 INFO_OK = {"name": "ThriftBooks", "trustScore": 4.5, "reviewCount": 2843175, "aiSummary": "Great."}
182
183
184 @pytest.fixture(autouse=True)
185 def _reset_trustpilot_state():
186 trustpilot._reset_state_for_tests()
187 yield
188 trustpilot._reset_state_for_tests()
189
190
191 def _capture_cli(monkeypatch, responses):
192 """Mock _run_cli, recording argv. ``responses`` maps a subcommand key
193 ("info", "search", "auth status", "auth login") to a dict, or to a list of
194 dicts consumed in order."""
195 calls: list[list[str]] = []
196 # A replayable session unless the test says otherwise: without one the
197 # lane runs no fetch command at all.
198 # ... and no cached company record unless the test supplies one.
199 responses = {
200 "auth status": {"isFresh": True, "hasSession": True},
201 "info --local": {"error": "no cached info"},
202 **responses,
203 }
204
205 def fake(cmd, timeout):
206 calls.append(list(cmd))
207 key = cmd[1] if cmd[1] != "auth" else f"auth {cmd[2]}"
208 if key == "info" and "--local" in cmd:
209 key = "info --local"
210 resp = responses.get(key, {})
211 if isinstance(resp, list):
212 return dict(resp.pop(0)) if resp else {}
213 return dict(resp)
214
215 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
216 monkeypatch.setattr(trustpilot, "_run_cli", fake)
217 return calls
218
219
220 def _info_args(calls):
221 """Live `info` calls: the ones that would harvest a session."""
222 return [c for c in calls if c[1] == "info" and "--local" not in c]
223
224
225 def _local_info_args(calls):
226 return [c for c in calls if c[1] == "info" and "--local" in c]
227
228
229 def _search_args(calls):
230 return [c for c in calls if c[1] == "search"]
231
232
233 # ---- explicit domain (--trustpilot-domain) ----
234
235 def test_explicit_domain_used_verbatim(monkeypatch):
236 calls = _capture_cli(monkeypatch, {"info": INFO_OK})
237 out = trustpilot.search_trustpilot(
238 "ThriftBooks", D1, D2, explicit_domain="www.thriftbooks.com")
239 assert out["results"][0]["name"] == "ThriftBooks"
240 assert _info_args(calls)[0][-2:] == ["--", "www.thriftbooks.com"]
241 assert _search_args(calls) == [] # flag set -> no search call fires
242
243
244 def test_explicit_domain_bypasses_brand_gate(monkeypatch):
245 # A 4-word topic fails is_brand_shaped, but an explicit domain is proof
246 # of brand intent -- the CLI must still be invoked with the flag value.
247 calls = _capture_cli(monkeypatch, {"info": INFO_OK})
248 out = trustpilot.search_trustpilot(
249 "Stanley Steemer carpet cleaning", D1, D2,
250 explicit_domain="stanleysteemer.com")
251 assert len(out["results"]) == 1
252 assert _info_args(calls)[0][-2:] == ["--", "stanleysteemer.com"]
253
254
255 def test_explicit_domain_beats_domain_shaped_topic(monkeypatch):
256 calls = _capture_cli(monkeypatch, {"info": INFO_OK})
257 trustpilot.search_trustpilot(
258 "chownow.com", D1, D2, explicit_domain="www.thriftbooks.com")
259 assert _info_args(calls)[0][-2:] == ["--", "www.thriftbooks.com"]
260
261
262 def test_user_domain_is_verbatim_final_no_retry(monkeypatch):
263 # User-set flag (domain_is_hint=False): a miss degrades, never re-resolves.
264 calls = _capture_cli(monkeypatch, {"info": {"error": "HTTP 404"}})
265 out = trustpilot.search_trustpilot(
266 "ThriftBooks", D1, D2, explicit_domain="thriftbook.com")
267 assert out == {"results": []}
268 assert _search_args(calls) == []
269
270
271 def test_hint_domain_retries_via_search_on_miss(monkeypatch):
272 # Auto-resolved hint (domain_is_hint=True): a 404 falls through to the
273 # CLI search resolution and retries with the canonical domain.
274 calls = _capture_cli(monkeypatch, {
275 "info": [{"error": "HTTP 404"}, INFO_OK],
276 "search": THRIFTBOOKS_HITS,
277 })
278 out = trustpilot.search_trustpilot(
279 "ThriftBooks", D1, D2,
280 explicit_domain="getthriftbooks.io", domain_is_hint=True)
281 assert len(out["results"]) == 1
282 infos = _info_args(calls)
283 assert infos[0][-2:] == ["--", "getthriftbooks.io"]
284 assert infos[1][-2:] == ["--", "www.thriftbooks.com"]
285
286
287 # ---- name -> domain search fallback ----
288
289 def test_bare_name_resolves_via_search(monkeypatch):
290 calls = _capture_cli(monkeypatch, {"search": THRIFTBOOKS_HITS, "info": INFO_OK})
291 out = trustpilot.search_trustpilot("ThriftBooks", D1, D2)
292 assert len(out["results"]) == 1
293 assert _search_args(calls)[0][-2:] == ["--", "ThriftBooks"]
294 assert _info_args(calls)[0][-2:] == ["--", "www.thriftbooks.com"]
295
296
297 def test_ambiguous_hits_fall_back_to_topic(monkeypatch):
298 # Two same-named companies with comparable volume: review count must never
299 # break the tie (silent misattribution is worse than a visible miss).
300 hits = {"hits": [
301 {"displayName": "Mercury", "domain": "mercury.com", "numberOfReviews": 50000},
302 {"displayName": "Mercury", "domain": "mercuryinsurance.com", "numberOfReviews": 40000},
303 ]}
304 calls = _capture_cli(monkeypatch, {"search": hits, "info": INFO_OK})
305 trustpilot.search_trustpilot("Mercury", D1, D2)
306 assert _info_args(calls)[0][-2:] == ["--", "Mercury"] # legacy fallback identifier
307
308
309 def test_review_count_never_overrides_name_mismatch(monkeypatch):
310 hits = {"hits": [
311 {"displayName": "Bolt Technology", "domain": "bolt.eu", "numberOfReviews": 900000},
312 ]}
313 calls = _capture_cli(monkeypatch, {"search": hits, "info": INFO_OK})
314 trustpilot.search_trustpilot("Bolt", D1, D2)
315 assert _info_args(calls)[0][-2:] == ["--", "Bolt"]
316
317
318 @pytest.mark.parametrize("order", [("North 東京", "North 北京"), ("North 北京", "North 東京")])
319 def test_unicode_brands_keep_their_own_review_pages(monkeypatch, order):
320 domains = {"North 東京": "tokyo.example", "North 北京": "beijing.example"}
321 searches = []
322
323 def cli(cmd, timeout):
324 if cmd[1:3] == ["auth", "status"]:
325 return {"isFresh": True}
326 if cmd[1] == "search":
327 name = cmd[-1]
328 searches.append(name)
329 return {"hits": [{"displayName": name, "domain": domains[name]}]}
330 assert cmd[1] == "info"
331 return {"domain": cmd[-1], "reviewCount": 20}
332
333 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
334 monkeypatch.setattr(trustpilot, "_run_cli", cli)
335 for name in (*order, order[0]):
336 response = trustpilot.search_trustpilot(name, D1, D2)
337 item, = trustpilot.parse_trustpilot_response(response, query=name)
338 assert item["url"] == f"https://www.trustpilot.com/review/{domains[name]}"
339 assert item["id"] == domains[name]
340 assert searches == list(order)
341
342
343 @pytest.mark.parametrize(("topic", "candidate", "matches"), [
344 ("North 北京", "North 東京", False),
345 ("東京", "東京", True),
346 ("Élan", "E\u0301lan", True),
347 ("Acme, INC.", "acme inc", True),
348 ("Acme Straße", "Acme Strasse", False),
349 ("Acme A", "Acme A", False),
350 ("Acme क", "Acme कि", False),
351 ("Acme ★", "Acme ☆", False),
352 ("Acme A", "Acme А", False), # Latin and Cyrillic A
353 ])
354 def test_brand_name_match(topic, candidate, matches):
355 hit = {"displayName": candidate, "domain": "brand.example"}
356 assert trustpilot._select_search_hit(topic, [hit]) == (hit["domain"] if matches else None)
357
358
359 def test_search_error_falls_back_to_topic(monkeypatch):
360 calls = _capture_cli(monkeypatch, {"search": {"error": "boom"}, "info": INFO_OK})
361 out = trustpilot.search_trustpilot("ChowNow", D1, D2)
362 assert len(out["results"]) == 1
363 assert _info_args(calls)[0][-2:] == ["--", "ChowNow"]
364
365
366 def test_domain_shaped_topic_never_searches(monkeypatch):
367 calls = _capture_cli(monkeypatch, {"info": INFO_OK})
368 trustpilot.search_trustpilot("chownow.com", D1, D2)
369 assert _search_args(calls) == []
370 assert _info_args(calls)[0][-2:] == ["--", "chownow.com"]
371
372
373 def test_search_cached_per_topic_not_per_process(monkeypatch):
374 calls = _capture_cli(monkeypatch, {"search": dict(THRIFTBOOKS_HITS), "info": INFO_OK})
375 trustpilot.search_trustpilot("ThriftBooks", D1, D2)
376 trustpilot.search_trustpilot("ThriftBooks", D1, D2)
377 assert len(_search_args(calls)) == 1 # repeat topic hits the cache
378
379 # A DIFFERENT topic must trigger its own search (vs-mode entities resolve
380 # independently; a single process-wide slot would cross-contaminate).
381 responses_seen = _search_args(calls)
382 trustpilot.search_trustpilot("ChowNow", D1, D2)
383 assert len(_search_args(calls)) == len(responses_seen) + 1
384
385
386 # ---- session check (ensure_session_ready): never launches Chrome ----
387
388 def test_fresh_session_is_ready_without_login(monkeypatch):
389 calls = _capture_cli(monkeypatch, {"auth status": {"isFresh": True, "hasSession": True}})
390 assert trustpilot.ensure_session_ready("ThriftBooks") is True
391 assert [c[2] for c in calls if c[1] == "auth"] == ["status"]
392
393
394 @pytest.mark.parametrize("status", [
395 {"error": "no session"},
396 {"hasSession": False, "isFresh": False, "harvestedAt": "0001-01-01T00:00:00Z"},
397 {},
398 ])
399 def test_missing_or_stale_session_never_logs_in(monkeypatch, status):
400 # `auth login` is the command that printed "Launching Chrome via
401 # agent-browser (about 10 seconds)..." in the 2026-11-10 runs.
402 calls = _capture_cli(monkeypatch, {"auth status": status, "auth login": {"ok": True}})
403 assert trustpilot.ensure_session_ready("ThriftBooks") is False
404 assert [c[2] for c in calls if c[1] == "auth"] == ["status"]
405
406
407 def test_session_about_to_lapse_is_not_ready(monkeypatch):
408 # The CLI replays a session for four minutes and launches Chrome after
409 # that, so one in its last seconds could lapse inside the fetch command.
410 from datetime import datetime, timedelta, timezone
411
412 def harvested(seconds_ago):
413 return (datetime.now(timezone.utc) - timedelta(seconds=seconds_ago)).isoformat()
414
415 _capture_cli(monkeypatch, {"auth status": {"isFresh": True, "harvestedAt": harvested(230)}})
416 assert trustpilot.ensure_session_ready("ThriftBooks") is False
417 _capture_cli(monkeypatch, {"auth status": {"isFresh": True, "harvestedAt": harvested(60)}})
418 assert trustpilot.ensure_session_ready("ThriftBooks") is True
419
420
421 def test_every_check_reads_the_session_again(monkeypatch):
422 # No memo: the session lasts four minutes, so a remembered "fresh" could
423 # send a fetch command after it lapsed.
424 calls = _capture_cli(monkeypatch, {"auth status": [{"isFresh": True}, {"isFresh": False}]})
425 assert trustpilot.ensure_session_ready("ThriftBooks") is True
426 assert trustpilot.ensure_session_ready("ThriftBooks") is False
427 assert len(calls) == 2
428
429
430 # ---- the lane with no replayable session (2026-11-10 Waymo run) ----
431
432 def test_stale_session_skips_the_lane_with_the_sign_in_command(monkeypatch):
433 calls = _capture_cli(monkeypatch, {
434 "auth status": {"hasSession": False, "isFresh": False},
435 "info": INFO_OK,
436 })
437 logged: list[str] = []
438 monkeypatch.setattr(trustpilot, "_log", lambda msg: logged.append(msg))
439
440 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
441
442 # No fetch command ran: `info` and `search` harvest by themselves. The
443 # one `info --local` read of the CLI's cached record found nothing.
444 assert _info_args(calls) == [] and _search_args(calls) == []
445 assert [c[2] for c in calls if c[1] == "auth"] == ["status"]
446 assert _local_info_args(calls) == [["trustpilot-pp-cli", "info", "--local", "--agent", "--", "waymo.com"]]
447 assert out == {"results": [], "needs_session": True, "skipped": trustpilot.SESSION_NEEDED}
448 assert "trustpilot-pp-cli auth login" in out["skipped"]
449 assert "error" not in out
450 assert f"skipped: {trustpilot.SESSION_NEEDED}" in logged
451
452
453 def test_session_lapsing_between_search_and_info_stops_before_info(monkeypatch):
454 calls = _capture_cli(monkeypatch, {
455 "auth status": [{"isFresh": True}, {"isFresh": True}, {"isFresh": False}],
456 "search": THRIFTBOOKS_HITS,
457 "info": INFO_OK,
458 })
459
460 out = trustpilot.search_trustpilot("ThriftBooks", D1, D2)
461
462 assert out["needs_session"] is True
463 assert _info_args(calls) == []
464
465
466 def _run_with_stale_session(monkeypatch):
467 """A whole pipeline run (mock sources) whose only real lane is Trustpilot
468 with no replayable session."""
469 _capture_cli(monkeypatch, {"auth status": {"isFresh": False}, "info": INFO_OK})
470 monkeypatch.setattr(pipeline, "which", lambda name: f"/usr/bin/{name}")
471 real_impl = pipeline._retrieve_stream_impl
472
473 def impl(**kwargs):
474 if kwargs["source"] == "trustpilot":
475 return real_impl(**{**kwargs, "mock": False})
476 return real_impl(**kwargs)
477
478 monkeypatch.setattr(pipeline, "_retrieve_stream_impl", impl)
479 return pipeline.run(
480 topic="Waymo", config={"LAST30DAYS_REASONING_PROVIDER": "gemini"}, depth="quick",
481 requested_sources=["hackernews", "trustpilot"], mock=True,
482 trustpilot_domain="waymo.com",
483 )
484
485
486 def test_skipped_lane_is_a_quiet_skip_not_a_failed_source(monkeypatch):
487 from lib import render
488
489 report = _run_with_stale_session(monkeypatch)
490
491 outcome = report.source_status["trustpilot"]
492 assert (outcome.state, outcome.attempted, outcome.detail) == (
493 "no-results", False, trustpilot.SESSION_NEEDED,
494 )
495 assert "trustpilot" not in report.errors_by_source
496 assert not any("trustpilot" in warning.lower() for warning in report.warnings)
497 compact = render.render_compact(report)
498 assert "Some sources failed" not in compact
499 assert "Partial Coverage" not in compact or "Trustpilot" not in compact.split("Partial Coverage")[1].split("\n## ")[0]
500
501
502 def test_warmup_skips_non_brand_topic(monkeypatch):
503 # AE6: generic topic with trustpilot active -> no warm-up, no Chrome.
504 calls = _capture_cli(monkeypatch, {})
505 trustpilot.ensure_session_ready("AI coding agents")
506 assert calls == []
507
508
509 def test_warmup_domain_bypasses_brand_gate(monkeypatch):
510 calls = _capture_cli(monkeypatch, {"auth status": {"isFresh": True}})
511 trustpilot.ensure_session_ready("Stanley Steemer carpet cleaning", has_domain=True)
512 assert len(calls) == 1
513
514
515 def test_warmup_respects_browser_opt_out(monkeypatch):
516 calls = _capture_cli(monkeypatch, {})
517 trustpilot.ensure_session_ready("ThriftBooks", config={trustpilot.NO_BROWSER_ENV: "1"})
518 assert calls == []
519
520
521 def test_warmup_logs_no_token_bytes(monkeypatch):
522 # The auth status payload carries live WAF-token prefixes; log lines must
523 # only ever contain structured status strings.
524 logged: list[str] = []
525 monkeypatch.setattr(trustpilot, "_log", lambda msg: logged.append(msg))
526 _capture_cli(monkeypatch, {
527 "auth status": {"isFresh": False, "tokenPrefix": "48372fee-99b"},
528 "auth login": {"ok": True, "token": "48372fee-99b1-dead-beef"},
529 })
530 trustpilot.ensure_session_ready("ThriftBooks")
531 assert logged and all("48372fee" not in msg for msg in logged)
532
533
534 def test_trustpilot_capped_to_single_fetch():
535 # N subqueries listing trustpilot must produce exactly one stream: every
536 # stream would use the identical company identifier, and each extra one
537 # risks its own WAF-cookie Chrome harvest.
538 assert pipeline.MAX_SOURCE_FETCHES.get("trustpilot") == 1
539
540
541 # ---- review-driven hardening ----
542
543 def test_search_trustpilot_warms_session_at_first_touch(monkeypatch):
544 # The warm-up runs inside the source fetch (never the pipeline fan-out
545 # setup), so it must precede the info call within one search invocation.
546 calls = _capture_cli(monkeypatch, {
547 "auth status": {"isFresh": True},
548 "info": INFO_OK,
549 })
550 trustpilot.search_trustpilot(
551 "ThriftBooks", D1, D2, explicit_domain="www.thriftbooks.com")
552 assert calls[0][1] == "auth" and calls[0][2] == "status"
553 assert [c for c in calls if c[1] == "info"]
554
555
556 def test_hint_on_non_brand_topic_stays_quiet(monkeypatch):
557 # An auto-resolved hint must not widen activation beyond brand-shaped
558 # topics -- only a USER-set domain proves brand intent (AE6 contract).
559 calls = _capture_cli(monkeypatch, {})
560 out = trustpilot.search_trustpilot(
561 "AI coding agents", D1, D2,
562 explicit_domain="aicodingagents.com", domain_is_hint=True)
563 assert out == {"results": []}
564 assert calls == []
565
566
567 def test_transient_search_error_not_cached(monkeypatch):
568 # A flaky search must not poison the per-topic cache for the process.
569 calls = _capture_cli(monkeypatch, {
570 "search": [{"error": "timeout"}, dict(THRIFTBOOKS_HITS)],
571 "info": INFO_OK,
572 })
573 assert trustpilot._search_domain("ThriftBooks") is None
574 assert trustpilot._search_domain("ThriftBooks") == "www.thriftbooks.com"
575 assert len(_search_args(calls)) == 2
576
577
578 def test_empty_search_payload_not_cached(monkeypatch):
579 # Empty stdout parses to {} (exit 0, no output): a degenerate payload,
580 # not a definitive no-match -- it must not become a permanent cache entry.
581 calls = _capture_cli(monkeypatch, {
582 "search": [{}, dict(THRIFTBOOKS_HITS)],
583 "info": INFO_OK,
584 })
585 assert trustpilot._search_domain("ThriftBooks") is None
586 assert trustpilot._search_domain("ThriftBooks") == "www.thriftbooks.com"
587 assert len(_search_args(calls)) == 2
588
589
590 def test_definitive_no_match_is_cached(monkeypatch):
591 # A well-formed empty hits list IS definitive: cache it so repeat lookups
592 # for a name Trustpilot does not know cost one subprocess, not N.
593 calls = _capture_cli(monkeypatch, {"search": {"hits": []}, "info": INFO_OK})
594 assert trustpilot._search_domain("ChowNow") is None
595 assert trustpilot._search_domain("ChowNow") is None
596 assert len(_search_args(calls)) == 1
597
598
599 # ---- cached company record: a free fallback when the session is stale ----
600
601 def _fetched(days_ago):
602 from datetime import datetime, timedelta, timezone
603
604 return (datetime.now(timezone.utc) - timedelta(days=days_ago)).isoformat()
605
606
607 def test_stale_session_uses_the_cached_record_and_labels_its_age(monkeypatch):
608 calls = _capture_cli(monkeypatch, {
609 "auth status": {"hasSession": False, "isFresh": False},
610 "info --local": {**INFO_OK, "fetchedAt": _fetched(3)},
611 "auth login": {"ok": True},
612 })
613
614 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
615
616 # Nothing that can open a browser ran.
617 assert _info_args(calls) == [] and _search_args(calls) == []
618 assert [c[2] for c in calls if c[1] == "auth"] == ["status"]
619 assert "needs_session" not in out and "error" not in out
620 items = trustpilot.parse_trustpilot_response(out, query="Waymo")
621 assert len(items) == 1
622 assert items[0]["title"] == "ThriftBooks: TrustScore 4.5 (cached 3 days ago)"
623 assert "cached 3 days ago" in items[0]["why_relevant"]
624
625
626 @pytest.mark.parametrize("days,label", [(0, "cached today"), (1, "cached 1 day ago")])
627 def test_cache_age_labels(monkeypatch, days, label):
628 _capture_cli(monkeypatch, {
629 "auth status": {"isFresh": False},
630 "info --local": {**INFO_OK, "fetchedAt": _fetched(days)},
631 })
632 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
633 assert label in trustpilot.parse_trustpilot_response(out)[0]["title"]
634
635
636 def test_cached_record_without_a_fetch_time_says_its_age_is_unknown(monkeypatch):
637 _capture_cli(monkeypatch, {"auth status": {"isFresh": False}, "info --local": INFO_OK})
638 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
639 assert "(cached, age unknown)" in trustpilot.parse_trustpilot_response(out)[0]["title"]
640
641
642 def test_cached_record_older_than_the_window_is_not_used(monkeypatch):
643 _capture_cli(monkeypatch, {
644 "auth status": {"isFresh": False},
645 "info --local": {**INFO_OK, "fetchedAt": _fetched(45)},
646 })
647 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
648 assert out == {"results": [], "needs_session": True, "skipped": trustpilot.SESSION_NEEDED}
649
650
651 def test_stale_session_with_only_a_name_reads_no_cache(monkeypatch):
652 # Cached records are keyed by domain, and name -> domain needs a session.
653 calls = _capture_cli(monkeypatch, {
654 "auth status": {"isFresh": False}, "info --local": INFO_OK,
655 })
656 out = trustpilot.search_trustpilot("ThriftBooks", D1, D2)
657 assert out["needs_session"] is True
658 assert _local_info_args(calls) == []
659
660
661 def test_fresh_session_fetches_live_and_carries_no_cache_label(monkeypatch):
662 calls = _capture_cli(monkeypatch, {"info": INFO_OK, "info --local": INFO_OK})
663 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
664 assert _local_info_args(calls) == []
665 assert "cached" not in trustpilot.parse_trustpilot_response(out)[0]["title"]
666
667
668 # ---- can the lane run now? (--diagnose `trustpilot_can_run`) ----
669
670 @pytest.mark.parametrize("status,cache,expected", [
671 ({"isFresh": True, "hasSession": True}, {"companies": 0}, True),
672 ({"isFresh": False}, {"companies": 2}, True),
673 ({"isFresh": False}, {"companies": 0}, False),
674 ({"isFresh": False}, {"error": "boom"}, False),
675 ])
676 def test_can_run_now_needs_a_fresh_session_or_a_cached_company(monkeypatch, status, cache, expected):
677 calls = _capture_cli(monkeypatch, {
678 "auth status": status, "doctor-tp": cache, "auth login": {"ok": True},
679 })
680 assert trustpilot.can_run_now({})["can_run"] is expected
681 # Local reads only.
682 assert {c[1] for c in calls} <= {"auth", "doctor-tp"}
683 assert [c[2] for c in calls if c[1] == "auth"] == ["status"]
684
685
686 def test_can_run_now_is_false_without_the_cli_or_with_the_opt_out(monkeypatch):
687 calls = _capture_cli(monkeypatch, {})
688 assert trustpilot.can_run_now({trustpilot.NO_BROWSER_ENV: "1"})["can_run"] is False
689 monkeypatch.setattr(trustpilot, "_is_available", lambda: False)
690 assert trustpilot.can_run_now({})["can_run"] is False
691 assert calls == []
692
693
694 def test_diagnose_reports_whether_trustpilot_can_run(monkeypatch):
695 _capture_cli(monkeypatch, {"auth status": {"isFresh": False}, "doctor-tp": {"companies": 0}})
696 assert pipeline.diagnose({}, None, safe=True)["trustpilot_can_run"] is False
697 _capture_cli(monkeypatch, {"auth status": {"isFresh": False}, "doctor-tp": {"companies": 1}})
698 assert pipeline.diagnose({}, None, safe=True)["trustpilot_can_run"] is True
699
700
701 def test_doctor_record_says_when_trustpilot_cannot_run_now(monkeypatch):
702 from lib import doctor, health
703
704 monkeypatch.setattr(
705 doctor, "_cli_gated_record",
706 lambda config, cli, purpose: doctor._record(status=health.OK, requires=cli),
707 )
708 # Without INCLUDE_SOURCES=trustpilot, doctor mirrors pipeline.available_sources() as opt-in.
709 optin = doctor._trustpilot_record({})
710 assert optin["status"] == "opt-in"
711 assert optin["tier"] == doctor.TIER_OFF
712
713 opted_in = {"INCLUDE_SOURCES": "trustpilot"}
714 _capture_cli(monkeypatch, {"auth status": {"isFresh": False}, "doctor-tp": {"companies": 0}})
715 record = doctor._trustpilot_record(opted_in)
716 assert record["status"] == health.DEGRADED
717 assert record["tier"] == doctor.TIER_WARN
718 assert "cannot run now" in record["note"] and "never opens a browser" in record["note"]
719 _capture_cli(monkeypatch, {"auth status": {"isFresh": False}, "doctor-tp": {"companies": 3}})
720 cached = doctor._trustpilot_record(opted_in)
721 assert cached["status"] == health.OK
722 assert "3 cached company records" in cached["note"]
723
724
725 def test_runbook_resolves_the_domain_only_when_trustpilot_can_run():
726 from tests.skill_contract import reference_text
727
728 runbook = reference_text("research-runbook")
729 step = runbook.split("### Step 0.5d", 1)[1].split("\n### ", 1)[0]
730 assert "only when `--diagnose` reports `trustpilot_can_run: true`" in step
731 assert "never opens a browser" in step
732 assert step.index("trustpilot_can_run") < step.index("WebSearch(")
733
734
735 # ---- a cached record carries its fetch date, not yesterday ----
736
737 def test_cached_record_is_dated_by_its_fetch_not_yesterday(monkeypatch):
738 fetched = _fetched(21)
739 _capture_cli(monkeypatch, {
740 "auth status": {"isFresh": False},
741 "info --local": {**INFO_OK, "fetchedAt": fetched},
742 })
743 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
744 item = trustpilot.parse_trustpilot_response(out)[0]
745 assert item["date"] == fetched[:10]
746 assert "cached 21 days ago" in item["title"]
747
748
749 def test_cached_record_with_no_fetch_time_is_undated(monkeypatch):
750 from datetime import datetime, timedelta, timezone
751 from lib import dates
752
753 _capture_cli(monkeypatch, {"auth status": {"isFresh": False}, "info --local": INFO_OK})
754 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
755 raw = trustpilot.parse_trustpilot_response(out, query="Waymo")
756 assert raw[0]["date"] is None
757 # Undated, the item still reaches the report (like other undated items).
758 today = datetime.now(timezone.utc).date()
759 kept = pipeline._normalize_score_dedupe(
760 "trustpilot", raw, (today - timedelta(days=30)).isoformat(), today.isoformat(),
761 "balanced_recent", "Waymo",
762 )
763 assert len(kept) == 1 and kept[0].published_at is None
764 assert dates.get_date_range(1)[0] not in str(kept[0].published_at)
765
766
767 def test_live_record_keeps_the_current_date(monkeypatch):
768 from lib import dates
769
770 _capture_cli(monkeypatch, {"info": INFO_OK})
771 out = trustpilot.search_trustpilot("Waymo", D1, D2, explicit_domain="waymo.com")
772 # get_date_range(1) is (yesterday, today); a live record is dated today.
773 assert trustpilot.parse_trustpilot_response(out)[0]["date"] == dates.get_date_range(1)[1]
774
774 lines PYTHON