| 1 | """Tests for the Amazon source: discovery, enrichment, stats, footer (U2, U3). |
| 2 | |
| 3 | Fixtures mirror live payload shapes pulled 2026-08-13, including the three |
| 4 | fields that arrive doubled and the fact that ``max_reviews`` is a ceiling |
| 5 | rather than a quota. |
| 6 | |
| 7 | Nothing here spawns a subprocess or touches the network. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import sys |
| 13 | from datetime import datetime, timedelta, timezone |
| 14 | from pathlib import Path |
| 15 | |
| 16 | import pytest |
| 17 | |
| 18 | sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts")) |
| 19 | |
| 20 | from lib import amazon # noqa: E402 |
| 21 | |
| 22 | |
| 23 | TODAY = datetime(2026, 8, 13, tzinfo=timezone.utc) |
| 24 | DOMAIN = "https://www.amazon.com" |
| 25 | |
| 26 | |
| 27 | def _days_ago(n: int) -> str: |
| 28 | return (TODAY - timedelta(days=n)).date().isoformat() |
| 29 | |
| 30 | |
| 31 | def search_record(**over): |
| 32 | base = { |
| 33 | "asin": "B0AAA00001", |
| 34 | "url": "https://www.amazon.com/Bentgo-Chill/dp/B0AAA00001/ref=sr_1_1?dib=xyz", |
| 35 | "name": "Chill Max Leak-Proof XL Bento-Style Lunch Box | Ice Pack Included", |
| 36 | "brand": "Bentgo", |
| 37 | "sponsored": "false", |
| 38 | "rating": 4.4, |
| 39 | "num_ratings": 459, |
| 40 | "final_price": 39.99, |
| 41 | "currency": "USD", |
| 42 | } |
| 43 | base.update(over) |
| 44 | return base |
| 45 | |
| 46 | |
| 47 | def review_record(days_ago: int, rating: int, **over): |
| 48 | review_date = TODAY - timedelta(days=days_ago) |
| 49 | # ``%-d`` is POSIX-only and raises on Windows. Build the day component |
| 50 | # from the datetime so this fixture exercises the same payload everywhere. |
| 51 | posted = f"{review_date.strftime('%B')} {review_date.day}, {review_date.year}" |
| 52 | base = { |
| 53 | "review_id": f"R{days_ago}{rating}", |
| 54 | # Live shape: the date is doubled and prose-wrapped. |
| 55 | "review_posted_date": f"{posted}Reviewed in the United States on {posted}", |
| 56 | "review_header": "Great box!Great box!", |
| 57 | "review_text": f"Review body from {days_ago} days ago.", |
| 58 | "rating": rating, |
| 59 | "helpful_count": 0, |
| 60 | "is_verified": True, |
| 61 | "is_amazon_vine": False, |
| 62 | "author_name": "A Buyer", |
| 63 | "product_rating": 4.4, |
| 64 | "product_rating_count": 459, |
| 65 | "product_rating_object": { |
| 66 | "one_star": 28, "two_star": 9, "three_star": 28, |
| 67 | "four_star": 60, "five_star": 335, |
| 68 | }, |
| 69 | } |
| 70 | base.update(over) |
| 71 | return base |
| 72 | |
| 73 | |
| 74 | # ------------------------------------------------------- field repair |
| 75 | |
| 76 | |
| 77 | class TestFieldRepair: |
| 78 | def test_doubled_header_is_repaired(self): |
| 79 | assert amazon.undouble("Best Box!Best Box!") == "Best Box!" |
| 80 | |
| 81 | def test_comma_doubled_badge_is_repaired(self): |
| 82 | assert amazon.undouble("Verified Purchase, Verified Purchase") == "Verified Purchase" |
| 83 | |
| 84 | def test_genuinely_repetitive_text_survives(self): |
| 85 | assert amazon.undouble("Great great product") == "Great great product" |
| 86 | assert amazon.undouble("Buy one, buy two") == "Buy one, buy two" |
| 87 | |
| 88 | def test_prose_wrapped_date_yields_the_leading_date(self): |
| 89 | raw = "August 3, 2026Reviewed in the United States on August 3, 2026" |
| 90 | assert amazon.parse_review_date(raw) == "2026-08-03" |
| 91 | |
| 92 | def test_unparseable_date_is_none_not_an_exception(self): |
| 93 | assert amazon.parse_review_date("") is None |
| 94 | assert amazon.parse_review_date("sometime last year") is None |
| 95 | assert amazon.parse_review_date(None) is None |
| 96 | |
| 97 | |
| 98 | class TestShortName: |
| 99 | def test_takes_the_segment_before_the_delimiter(self): |
| 100 | assert amazon.short_name("Chill Max XL | Ice Pack Included") == "Chill Max XL" |
| 101 | |
| 102 | def test_strips_a_leading_brand_when_present(self): |
| 103 | assert amazon.short_name("Weber Spirit E-325", "Weber") == "Spirit E-325" |
| 104 | |
| 105 | def test_clips_long_names_on_a_word_boundary(self): |
| 106 | out = amazon.short_name("Kids Prints Leak-Proof 5-Compartment Bento-Style Box") |
| 107 | assert len(out) <= amazon.SHORT_NAME_MAX |
| 108 | assert not out.endswith("-") |
| 109 | assert " " not in out[-1:] |
| 110 | |
| 111 | |
| 112 | # ---------------------------------------------------------- discovery |
| 113 | |
| 114 | |
| 115 | class TestDiscovery: |
| 116 | def test_parses_products_with_rating_and_price(self): |
| 117 | products = amazon.parse_search_response({"records": [search_record()]}, "bentgo lunch box") |
| 118 | assert len(products) == 1 |
| 119 | product = products[0] |
| 120 | assert product["rating"] == 4.4 |
| 121 | assert product["price"] == 39.99 |
| 122 | assert product["num_ratings"] == 459 |
| 123 | assert product["brand"] == "Bentgo" |
| 124 | |
| 125 | def test_urls_are_canonicalized_to_dp_asin(self): |
| 126 | """Live URLs carry 200+ chars of session-scoped tracking tail.""" |
| 127 | products = amazon.parse_search_response({"records": [search_record()]}, "bentgo") |
| 128 | assert products[0]["url"] == "https://www.amazon.com/dp/B0AAA00001" |
| 129 | |
| 130 | def test_duplicate_asins_collapse_keeping_the_richest_record(self): |
| 131 | records = [ |
| 132 | search_record(num_ratings=84), |
| 133 | search_record(num_ratings=459), |
| 134 | search_record(num_ratings=12), |
| 135 | ] |
| 136 | products = amazon.parse_search_response({"records": records}, "bentgo") |
| 137 | assert len(products) == 1 |
| 138 | assert products[0]["num_ratings"] == 459 |
| 139 | |
| 140 | def test_off_keyword_products_are_gated_out(self): |
| 141 | records = [ |
| 142 | search_record(), |
| 143 | search_record(asin="B0ZZZ00001", name="Cordless Drill Driver Kit", brand="DeWalt", |
| 144 | url="https://www.amazon.com/dp/B0ZZZ00001"), |
| 145 | ] |
| 146 | products = amazon.parse_search_response({"records": records}, "bentgo lunch box") |
| 147 | assert [p["asin"] for p in products] == ["B0AAA00001"] |
| 148 | |
| 149 | def test_non_amazon_and_non_https_urls_are_rejected(self): |
| 150 | records = [ |
| 151 | search_record(asin="B000000001", url="http://www.amazon.com/dp/B000000001"), |
| 152 | search_record(asin="B000000002", url="https://evil.example.com/dp/B2"), |
| 153 | search_record(asin="B000000003", url="https://www.amazon.com/dp/B000000003"), |
| 154 | ] |
| 155 | products = amazon.parse_search_response({"records": records}, "bentgo chill max lunch box") |
| 156 | assert [p["asin"] for p in products] == ["B000000003"] |
| 157 | |
| 158 | def test_alternate_marketplace_domain_is_honored(self): |
| 159 | record = search_record(url="https://www.amazon.co.uk/dp/B0AAA00001") |
| 160 | products = amazon.parse_search_response( |
| 161 | {"records": [record]}, "bentgo", domain="https://www.amazon.co.uk" |
| 162 | ) |
| 163 | assert products and products[0]["url"].startswith("https://www.amazon.co.uk/dp/") |
| 164 | |
| 165 | def test_sponsored_string_is_recorded_as_bool_never_filtered(self): |
| 166 | """R4: the flag is metadata only. Filtering can blank the lane.""" |
| 167 | records = [ |
| 168 | search_record(asin="B000000001", sponsored="true", url="https://www.amazon.com/dp/B000000001"), |
| 169 | search_record(asin="B000000002", sponsored="false", url="https://www.amazon.com/dp/B000000002"), |
| 170 | ] |
| 171 | products = amazon.parse_search_response({"records": records}, "bentgo chill max lunch box") |
| 172 | assert len(products) == 2 |
| 173 | assert {p["asin"]: p["sponsored"] for p in products} == {"B000000001": True, "B000000002": False} |
| 174 | |
| 175 | def test_error_envelope_yields_no_products(self): |
| 176 | assert amazon.parse_search_response({"records": [], "error": "401"}, "x") == [] |
| 177 | |
| 178 | |
| 179 | class TestTargetSelection: |
| 180 | def _pool(self): |
| 181 | return amazon.parse_search_response( |
| 182 | { |
| 183 | "records": [ |
| 184 | search_record(asin="C000000001", brand="Fimibuke", num_ratings=901, |
| 185 | name="60oz Leakproof Bento Lunch Box", |
| 186 | url="https://www.amazon.com/dp/C000000001"), |
| 187 | search_record(asin="B000000001", brand="Bentgo", num_ratings=821, |
| 188 | name="Kids Insulated Lunch Bag", |
| 189 | url="https://www.amazon.com/dp/B000000001"), |
| 190 | search_record(asin="B000000002", brand="Bentgo", num_ratings=710, |
| 191 | name="MicroSteel Bento Lunch Box", |
| 192 | url="https://www.amazon.com/dp/B000000002"), |
| 193 | search_record(asin="B000000003", brand="Bentgo", num_ratings=623, |
| 194 | name="Classic Stackable Lunch Box", |
| 195 | url="https://www.amazon.com/dp/B000000003"), |
| 196 | ] |
| 197 | }, |
| 198 | "bentgo lunch box", |
| 199 | ) |
| 200 | |
| 201 | def test_brand_topic_excludes_competitors_buying_the_keyword(self): |
| 202 | """The guard against paying to review a rival's product.""" |
| 203 | targets = amazon.select_enrichment_targets(self._pool(), limit=3, keyword="bentgo lunch box") |
| 204 | assert [t["asin"] for t in targets] == ["B000000001", "B000000002", "B000000003"] |
| 205 | assert all(t["brand"] == "Bentgo" for t in targets) |
| 206 | |
| 207 | def test_category_topic_stays_unfiltered_and_ranks_on_merit(self): |
| 208 | targets = amazon.select_enrichment_targets(self._pool(), limit=3, keyword="kids lunch box") |
| 209 | assert targets[0]["asin"] == "C000000001" |
| 210 | |
| 211 | def test_infer_brand_needs_the_keyword_to_name_it(self): |
| 212 | pool = self._pool() |
| 213 | assert amazon.infer_brand(pool, "bentgo lunch box") == "Bentgo" |
| 214 | assert amazon.infer_brand(pool, "best kids lunch box") == "" |
| 215 | |
| 216 | def test_near_identical_variants_do_not_take_two_pulls(self): |
| 217 | pool = amazon.parse_search_response( |
| 218 | { |
| 219 | "records": [ |
| 220 | search_record(asin="V000000001", num_ratings=901, name="60oz Leakproof Box | Blue", |
| 221 | url="https://www.amazon.com/dp/V000000001"), |
| 222 | search_record(asin="V000000002", num_ratings=900, name="60oz Leakproof Box | Pink", |
| 223 | url="https://www.amazon.com/dp/V000000002"), |
| 224 | search_record(asin="V000000003", num_ratings=500, name="Chill Max XL Box", |
| 225 | url="https://www.amazon.com/dp/V000000003"), |
| 226 | ] |
| 227 | }, |
| 228 | "bentgo lunch box", |
| 229 | ) |
| 230 | targets = amazon.select_enrichment_targets(pool, limit=2, keyword="bentgo lunch box") |
| 231 | assert [t["asin"] for t in targets] == ["V000000001", "V000000003"] |
| 232 | |
| 233 | def test_zero_limit_selects_nothing(self): |
| 234 | assert amazon.select_enrichment_targets(self._pool(), limit=0) == [] |
| 235 | |
| 236 | |
| 237 | # --------------------------------------------------------- enrichment |
| 238 | |
| 239 | |
| 240 | class TestReviewParsing: |
| 241 | def test_reviews_become_comments_with_stats(self): |
| 242 | response = {"records": [review_record(3, 5), review_record(10, 4)]} |
| 243 | comments, stats = amazon.parse_reviews(response) |
| 244 | assert len(comments) == 2 |
| 245 | assert stats["product_rating"] == 4.4 |
| 246 | assert stats["product_rating_count"] == 459 |
| 247 | assert stats["star_distribution"]["five_star"] == 335 |
| 248 | |
| 249 | def test_comments_carry_the_keys_remap_would_strip(self): |
| 250 | """Rating, date, and verified are exactly what this source needs.""" |
| 251 | comments, _ = amazon.parse_reviews({"records": [review_record(3, 5)]}) |
| 252 | comment = comments[0] |
| 253 | assert set(comment) >= {"score", "excerpt", "rating", "date", "verified"} |
| 254 | assert comment["rating"] == 5 |
| 255 | assert comment["date"] == _days_ago(3) |
| 256 | |
| 257 | def test_doubled_header_is_repaired_in_the_comment_title(self): |
| 258 | comments, _ = amazon.parse_reviews({"records": [review_record(3, 5)]}) |
| 259 | assert comments[0]["title"] == "Great box!" |
| 260 | |
| 261 | def test_woven_sample_is_newest_first(self): |
| 262 | """R2a: recency is enforced client-side, not assumed from the API.""" |
| 263 | response = {"records": [ |
| 264 | review_record(400, 5), review_record(2, 3), review_record(45, 4), |
| 265 | ]} |
| 266 | comments, _ = amazon.parse_reviews(response) |
| 267 | assert [c["date"] for c in comments] == [_days_ago(2), _days_ago(45), _days_ago(400)] |
| 268 | |
| 269 | def test_empty_payload_is_not_an_error(self): |
| 270 | assert amazon.parse_reviews({"records": []}) == ([], {}) |
| 271 | |
| 272 | |
| 273 | class TestEnrichmentLane: |
| 274 | def _products(self, n=4): |
| 275 | return [ |
| 276 | {"asin": f"B00000000{i}", "url": f"https://www.amazon.com/dp/B00000000{i}", |
| 277 | "name": f"Product {i}", "short_name": f"Product {i}", |
| 278 | "brand": "Bentgo", "num_ratings": 900 - i, "rating": 4.4} |
| 279 | for i in range(n) |
| 280 | ] |
| 281 | |
| 282 | def test_quick_depth_spawns_no_review_pulls(self): |
| 283 | calls = [] |
| 284 | out, status = amazon.enrich_with_reviews( |
| 285 | self._products(), depth="quick", |
| 286 | fetcher=lambda url: calls.append(url) or {"records": []}, |
| 287 | ) |
| 288 | assert calls == [] |
| 289 | assert len(out) == 4 |
| 290 | assert status is None # quick depth is not a degraded outcome |
| 291 | |
| 292 | def test_default_depth_pulls_exactly_three(self): |
| 293 | calls = [] |
| 294 | _, status = amazon.enrich_with_reviews( |
| 295 | self._products(), depth="default", |
| 296 | fetcher=lambda url: calls.append(url) or {"records": [review_record(2, 5)]}, |
| 297 | ) |
| 298 | assert len(calls) == 3 |
| 299 | assert status is None |
| 300 | |
| 301 | def test_deep_depth_pulls_five(self): |
| 302 | calls = [] |
| 303 | _, status = amazon.enrich_with_reviews( |
| 304 | self._products(6), depth="deep", |
| 305 | fetcher=lambda url: calls.append(url) or {"records": []}, |
| 306 | ) |
| 307 | assert len(calls) == 5 |
| 308 | |
| 309 | def test_cap_is_fifty_per_pull(self): |
| 310 | seen = {} |
| 311 | |
| 312 | def fetcher(url): |
| 313 | return {"records": []} |
| 314 | |
| 315 | # The cap reaches the CLI through fetch_reviews; assert the constant |
| 316 | # and the plumbed default together. |
| 317 | assert amazon.MAX_REVIEWS == 50 |
| 318 | import lib.brightdata as bd |
| 319 | original = bd.run_pipeline |
| 320 | bd.run_pipeline = lambda d, record, **k: seen.update(record=record) or {"records": []} |
| 321 | try: |
| 322 | amazon.fetch_reviews("https://www.amazon.com/dp/B000000001") |
| 323 | finally: |
| 324 | bd.run_pipeline = original |
| 325 | assert seen["record"] == {"url": "https://www.amazon.com/dp/B000000001", "max_reviews": 50} |
| 326 | |
| 327 | def test_reviews_attach_to_the_right_product(self): |
| 328 | out, status = amazon.enrich_with_reviews( |
| 329 | self._products(3), depth="default", |
| 330 | fetcher=lambda url: {"records": [review_record(2, 5, review_text=f"Review for {url}")]}, |
| 331 | ) |
| 332 | assert all(p.get("top_comments") for p in out) |
| 333 | assert {p["asin"]: p["top_comments"][0]["excerpt"] for p in out} == { |
| 334 | f"B00000000{i}": f"Review for https://www.amazon.com/dp/B00000000{i}" |
| 335 | for i in range(3) |
| 336 | } |
| 337 | assert out[0]["product_rating_count"] == 459 |
| 338 | assert status is None |
| 339 | |
| 340 | def test_one_failing_pull_does_not_discard_its_siblings(self): |
| 341 | def fetcher(url): |
| 342 | if url.endswith("B000000001"): |
| 343 | return {"records": [], "error": "snapshot failed"} |
| 344 | return {"records": [review_record(2, 5)]} |
| 345 | |
| 346 | out, status = amazon.enrich_with_reviews(self._products(3), depth="default", fetcher=fetcher) |
| 347 | by_asin = {p["asin"]: p for p in out} |
| 348 | assert not by_asin["B000000001"].get("top_comments") |
| 349 | assert by_asin["B000000000"].get("top_comments") |
| 350 | assert by_asin["B000000002"].get("top_comments") |
| 351 | assert status is None # partial success is not reported as status |
| 352 | |
| 353 | def test_one_raising_pull_does_not_kill_the_lane(self): |
| 354 | def fetcher(url): |
| 355 | if url.endswith("B000000001"): |
| 356 | raise RuntimeError("boom") |
| 357 | return {"records": [review_record(2, 5)]} |
| 358 | |
| 359 | out, status = amazon.enrich_with_reviews(self._products(3), depth="default", fetcher=fetcher) |
| 360 | assert sum(1 for p in out if p.get("top_comments")) == 2 |
| 361 | assert status is None # partial success is not reported as status |
| 362 | |
| 363 | def test_dropped_straggler_keeps_its_product_with_search_stats(self): |
| 364 | """A deadline drop must never delete the product from the report. |
| 365 | |
| 366 | Use a patched short LANE_DEADLINE to trigger the straggler case without |
| 367 | relying on crumb budgets (which now skip the lane entirely). |
| 368 | """ |
| 369 | import time as _time |
| 370 | import unittest.mock |
| 371 | |
| 372 | def slow(url): |
| 373 | if url.endswith("B000000000"): |
| 374 | _time.sleep(3) |
| 375 | return {"records": [review_record(2, 5)]} |
| 376 | |
| 377 | # Patch LANE_DEADLINE to 1s so the slow product times out but other |
| 378 | # products have time to complete. elapsed=0 keeps the full 1s budget. |
| 379 | with unittest.mock.patch.object(amazon, "LANE_DEADLINE", 1): |
| 380 | out, status = amazon.enrich_with_reviews( |
| 381 | self._products(2), depth="default", fetcher=slow, |
| 382 | elapsed=0.0, |
| 383 | ) |
| 384 | by_asin = {p["asin"]: p for p in out} |
| 385 | assert set(by_asin) == {"B000000000", "B000000001"} |
| 386 | # Search-record stats survive on the dropped product. |
| 387 | assert by_asin["B000000000"]["rating"] == 4.4 |
| 388 | assert by_asin["B000000000"]["num_ratings"] == 900 |
| 389 | # One straggler dropped, so status should be "review lane timed out" |
| 390 | # (since all 3 pulls didn't complete, but some did) |
| 391 | # Actually, B000000001 completed, so status is None |
| 392 | # Let me check: if completed_count > 0, status is None |
| 393 | |
| 394 | def test_exhausted_wall_clock_skips_the_lane_entirely(self): |
| 395 | calls = [] |
| 396 | out, status = amazon.enrich_with_reviews( |
| 397 | self._products(), depth="default", |
| 398 | fetcher=lambda url: calls.append(url) or {"records": []}, |
| 399 | elapsed=amazon.FOREGROUND_CONTRACT, |
| 400 | ) |
| 401 | assert calls == [] |
| 402 | assert status == "review lane skipped (budget 0s)" |
| 403 | |
| 404 | def test_crumb_budget_skips_not_fires_doomed_pulls(self): |
| 405 | """Regression test for the Bentgo bug: elapsed=269 must skip, not fire doomed 11s pulls. |
| 406 | |
| 407 | The bug: a multi-source run took 269s before reaching Amazon enrichment, |
| 408 | leaving only 11s of budget (300 - 269 - 20 = 11). All Bright Data pulls |
| 409 | timed out (cli_timeout = max(5, timeout-10) = 1s), spending credits |
| 410 | without returning reviews. |
| 411 | |
| 412 | The fix: crumb budgets (below MIN_USEFUL_REVIEW_BUDGET) return 0, |
| 413 | skipping the lane entirely instead of firing doomed short pulls. |
| 414 | """ |
| 415 | calls = [] |
| 416 | out, status = amazon.enrich_with_reviews( |
| 417 | self._products(), depth="default", |
| 418 | fetcher=lambda url: calls.append(url) or {"records": []}, |
| 419 | elapsed=269.0, |
| 420 | ) |
| 421 | # Fetcher should never be called |
| 422 | assert calls == [] |
| 423 | # Products keep their search stats (no top_comments) |
| 424 | assert all(not p.get("top_comments") for p in out) |
| 425 | assert all(p.get("rating") == 4.4 for p in out) |
| 426 | assert all(p.get("num_ratings") for p in out) |
| 427 | # Status should indicate the lane was skipped |
| 428 | assert status == "review lane skipped (budget 0s)" |
| 429 | |
| 430 | def test_early_elapsed_gets_full_budget(self): |
| 431 | """A quick search (40s elapsed) should get the full LANE_DEADLINE budget.""" |
| 432 | timeouts_seen = [] |
| 433 | |
| 434 | def capturing_fetcher(url): |
| 435 | return {"records": [review_record(2, 5)]} |
| 436 | |
| 437 | # Patch fetch_reviews to capture the timeout |
| 438 | original_fetch = amazon.fetch_reviews |
| 439 | captured_timeout = [] |
| 440 | |
| 441 | def mock_fetch(url, *, max_reviews=50, config=None, timeout=180): |
| 442 | captured_timeout.append(timeout) |
| 443 | return {"records": [review_record(2, 5)]} |
| 444 | |
| 445 | amazon.fetch_reviews = mock_fetch |
| 446 | try: |
| 447 | out, status = amazon.enrich_with_reviews( |
| 448 | self._products(1), depth="default", |
| 449 | elapsed=40.0, |
| 450 | ) |
| 451 | finally: |
| 452 | amazon.fetch_reviews = original_fetch |
| 453 | |
| 454 | assert captured_timeout, "fetch_reviews was not called" |
| 455 | # elapsed=40 → remaining = 300-40-20 = 240 → clamped to LANE_DEADLINE |
| 456 | assert captured_timeout[0] == amazon.LANE_DEADLINE |
| 457 | assert status is None |
| 458 | |
| 459 | def test_all_pulls_dropped_reports_timed_out_status(self): |
| 460 | """When all pulls drop (none complete), status should be 'review lane timed out'.""" |
| 461 | import time as _time |
| 462 | import unittest.mock |
| 463 | |
| 464 | def very_slow(url): |
| 465 | _time.sleep(5) # Longer than the deadline |
| 466 | return {"records": [review_record(2, 5)]} |
| 467 | |
| 468 | # Use a very short deadline so all pulls time out |
| 469 | with unittest.mock.patch.object(amazon, "LANE_DEADLINE", 1): |
| 470 | with unittest.mock.patch.object(amazon, "MIN_USEFUL_REVIEW_BUDGET", 1): |
| 471 | out, status = amazon.enrich_with_reviews( |
| 472 | self._products(2), depth="default", fetcher=very_slow, |
| 473 | elapsed=0.0, |
| 474 | ) |
| 475 | |
| 476 | # No products should have top_comments (all dropped) |
| 477 | assert all(not p.get("top_comments") for p in out) |
| 478 | # Status should indicate timeout |
| 479 | assert status == "review lane timed out" |
| 480 | |
| 481 | |
| 482 | # --------------------------------------------------------------- stats |
| 483 | |
| 484 | |
| 485 | class TestStats: |
| 486 | def test_five_star_share_from_the_distribution_object(self): |
| 487 | share = amazon.five_star_share( |
| 488 | {"one_star": 28, "two_star": 9, "three_star": 28, "four_star": 60, "five_star": 335} |
| 489 | ) |
| 490 | assert round(share * 100) == 73 |
| 491 | |
| 492 | def test_five_star_share_is_none_without_a_distribution(self): |
| 493 | assert amazon.five_star_share({}) is None |
| 494 | |
| 495 | def test_recent_window_counts_only_dated_reviews_inside_it(self): |
| 496 | comments = [ |
| 497 | {"date": _days_ago(2), "rating": 4}, |
| 498 | {"date": _days_ago(29), "rating": 4}, |
| 499 | {"date": _days_ago(31), "rating": 1}, |
| 500 | {"date": None, "rating": 5}, |
| 501 | ] |
| 502 | window = amazon.recent_window_stats(comments, today=TODAY) |
| 503 | assert window["recent_n"] == 2 |
| 504 | assert window["recent_avg"] == 4 |
| 505 | |
| 506 | @pytest.mark.parametrize( |
| 507 | "ratings,expected", |
| 508 | [ |
| 509 | ([1, 2, 3, 4, 5], "down"), # avg 3.0 vs 4.4 |
| 510 | ([5, 5, 5, 5, 5], "up"), # avg 5.0 vs 4.4 |
| 511 | ([4, 4, 5, 4, 5], "flat"), # avg 4.4 vs 4.4 |
| 512 | ], |
| 513 | ) |
| 514 | def test_drift_direction(self, ratings, expected): |
| 515 | product = { |
| 516 | "product_rating": 4.4, |
| 517 | "product_rating_count": 459, |
| 518 | "top_comments": [ |
| 519 | {"date": _days_ago(i + 1), "rating": r} for i, r in enumerate(ratings) |
| 520 | ], |
| 521 | } |
| 522 | assert amazon.product_stats(product, today=TODAY)["drift"] == expected |
| 523 | |
| 524 | def test_below_threshold_sample_renders_quiet_not_a_drift(self): |
| 525 | """Live census: a 50-cap pull can land only a handful in-window.""" |
| 526 | product = { |
| 527 | "product_rating": 4.4, |
| 528 | "top_comments": [{"date": _days_ago(i + 1), "rating": 1} for i in range(4)], |
| 529 | } |
| 530 | assert amazon.product_stats(product, today=TODAY)["drift"] == "quiet" |
| 531 | |
| 532 | def test_threshold_is_exactly_five(self): |
| 533 | product = { |
| 534 | "product_rating": 4.4, |
| 535 | "top_comments": [{"date": _days_ago(i + 1), "rating": 1} for i in range(5)], |
| 536 | } |
| 537 | assert amazon.product_stats(product, today=TODAY)["drift"] == "down" |
| 538 | |
| 539 | def test_no_baseline_renders_new(self): |
| 540 | assert amazon.product_stats({"top_comments": []}, today=TODAY)["drift"] == "new" |
| 541 | |
| 542 | def test_review_pull_rating_count_supersedes_the_search_record(self): |
| 543 | """Search counts are variant-level and can undercount 100x.""" |
| 544 | stats = amazon.product_stats( |
| 545 | {"num_ratings": 84, "product_rating_count": 8446, "product_rating": 4.7}, |
| 546 | today=TODAY, |
| 547 | ) |
| 548 | assert stats["ratings_total"] == 8446 |
| 549 | |
| 550 | def test_reproduces_the_live_chill_max_reading(self): |
| 551 | """End-to-end against the real 2026-08-13 payload shape.""" |
| 552 | records = ( |
| 553 | [review_record(i, r) for i, r in ((1, 5), (2, 1), (5, 5), (9, 4), (11, 4))] |
| 554 | + [review_record(200, 5), review_record(400, 5)] |
| 555 | ) |
| 556 | comments, stats = amazon.parse_reviews({"records": records}) |
| 557 | product = {"short_name": "Chill Max XL", **stats, "top_comments": comments} |
| 558 | out = amazon.product_stats(product, today=TODAY) |
| 559 | assert out["all_time"] == 4.4 |
| 560 | assert out["ratings_total"] == 459 |
| 561 | assert round(out["five_star_share"] * 100) == 73 |
| 562 | assert out["recent_n"] == 5 |
| 563 | assert out["recent_avg"] == 3.8 |
| 564 | assert out["drift"] == "down" |
| 565 | |
| 566 | |
| 567 | # -------------------------------------------------------------- footer |
| 568 | |
| 569 | |
| 570 | class TestFooterEntry: |
| 571 | def test_negative_drift_gets_the_arrow_marker(self): |
| 572 | entry = amazon.footer_entry( |
| 573 | {"short_name": "Chill Max XL", "all_time": 4.4, "recent_avg": 3.8, "drift": "down"} |
| 574 | ) |
| 575 | assert entry == "Chill Max XL 4.4★→3.8★ ↓" |
| 576 | |
| 577 | def test_positive_drift_gets_no_marker(self): |
| 578 | entry = amazon.footer_entry( |
| 579 | {"short_name": "Deluxe Bag", "all_time": 4.7, "recent_avg": 5.0, "drift": "up"} |
| 580 | ) |
| 581 | assert entry == "Deluxe Bag 4.7★→5.0★" |
| 582 | assert "↓" not in entry |
| 583 | |
| 584 | def test_quiet_state_shows_the_baseline_without_an_arrow(self): |
| 585 | entry = amazon.footer_entry( |
| 586 | {"short_name": "Genesis E-325", "all_time": 4.4, "recent_avg": None, "drift": "quiet"} |
| 587 | ) |
| 588 | assert entry == "Genesis E-325 4.4★ quiet" |
| 589 | assert "→" not in entry |
| 590 | |
| 591 | def test_new_state_claims_no_baseline(self): |
| 592 | entry = amazon.footer_entry({"short_name": "BLUEY Set", "all_time": None, "drift": "new"}) |
| 593 | assert entry == "BLUEY Set new" |
| 594 | |
| 595 | def test_quote_renders_only_on_negative_drift(self): |
| 596 | sagging = amazon.footer_entry( |
| 597 | {"short_name": "Chill Max XL", "all_time": 4.4, "recent_avg": 3.8, "drift": "down"}, |
| 598 | quote="the lid jams", |
| 599 | ) |
| 600 | assert sagging == 'Chill Max XL 4.4★→3.8★ ↓ "the lid jams"' |
| 601 | healthy = amazon.footer_entry( |
| 602 | {"short_name": "Deluxe Bag", "all_time": 4.7, "recent_avg": 5.0, "drift": "up"}, |
| 603 | quote="the lid jams", |
| 604 | ) |
| 605 | assert '"' not in healthy |
| 606 | |
| 607 | def test_absent_quote_renders_the_clean_numeric_entry(self): |
| 608 | entry = amazon.footer_entry( |
| 609 | {"short_name": "Chill Max XL", "all_time": 4.4, "recent_avg": 3.8, "drift": "down"}, |
| 610 | quote="", |
| 611 | ) |
| 612 | assert entry == "Chill Max XL 4.4★→3.8★ ↓" |
| 613 | |
| 614 | |
| 615 | class _Item: |
| 616 | """Minimal SourceItem stand-in for the enrichment adapter.""" |
| 617 | |
| 618 | def __init__(self, asin, **meta): |
| 619 | self.source = "amazon" |
| 620 | self.url = f"https://www.amazon.com/dp/{asin}" |
| 621 | self.title = meta.get("name", asin) |
| 622 | self.metadata = {"asin": asin, "short_name": asin, "brand": "Bentgo", **meta} |
| 623 | |
| 624 | |
| 625 | class TestSourceItemEnrichment: |
| 626 | def test_reviews_and_stats_land_on_item_metadata(self, monkeypatch): |
| 627 | # Review records are relative to the fixture date, not the wall clock. |
| 628 | monkeypatch.setattr(amazon, "_today", lambda: TODAY) |
| 629 | items = [_Item("B000000001"), _Item("B000000002")] |
| 630 | amazon.enrich_source_items( |
| 631 | items, depth="default", keyword="bentgo lunch box", |
| 632 | fetcher=lambda url: {"records": [ |
| 633 | review_record(i + 1, r) for i, r in enumerate([1, 1, 1, 1, 1]) |
| 634 | ]}, |
| 635 | ) |
| 636 | for item in items: |
| 637 | assert item.metadata["top_comments"] |
| 638 | assert item.metadata["stats"]["drift"] == "down" |
| 639 | |
| 640 | def test_non_amazon_items_are_untouched(self): |
| 641 | other = _Item("B000000001") |
| 642 | other.source = "reddit" |
| 643 | amazon.enrich_source_items([other], depth="default", fetcher=lambda url: {"records": []}) |
| 644 | assert "top_comments" not in other.metadata |
| 645 | |
| 646 | def test_already_enriched_items_are_not_re_pulled(self): |
| 647 | """enrich_source_items no-ops when top_comments is already set. |
| 648 | |
| 649 | This is critical for the thin-retry path: Phase 1 enriches products at |
| 650 | search time, then thin retry (Phase 2b) may return the same ASINs. The |
| 651 | pipeline passes skip_amazon_enrichment=True in thin retry, so products |
| 652 | arrive at finalize without re-enrichment. Finalize calls enrich_source_items, |
| 653 | which skips already-enriched items (top_comments set) and only enriches |
| 654 | genuinely new products. This prevents duplicate Bright Data pulls. |
| 655 | """ |
| 656 | item = _Item("B000000001", top_comments=[{"excerpt": "cached", "score": 0, "rating": 5, "date": None}]) |
| 657 | calls = [] |
| 658 | amazon.enrich_source_items( |
| 659 | [item], depth="default", |
| 660 | fetcher=lambda url: calls.append(url) or {"records": []}, |
| 661 | ) |
| 662 | assert calls == [] |
| 663 | |
| 664 | def test_quick_depth_touches_nothing(self): |
| 665 | items = [_Item("B000000001")] |
| 666 | calls = [] |
| 667 | amazon.enrich_source_items( |
| 668 | items, depth="quick", |
| 669 | fetcher=lambda url: calls.append(url) or {"records": []}, |
| 670 | ) |
| 671 | assert calls == [] |
| 672 | assert "top_comments" not in items[0].metadata |
| 673 | |
| 674 | |
| 675 | class TestStatsFromItem: |
| 676 | def test_uses_the_cached_block_when_enrichment_already_ran(self): |
| 677 | item = _Item("B000000001", stats={"short_name": "Cached", "drift": "up"}) |
| 678 | assert amazon.stats_from_item(item)["short_name"] == "Cached" |
| 679 | |
| 680 | def test_recomputes_from_metadata_when_absent(self): |
| 681 | """Mock runs and replayed fixtures skip enrichment entirely.""" |
| 682 | item = _Item( |
| 683 | "B1", |
| 684 | product_rating=4.4, |
| 685 | product_rating_count=459, |
| 686 | star_distribution={"one_star": 28, "two_star": 9, "three_star": 28, |
| 687 | "four_star": 60, "five_star": 335}, |
| 688 | top_comments=[{"date": _days_ago(i + 1), "rating": 1} for i in range(5)], |
| 689 | ) |
| 690 | stats = amazon.stats_from_item(item, today=TODAY) |
| 691 | assert stats["drift"] == "down" |
| 692 | assert stats["all_time"] == 4.4 |
| 693 | assert round(stats["five_star_share"] * 100) == 73 |
| 694 | |
| 695 | |
| 696 | class _FooterItem: |
| 697 | def __init__(self, short_name, *, reviews=0, all_time=4.4, recent=None, |
| 698 | drift="quiet", quote=None): |
| 699 | self.source = "amazon" |
| 700 | self.url = "https://www.amazon.com/dp/X" |
| 701 | self.title = short_name |
| 702 | self.metadata = { |
| 703 | "asin": short_name, |
| 704 | "stats": { |
| 705 | "short_name": short_name, "all_time": all_time, |
| 706 | "recent_avg": recent, "drift": drift, |
| 707 | "reviews_pulled": reviews, "ratings_total": 100, |
| 708 | "five_star_share": 0.7, "recent_n": 5 if recent else 0, |
| 709 | "url": self.url, |
| 710 | }, |
| 711 | } |
| 712 | if quote: |
| 713 | self.metadata["pulse_quote"] = quote |
| 714 | |
| 715 | |
| 716 | def _report(items, *, keyword="bentgo lunch box"): |
| 717 | from lib import schema |
| 718 | report = object.__new__(schema.Report) |
| 719 | object.__setattr__(report, "items_by_source", {"amazon": items}) |
| 720 | object.__setattr__(report, "artifacts", {"amazon_query": keyword}) |
| 721 | object.__setattr__(report, "source_status", {}) |
| 722 | return report |
| 723 | |
| 724 | |
| 725 | class TestFooterLine: |
| 726 | def _line(self, items, **kw): |
| 727 | from lib import render |
| 728 | return render._amazon_footer_line(_report(items, **kw)) |
| 729 | |
| 730 | def test_only_sampled_products_get_a_slot(self): |
| 731 | """A dozen discovered products must not become a dozen entries.""" |
| 732 | items = [_FooterItem("Sampled", reviews=20, recent=3.8, drift="down")] |
| 733 | items += [_FooterItem(f"Unsampled{i}") for i in range(9)] |
| 734 | line = self._line(items) |
| 735 | assert "Sampled 4.4★→3.8★ ↓" in line |
| 736 | assert "Unsampled" not in line |
| 737 | # The count still reports everything discovered. |
| 738 | assert line.startswith("📦 Amazon: 10 products │") |
| 739 | |
| 740 | def test_duplicate_variant_names_are_collapsed(self): |
| 741 | items = [ |
| 742 | _FooterItem("Kids Bento", reviews=20, recent=4.9, drift="up"), |
| 743 | _FooterItem("Kids Bento", reviews=20, recent=4.8, drift="up"), |
| 744 | ] |
| 745 | assert self._line(items).count("Kids Bento") == 1 |
| 746 | |
| 747 | def test_quick_depth_renders_the_inventory_form(self): |
| 748 | items = [_FooterItem("A"), _FooterItem("B")] |
| 749 | line = self._line(items) |
| 750 | assert "→" not in line |
| 751 | assert "average" in line and "ratings" in line |
| 752 | |
| 753 | def test_footer_renders_no_quote_today(self): |
| 754 | """The engine renders this line before the model sees the report, so |
| 755 | there is no weave-time path for a model-written quote. Deferred.""" |
| 756 | items = [_FooterItem("Sagging", reviews=20, recent=3.8, drift="down", |
| 757 | quote="the lid jams")] |
| 758 | line = self._line(items) |
| 759 | assert "↓" in line |
| 760 | assert '"' not in line |
| 761 | |
| 762 | def test_footer_entry_still_accepts_a_quote_for_a_future_writer(self): |
| 763 | entry = amazon.footer_entry( |
| 764 | {"short_name": "X", "all_time": 4.4, "recent_avg": 3.8, "drift": "down"}, |
| 765 | quote="the lid jams", |
| 766 | ) |
| 767 | assert '"the lid jams"' in entry |
| 768 | |
| 769 | def test_empty_result_names_the_keyword(self): |
| 770 | assert self._line([]) == '📦 Amazon: no products matched "bentgo lunch box"' |
| 771 | |
| 772 | def test_no_line_at_all_when_the_source_never_ran(self): |
| 773 | assert self._line([], keyword="") is None |
| 774 | |
| 775 | def test_malformed_asin_records_are_rejected(self): |
| 776 | """The ASIN is interpolated into a URL that is refetched and rendered.""" |
| 777 | records = [ |
| 778 | search_record(asin="../../etc/passwd", url="https://www.amazon.com/dp/x"), |
| 779 | search_record(asin="B0AAA0000", url="https://www.amazon.com/dp/y"), # 9 chars |
| 780 | search_record(asin="B0AAA000012", url="https://www.amazon.com/dp/z"), # 11 chars |
| 781 | search_record(asin="B0AAA00001", url="https://www.amazon.com/dp/ok"), |
| 782 | ] |
| 783 | products = amazon.parse_search_response({"records": records}, "bentgo chill max lunch box") |
| 784 | assert [p["asin"] for p in products] == ["B0AAA00001"] |
| 785 | |
| 786 | def test_canonical_url_falls_back_when_the_asin_is_malformed(self): |
| 787 | original = "https://www.amazon.com/dp/legit" |
| 788 | assert amazon.canonical_product_url(original, "not-an-asin", DOMAIN) == original |
| 789 | |
| 790 | def test_option_shaped_keyword_is_rejected_before_the_cli_runs(self): |
| 791 | """A leading dash would be parsed as a flag, not a search term.""" |
| 792 | calls = [] |
| 793 | import lib.brightdata as bd |
| 794 | original = bd.run_pipeline |
| 795 | bd.run_pipeline = lambda *a, **k: calls.append(a) or {"records": []} |
| 796 | try: |
| 797 | out = amazon.search_products("--help") |
| 798 | finally: |
| 799 | bd.run_pipeline = original |
| 800 | assert calls == [] |
| 801 | assert "may not begin" in out["error"] |
| 802 | |
| 803 | |
| 804 | class TestReviewFindingRegressions: |
| 805 | """Regressions caught by the correctness review pass.""" |
| 806 | |
| 807 | def test_brand_inference_survives_mixed_casing(self): |
| 808 | """One vendor spelled two ways must not disable the guard.""" |
| 809 | pool = [{"brand": "Bentgo"}, {"brand": "BENTGO"}, {"brand": "Umi"}] |
| 810 | assert amazon.infer_brand(pool, "bentgo lunch box") == "Bentgo" |
| 811 | |
| 812 | def test_multi_word_brands_are_matched(self): |
| 813 | pool = [{"brand": "Hydro Flask"}, {"brand": "Iron Flask"}] |
| 814 | assert amazon.infer_brand(pool, "hydro flask water bottle") == "Hydro Flask" |
| 815 | |
| 816 | def test_two_distinct_brands_in_the_keyword_stay_ambiguous(self): |
| 817 | pool = [{"brand": "Yeti"}, {"brand": "Stanley"}] |
| 818 | assert amazon.infer_brand(pool, "yeti vs stanley tumbler") == "" |
| 819 | |
| 820 | def test_short_name_respects_word_boundaries_on_the_brand(self): |
| 821 | """A bare startswith() ate into sub-brands and coincidental prefixes.""" |
| 822 | assert amazon.short_name("AnkerWork B600 Video Bar", "Anker") == "AnkerWork B600" |
| 823 | assert amazon.short_name("Chillax Bento Lunch Box", "Chill") == "Chillax Bento" |
| 824 | |
| 825 | def test_undouble_leaves_short_repeated_words_alone(self): |
| 826 | assert amazon.undouble("ByeBye") == "ByeBye" |
| 827 | assert amazon.undouble("NoNo") == "NoNo" |
| 828 | # Real doubling of a whole headline still repairs. |
| 829 | assert amazon.undouble("Best Box!Best Box!") == "Best Box!" |
| 830 | assert amazon.undouble("Great value for money.Great value for money.") == \ |
| 831 | "Great value for money." |
| 832 | |
| 833 | def test_lane_budget_shrinks_as_the_run_clock_advances(self): |
| 834 | """The clamp was dead code until `elapsed` was threaded through.""" |
| 835 | # Fresh run gets full LANE_DEADLINE |
| 836 | assert amazon._remaining_lane_budget(0.0) == amazon.LANE_DEADLINE |
| 837 | # Mid-run (100s elapsed) still has 180s leftover (300-100-20=180), clamped to LANE_DEADLINE |
| 838 | mid = amazon._remaining_lane_budget(100.0) |
| 839 | assert mid == amazon.LANE_DEADLINE |
| 840 | # Below floor (300-240-20=40 < MIN_USEFUL_REVIEW_BUDGET=45) → 0 |
| 841 | assert amazon._remaining_lane_budget(240.0) == 0 |
| 842 | # Way past contract → 0 |
| 843 | assert amazon._remaining_lane_budget(295.0) == 0 |
| 844 | |
| 845 | def test_lane_budget_floor_prevents_doomed_pulls(self): |
| 846 | """Crumb budgets return 0, not the crumbs. |
| 847 | |
| 848 | This is the fix for the Bentgo bug: elapsed=269 left only 11s of budget, |
| 849 | causing Bright Data pulls to time out (cli_timeout = max(5, timeout-10) |
| 850 | → 1s timeout). Now any budget below MIN_USEFUL_REVIEW_BUDGET returns 0. |
| 851 | """ |
| 852 | # elapsed=269 → remaining = 300-269-20 = 11 < MIN_USEFUL=45 → 0 |
| 853 | assert amazon._remaining_lane_budget(269.0) == 0 |
| 854 | # Just above floor: 300-235-20=45 == MIN_USEFUL → 45 (not 0) |
| 855 | assert amazon._remaining_lane_budget(235.0) == amazon.MIN_USEFUL_REVIEW_BUDGET |
| 856 | # Just below floor: 300-236-20=44 < MIN_USEFUL=45 → 0 |
| 857 | assert amazon._remaining_lane_budget(236.0) == 0 |
| 858 | |
| 859 | def test_lane_budget_constants_are_sane(self): |
| 860 | """Guard against accidental constant drift breaking the logic.""" |
| 861 | assert amazon.MIN_USEFUL_REVIEW_BUDGET == 45 |
| 862 | assert amazon.LANE_DEADLINE == 60 |
| 863 | assert amazon.MIN_USEFUL_REVIEW_BUDGET < amazon.LANE_DEADLINE |
| 864 | |
| 865 | def test_enrichment_refreshes_the_variant_level_rating_count(self): |
| 866 | """Search counts undercount badly; the pull's count is authoritative.""" |
| 867 | item = _Item("B000000001", name="Deluxe Bag", num_ratings=84) |
| 868 | item.title = "Bentgo Deluxe Bag - 4.7/5 (84 ratings)" |
| 869 | item.engagement = {"ratings": 84} |
| 870 | amazon.enrich_source_items( |
| 871 | [item], depth="default", |
| 872 | fetcher=lambda url: {"records": [ |
| 873 | review_record(i + 1, 5, product_rating=4.7, product_rating_count=8446) |
| 874 | for i in range(5) |
| 875 | ]}, |
| 876 | ) |
| 877 | assert item.engagement["ratings"] == 8446 |
| 878 | assert "8,446 ratings" in item.title |
| 879 | assert "84 ratings" not in item.title |
| 880 | assert item.metadata["stats"]["ratings_total"] == 8446 |
| 881 | |
| 882 | |
| 883 | class TestSavedArtifactCompleteness: |
| 884 | """The saved report is the copy users keep; it must not drop evidence.""" |
| 885 | |
| 886 | def _saved(self, sources): |
| 887 | from lib import render, schema |
| 888 | report = object.__new__(schema.Report) |
| 889 | for field, value in { |
| 890 | "topic": "bentgo", "range_from": "2026-07-14", "range_to": "2026-08-13", |
| 891 | "generated_at": "2026-08-13", "clusters": [], "ranked_candidates": [], |
| 892 | "items_by_source": sources, "errors_by_source": {}, "source_status": {}, |
| 893 | "freshness_verdicts": [], "warnings": [], "artifacts": {}, |
| 894 | "library_context": [], "drill_of": None, |
| 895 | "provider_runtime": schema.ProviderRuntime( |
| 896 | reasoning_provider="local", planner_model="m", rerank_model="m", |
| 897 | ), |
| 898 | "query_plan": schema.QueryPlan( |
| 899 | intent="product", freshness_mode="balanced_recent", cluster_mode="none", |
| 900 | raw_topic="bentgo", subqueries=[], |
| 901 | source_weights={s: 1.0 for s in sources}, |
| 902 | ), |
| 903 | }.items(): |
| 904 | object.__setattr__(report, field, value) |
| 905 | return render.render_full(report) |
| 906 | |
| 907 | def _item(self, source, item_id, engagement): |
| 908 | from lib import schema |
| 909 | return schema.SourceItem( |
| 910 | item_id=item_id, source=source, title=f"{source} item", body="b", |
| 911 | url="https://example.com", author="A", container=None, |
| 912 | published_at="2026-08-10", date_confidence="high", |
| 913 | engagement=engagement, relevance_hint=0.5, why_relevant="", |
| 914 | snippet="", metadata={}, |
| 915 | ) |
| 916 | |
| 917 | def test_amazon_items_appear_in_the_per_source_dump(self): |
| 918 | """Regression: a hardcoded source list silently dropped this section.""" |
| 919 | out = self._saved({"amazon": [self._item("amazon", "B0AAA00001", {"ratings": 459})]}) |
| 920 | assert "### Amazon (1 items)" in out |
| 921 | assert "B0AAA00001" in out |
| 922 | |
| 923 | def test_a_source_absent_from_the_fixed_order_still_renders(self): |
| 924 | """The list is display order, not the source registry.""" |
| 925 | out = self._saved({"trustpilot": [self._item("trustpilot", "TP1", {"reviews": 12})]}) |
| 926 | assert "TP1" in out |
| 927 | |
| 928 | def test_engagement_is_not_blank_for_a_non_allowlisted_metric(self): |
| 929 | out = self._saved({"amazon": [self._item("amazon", "B0AAA00001", {"ratings": 459})]}) |
| 930 | assert "459 ratings" in out |
| 931 | |
| 932 | def test_allowlisted_sources_keep_their_existing_engagement_format(self): |
| 933 | """The fall-through must not add previously-unshown keys.""" |
| 934 | out = self._saved({"reddit": [self._item( |
| 935 | "reddit", "R1", {"score": 120, "num_comments": 48, "upvote_ratio": 0.91} |
| 936 | )]}) |
| 937 | assert "120 score, 48 num_comments" in out |
| 938 | assert "upvote_ratio" not in out |
| 939 | |
| 940 | |
| 941 | class TestReviewsUnavailable: |
| 942 | """The provider's review scraper not answering must not cost the products.""" |
| 943 | |
| 944 | def _products(self, n=3): |
| 945 | return [ |
| 946 | {"asin": f"B00000000{i}", "url": f"https://www.amazon.com/dp/B00000000{i}", |
| 947 | "name": f"Product {i}", "short_name": f"Product {i}", "brand": "Bentgo", |
| 948 | "rating": 4.4, "num_ratings": 900 - i, "price": 39.99 + i} |
| 949 | for i in range(n) |
| 950 | ] |
| 951 | |
| 952 | def test_every_pull_failing_is_reported_and_keeps_the_products(self): |
| 953 | out, status = amazon.enrich_with_reviews( |
| 954 | self._products(), depth="default", |
| 955 | fetcher=lambda url: {"records": [], "error": "timed out after 50s"}, |
| 956 | ) |
| 957 | assert [p["asin"] for p in out] == [f"B00000000{i}" for i in range(3)] |
| 958 | assert all(p["rating"] == 4.4 and p["num_ratings"] and p["price"] for p in out) |
| 959 | assert status == "review pulls failed" |
| 960 | |
| 961 | def test_outcome_detail_names_the_provider_for_failed_and_timed_out_lanes(self): |
| 962 | for status in ("review pulls failed", "review lane timed out"): |
| 963 | detail = amazon.outcome_detail(status) |
| 964 | assert detail.startswith(amazon.REVIEWS_UNAVAILABLE_NOTE) |
| 965 | assert status in detail |
| 966 | skipped = "review lane skipped (budget 0s)" |
| 967 | assert amazon.outcome_detail(skipped) == skipped |
| 968 | |
| 969 | def test_review_lane_holds_the_run_for_about_a_minute_at_most(self): |
| 970 | assert amazon.LANE_DEADLINE == 60 |
| 971 | assert amazon.REVIEW_TIMEOUT <= amazon.LANE_DEADLINE |
| 972 | assert amazon.MIN_USEFUL_REVIEW_BUDGET < amazon.LANE_DEADLINE |
| 973 | |
| 974 | def test_a_lane_that_already_ran_is_not_pulled_again_at_finalize(self): |
| 975 | out, _ = amazon.enrich_with_reviews( |
| 976 | self._products(), depth="default", |
| 977 | fetcher=lambda url: {"records": [], "error": "timed out after 50s"}, |
| 978 | ) |
| 979 | assert all(p["reviews_attempted"] for p in out) |
| 980 | items = [_Item(p["asin"], reviews_attempted=True) for p in out] |
| 981 | calls = [] |
| 982 | amazon.enrich_source_items( |
| 983 | items, depth="default", |
| 984 | fetcher=lambda url: calls.append(url) or {"records": []}, |
| 985 | ) |
| 986 | assert calls == [] |
| 987 | |
| 988 | def test_normalize_carries_the_attempt_flag(self): |
| 989 | from lib import normalize |
| 990 | product = dict(self._products(1)[0], reviews_attempted=True, date="2026-08-13") |
| 991 | item = normalize._normalize_amazon("amazon", product, 0, "2026-07-14", "2026-08-13") |
| 992 | assert item.metadata["reviews_attempted"] is True |
| 993 | assert item.metadata["price"] == 39.99 |
| 994 | |
| 995 | def _footer(self, detail): |
| 996 | from lib import render, schema |
| 997 | items = [_FooterItem("A"), _FooterItem("B")] |
| 998 | items[0].metadata.update(price=399.0, currency="USD") |
| 999 | items[1].metadata.update(price=1299.99, currency="USD") |
| 1000 | report = _report(items) |
| 1001 | object.__setattr__(report, "source_status", {"amazon": schema.SourceOutcome( |
| 1002 | source="amazon", state=schema.PARTIAL, detail=detail, items_returned=2, |
| 1003 | )}) |
| 1004 | return render._amazon_footer_line(report) |
| 1005 | |
| 1006 | def test_footer_is_built_from_search_stats_with_a_reviews_note(self): |
| 1007 | line = self._footer(amazon.outcome_detail("review lane timed out")) |
| 1008 | assert line == ( |
| 1009 | "📦 Amazon: 2 products │ 4.4★ average │ 200 ratings │ $399 to $1,300 │ " |
| 1010 | "written reviews unavailable from the provider this run" |
| 1011 | ) |
| 1012 | |
| 1013 | def test_footer_has_no_reviews_note_when_the_lane_was_only_skipped(self): |
| 1014 | line = self._footer("review lane skipped (budget 0s)") |
| 1015 | assert "unavailable" not in line |
| 1016 | assert line.startswith("📦 Amazon: 2 products │ 4.4★ average │ 200 ratings") |
| 1017 |