AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
test: strengthen numeric, payload, and concurrency oracles (#1225)
Ilia Alshanetsky3b38bbb53fe8
diff --git a/mcp/go.mod b/mcp/go.modindex 32ede31f..92b00f68 100644--- a/mcp/go.mod+++ b/mcp/go.mod@@ -2,7 +2,10 @@ module github.com/mvanhorn/last30days-skill/mcpgo 1.25.5-require github.com/mark3labs/mcp-go v1.1.1+require (+ github.com/mark3labs/mcp-go v1.1.1+ gopkg.in/yaml.v3 v3.0.1+)require (github.com/google/jsonschema-go v0.4.2 // indirectdiff --git a/mcp/internal/manifest/manifest_test.go b/mcp/internal/manifest/manifest_test.goindex 26a2c98e..b7375e7a 100644--- a/mcp/internal/manifest/manifest_test.go+++ b/mcp/internal/manifest/manifest_test.go@@ -10,6 +10,8 @@ import ("runtime""strings""testing"++ "gopkg.in/yaml.v3")// envBinding is a minimal subset of the MCPB v0.3 manifest just covering@@ -155,22 +157,49 @@ func TestUserConfigShape(t *testing.T) {}func TestPlatformsMatchShippingMatrix(t *testing.T) {- // compatibility.platforms must list exactly what the release CI- // actually packages. Listing a platform we don't ship would let- // Claude Desktop start an install that has no matching binary inside- // the bundle, producing a silent failure. The CI matrix in- // .github/workflows/release.yml currently covers darwin (arm64 +- // amd64) and linux/amd64; Windows is deferred.m := loadManifest(t)- required := map[string]bool{"darwin": false, "linux": false}- forbidden := map[string]bool{"win32": true}- for _, p := range m.Compatibility.Platforms {- if _, ok := required[p]; ok {- required[p] = true+ _, thisFile, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatal("runtime.Caller failed")+ }+ workflowPath := filepath.Join(filepath.Dir(thisFile), "..", "..", "..", ".github", "workflows", "release.yml")+ data, err := os.ReadFile(workflowPath)+ if err != nil {+ t.Fatalf("read release workflow: %v", err)+ }+ var workflow struct {+ Jobs map[string]struct {+ Strategy struct {+ Matrix struct {+ Include []struct {+ GOOS string `yaml:"goos"`+ } `yaml:"include"`+ } `yaml:"matrix"`+ } `yaml:"strategy"`+ } `yaml:"jobs"`+ }+ if err := yaml.Unmarshal(data, &workflow); err != nil {+ t.Fatalf("parse release workflow: %v", err)+ }+ entries := workflow.Jobs["build-mcpb"].Strategy.Matrix.Include+ if len(entries) == 0 {+ t.Fatal("release build-mcpb matrix has no shipping platforms")+ }+ platformNames := map[string]string{"darwin": "darwin", "linux": "linux", "windows": "win32"}+ required := make(map[string]bool)+ for _, entry := range entries {+ platform, ok := platformNames[entry.GOOS]+ if !ok {+ t.Fatalf("release matrix GOOS %q has no manifest platform mapping", entry.GOOS)}- if forbidden[p] {+ required[platform] = false+ }+ for _, p := range m.Compatibility.Platforms {+ if _, ok := required[p]; !ok {t.Errorf("compatibility.platforms contains %q but the release matrix does not ship that platform; add it to the matrix or remove from the manifest", p)+ continue}+ required[p] = true}for p, found := range required {if !found {diff --git a/tests/test_cluster_v3.py b/tests/test_cluster_v3.pyindex f30b1534..d5bd6032 100644--- a/tests/test_cluster_v3.py+++ b/tests/test_cluster_v3.py@@ -110,12 +110,20 @@ class TestCrossSourceMerging(unittest.TestCase):make_candidate("c1", "reddit", "Kanye West Wireless Festival headline announcement", "Three nights!", 80),make_candidate("c2", "reddit", "Kanye West returning to Wireless Festival confirmed", "UK comeback.", 70),]- clusters = cluster.cluster_candidates(candidates, self._plan())- # The initial greedy pass may or may not merge these (depends on token similarity).- # But if they end up as separate clusters, the entity pass should NOT merge them- # since they're both from reddit.- for cl in clusters:- self.assertTrue(len(cl.sources) >= 1) # basic sanity+ initial = [+ schema.Cluster(+ cluster_id=f"cluster-{candidate.candidate_id}",+ title=candidate.title,+ candidate_ids=[candidate.candidate_id],+ representative_ids=[candidate.candidate_id],+ sources=[candidate.source],+ score=candidate.final_score,+ )+ for candidate in candidates+ ]+ clusters = cluster._merge_entity_clusters(initial, candidates)+ self.assertEqual([("c1",), ("c2",)], [tuple(cl.candidate_ids) for cl in clusters])+ self.assertEqual([["reddit"], ["reddit"]], [cl.sources for cl in clusters])class TestPolymarketIsolation(unittest.TestCase):diff --git a/tests/test_discover_render.py b/tests/test_discover_render.pyindex cbc279ed..57b199eb 100644--- a/tests/test_discover_render.py+++ b/tests/test_discover_render.py@@ -3,6 +3,8 @@ header, and the honest nothing-solid empty state."""from unittest import mock+import pytest+from lib import pipeline, render, schema@@ -88,26 +90,33 @@ def test_no_voice_line_when_topic_has_no_comment():assert "**Community voice:**" not in rendered-def test_best_community_comment_prefers_platform_normalized_strength():+ ("reddit_votes", "hn_votes", "expected"),+ [+ (300, 200, '"a modest but thoughtful comment here" - hn_user (200 votes)'),+ (4000, 3, '"the sharpest take in the thread by far" - u/sharp (4,000 votes)'),+ ],+)+def test_best_community_comment_prefers_platform_normalized_strength(+ reddit_votes, hn_votes, expected,+):items = [schema.SourceItem(item_id="a", source="reddit", title="t", body="t",url="https://reddit.com/a", metadata={"top_comments": [- {"text": "the sharpest take in the thread by far", "score": 4000, "author": "u/sharp"},+ {"text": "the sharpest take in the thread by far", "score": reddit_votes, "author": "u/sharp"},{"text": "short", "score": 9999},]},),schema.SourceItem(item_id="b", source="hackernews", title="t", body="t",url="https://news.ycombinator.com/b", metadata={"top_comments": [- {"text": "a modest but thoughtful comment here", "score": 3, "author": "hn_user"},+ {"text": "a modest but thoughtful comment here", "score": hn_votes, "author": "hn_user"},]},),]comment = pipeline._best_community_comment(items)- assert comment is not None- assert "u/sharp" in comment- assert "4,000 votes" in comment+ assert comment == expected# Sub-12-char comment bodies never surface.assert "short" not in commentdiff --git a/tests/test_entity_extract.py b/tests/test_entity_extract.pyindex c29e5697..6ffa7e9b 100644--- a/tests/test_entity_extract.py+++ b/tests/test_entity_extract.py@@ -35,13 +35,15 @@ class TestExtractXHandles(unittest.TestCase):def test_frequency_ranking(self):items = [+ {"author_handle": "rare", "text": ""},{"author_handle": "popular", "text": ""},+ {"author_handle": "regular", "text": ""},{"author_handle": "popular", "text": ""},+ {"author_handle": "regular", "text": ""},{"author_handle": "popular", "text": ""},- {"author_handle": "rare", "text": ""},]result = entity_extract._extract_x_handles(items)- self.assertEqual(result[0], "popular")+ self.assertEqual(result, ["popular", "regular", "rare"])def test_leading_at_stripped(self):items = [{"author_handle": "@withatsign", "text": ""}]@@ -78,12 +80,15 @@ class TestExtractXHashtags(unittest.TestCase):def test_frequency_ranking(self):items = [+ {"text": "#rare tag"},{"text": "#ai is great"},+ {"text": "#python is useful"},{"text": "#ai again"},- {"text": "#rare tag"},+ {"text": "#python again"},+ {"text": "#ai once more"},]result = entity_extract._extract_x_hashtags(items)- self.assertEqual(result[0], "#ai")+ self.assertEqual(result, ["#ai", "#python", "#rare"])def test_single_char_tag_filtered(self):items = [{"text": "#X is not enough chars but #AI is"}]@@ -115,12 +120,15 @@ class TestExtractSubreddits(unittest.TestCase):def test_frequency_ranking(self):items = [+ {"subreddit": "rare"},{"subreddit": "popular"},+ {"subreddit": "regular"},+ {"subreddit": "popular"},+ {"subreddit": "regular"},{"subreddit": "popular"},- {"subreddit": "rare"},]result = entity_extract._extract_subreddits(items)- self.assertEqual(result[0], "popular")+ self.assertEqual(result, ["popular", "regular", "rare"])def test_leading_r_slash_stripped(self):items = [{"subreddit": "r/stripped"}]diff --git a/tests/test_entity_extract_v3.py b/tests/test_entity_extract_v3.pyindex 9439a7de..cc735c46 100644--- a/tests/test_entity_extract_v3.py+++ b/tests/test_entity_extract_v3.py@@ -39,12 +39,15 @@ class TestExtractSubreddits(unittest.TestCase):def test_ranks_by_frequency(self):items = [+ {"subreddit": "B"},{"subreddit": "A"},+ {"subreddit": "C"},+ {"subreddit": "A"},+ {"subreddit": "C"},{"subreddit": "A"},- {"subreddit": "B"},]result = entity_extract._extract_subreddits(items)- self.assertEqual(result[0], "A")+ self.assertEqual(result, ["A", "C", "B"])def test_empty_items(self):self.assertEqual([], entity_extract._extract_subreddits([]))diff --git a/tests/test_evaluator_v3.py b/tests/test_evaluator_v3.pyindex 30c20b45..9e712a4e 100644--- a/tests/test_evaluator_v3.py+++ b/tests/test_evaluator_v3.py@@ -1,6 +1,7 @@import contextlibimport ioimport json+import mathimport osimport sysimport tempfile@@ -146,10 +147,16 @@ class EvaluatorV3Tests(unittest.TestCase):self.assertEqual(1.0, evaluator.jaccard(set(), set()))self.assertEqual(1.0, evaluator.retention(set(), {"a"}))self.assertEqual(0.5, evaluator.precision_at_k(ranking, judgments, 2))- self.assertGreater(evaluator.ndcg_at_k(ranking, judgments, 2, judged), 0.0)+ self.assertEqual(1.0, evaluator.ndcg_at_k(ranking, judgments, 2, judged))+ expected_reversed = (1 + 7 / math.log2(3)) / (7 + 1 / math.log2(3))+ self.assertAlmostEqual(+ expected_reversed,+ evaluator.ndcg_at_k(list(reversed(ranking)), judgments, 2, judged),+ )self.assertEqual(1.0, evaluator.source_coverage_recall(ranking, judged, judgments))self.assertEqual(0.0, evaluator.precision_at_k([], judgments, 5))self.assertEqual(0.0, evaluator.ndcg_at_k([], judgments, 5, judged))+ self.assertEqual(0.0, evaluator.ndcg_at_k(ranking, {"a": 0, "b": 0}, 2, judged))def test_resolve_google_judge_api_key_prefers_google_key(self):with mock.patch.dict("os.environ", {"GOOGLE_API_KEY": "google", "GEMINI_API_KEY": "gemini"}, clear=False):diff --git a/tests/test_fusion_v3.py b/tests/test_fusion_v3.pyindex 4efd80fd..4cefe41d 100644--- a/tests/test_fusion_v3.py+++ b/tests/test_fusion_v3.py@@ -379,9 +379,9 @@ class TestPerAuthorCap(unittest.TestCase):]streams = {("primary", "x"): items}candidates = fusion.weighted_rrf(streams, plan, pool_limit=20)- kept_ids = {c.item_id for c in candidates if any(si.author == "@prolific" for si in c.source_items)}+ kept_ids = [c.item_id for c in candidates if any(si.author == "@prolific" for si in c.source_items)]# The top 3 items (x_0, x_1, x_2) should be kept- self.assertLessEqual(len(kept_ids), 3)+ self.assertEqual(["x_0", "x_1", "x_2"], kept_ids)class TestUrlNormalization(unittest.TestCase):diff --git a/tests/test_hackernews.py b/tests/test_hackernews.pyindex f7df333e..f2b79552 100644--- a/tests/test_hackernews.py+++ b/tests/test_hackernews.py@@ -3,6 +3,7 @@import jsonfrom datetime import datetime, timezonefrom unittest.mock import Mock, patch+from urllib.parse import parse_qs, urlsplitimport pytest@@ -246,12 +247,10 @@ def test_search_hackernews_date_filtering(mock_request):hackernews.search_hackernews("test", "2026-01-01", "2026-01-31", depth="quick")- call_args = mock_request.call_args[0]- url = call_args[1]-- # Should have numeric filters for date range- assert "numericFilters" in url- assert "created_at_i" in url+ mock_request.assert_called_once()+ url = mock_request.call_args.args[1]+ filters = parse_qs(urlsplit(url).query)["numericFilters"]+ assert filters == ["created_at_i>1767225600,created_at_i<1769904000"]@patch('lib.hackernews.http.request')diff --git a/tests/test_html_publish.py b/tests/test_html_publish.pyindex eac771d2..ada38bce 100644--- a/tests/test_html_publish.py+++ b/tests/test_html_publish.py@@ -140,8 +140,19 @@ class HtmlPublishModuleTests(unittest.TestCase):{"one": {"url": "https://one.ht-ml.app"}, "two": {"url": "https://two.ht-ml.app"}},results,)- self.assertEqual(2, publish.call_count)- self.assertEqual("shared", publish.call_args_list[0].kwargs["password"])+ self.assertEqual(+ [+ mock.call(+ "<html>one</html>", password="shared",+ endpoint=html_publish.DEFAULT_ENDPOINT, opener=None, timeout=30,+ ),+ mock.call(+ "<html>two</html>", password="shared",+ endpoint=html_publish.DEFAULT_ENDPOINT, opener=None, timeout=30,+ ),+ ],+ publish.call_args_list,+ )class HtmlPublishCliTests(unittest.TestCase):diff --git a/tests/test_internals_v3.py b/tests/test_internals_v3.pyindex 4dd9f75a..49b5d765 100644--- a/tests/test_internals_v3.py+++ b/tests/test_internals_v3.py@@ -7,7 +7,7 @@ any of these functions would silently degrade output quality.import unittest-from lib import planner, rerank, render, signals, schema+from lib import dates, planner, rerank, render, signals, schemadef _item(source: str = "reddit", **kwargs) -> schema.SourceItem:@@ -405,9 +405,14 @@ class TestDaysAgoZeroFalsy(unittest.TestCase):)def test_items_from_today_count_as_recent(self):- from datetime import date- today = date.today().isoformat()- report = self._report_with_items([today] * 5)+ report = self._report_with_items(["2026-03-17"] * 5)+ self.assertEqual(+ [0] * 5,+ [+ dates.days_ago(item.published_at, reference_date=report.range_to)+ for item in report.items_by_source["reddit"]+ ],+ )warning = render._assess_data_freshness(report)self.assertIsNone(warning, f"Items from today should be recent, got warning: {warning}")@@ -564,4 +569,3 @@ class TestXaiModelDefault(unittest.TestCase):from lib import providersself.assertIn("grok-4", providers.XAI_DEFAULT,f"XAI_DEFAULT should be a grok-4 model, got: {providers.XAI_DEFAULT}")-diff --git a/tests/test_meta_ads.py b/tests/test_meta_ads.pyindex 21ffb814..2fc15900 100644--- a/tests/test_meta_ads.py+++ b/tests/test_meta_ads.py@@ -449,14 +449,31 @@ class TestSearchMetaAds:def test_rate_limit_retries_are_disabled_on_every_call(self):# The shared client retries a 429 twice by default, which would both# contradict the no-further-calls contract and burn the lane budget.- _result, _calls = self._run(- [envelope([ad_row()]), envelope([ad_row()], key="results")]- )- with mock.patch("lib.meta_ads.http.get") as get:- get.return_value = envelope([])- search_meta_ads("Brightpan", FROM_DATE, TO_DATE, token=TOKEN)- assert get.call_args.kwargs["max_429_retries"] == 0- assert get.call_args.kwargs["deadline_monotonic"] is not None+ video = ad_row()+ video["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/a.mp4"}]+ responses = [+ envelope([]),+ envelope([company_row("300000000000001", "Brightpan")], key="results"),+ envelope([video], key="results", cursor="next"),+ envelope([ad_row(ad_archive_id="second", collation_id="second")], key="results"),+ {"transcript_available": True, "transcript": "The kettle makes better mornings."},+ ]+ with mock.patch("lib.meta_ads.http.get", side_effect=responses) as get:+ result = search_meta_ads("Brightpan", FROM_DATE, TO_DATE, token=TOKEN)+ assert [call.args[0] for call in get.call_args_list] == [+ meta_ads.SEARCH_ADS_URL,+ meta_ads.SEARCH_COMPANIES_URL,+ meta_ads.COMPANY_ADS_URL,+ meta_ads.COMPANY_ADS_URL,+ meta_ads.AD_TRANSCRIPT_URL,+ ]+ assert {ad["id"] for ad in result["ads"]} == {"1000000000000001", "second"}+ assert result["tally"]["transcribed"] == 1+ deadline = get.call_args_list[0].kwargs["deadline_monotonic"]+ assert deadline is not None+ for call in get.call_args_list:+ assert call.kwargs["max_429_retries"] == 0, call.args[0]+ assert call.kwargs["deadline_monotonic"] == deadline, call.args[0]def test_exhausted_budget_keeps_what_was_fetched_and_reports_partial(self):# Running out of time must not discard creatives already in hand: thindiff --git a/tests/test_reddit_keyless_wait_allowance.py b/tests/test_reddit_keyless_wait_allowance.pyindex 19ddfe28..6c051512 100644--- a/tests/test_reddit_keyless_wait_allowance.py+++ b/tests/test_reddit_keyless_wait_allowance.py@@ -9,29 +9,41 @@ run). The site search lane's timeout is covered in test_reddit_search.py."""import threading+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespacefrom unittest import mockfrom lib import http, reddit_listing-def test_limiter_reports_waiting_threads():- limiter = http.RateLimiter(rate_per_sec=1000.0, burst=1)+def test_limiter_reports_waiting_threads(monkeypatch):+ sleeping = threading.Event()+ release = threading.Event()+ now = [0.0]++ def blocked_sleep(delay):+ sleeping.set()+ assert release.wait(timeout=5), "queued worker was not released"+ now[0] += delay++ monkeypatch.setattr(http, "time", SimpleNamespace(monotonic=lambda: now[0], sleep=blocked_sleep))+ monkeypatch.delenv(http.REDDIT_KEYLESS_RATE_ENV, raising=False)+ limiter = http.RateLimiter(rate_per_sec=1.0, burst=1)+ monkeypatch.setattr(http, "REDDIT_KEYLESS_LIMITER", limiter)assert limiter.waiting == 0limiter.acquire() # drains the single token- started = threading.Event()-- def _wait():- started.set()- limiter.acquire()-- t = threading.Thread(target=_wait)- t.start()- started.wait(timeout=1)- # The waiter is inside acquire() until a token refills.- deadline = threading.Event()- deadline.wait(timeout=0.01)- t.join(timeout=2)+ with ThreadPoolExecutor(max_workers=1) as pool:+ worker = pool.submit(limiter.acquire)+ try:+ assert sleeping.wait(timeout=5), "worker did not reach token wait"+ assert not worker.done()+ assert limiter.waiting == 1+ assert http.reddit_keyless_wait_allowance(2) == 3.0 + http.REDDIT_KEYLESS_CONTENTION_SECONDS+ finally:+ release.set()+ worker.result(timeout=5)assert limiter.waiting == 0+ assert http.reddit_keyless_wait_allowance(2) == 2.0 + http.REDDIT_KEYLESS_CONTENTION_SECONDSdef test_wait_allowance_scales_with_batch_and_queue(monkeypatch):diff --git a/tests/test_signals_v3.py b/tests/test_signals_v3.pyindex 8c9b3648..132dce20 100644--- a/tests/test_signals_v3.py+++ b/tests/test_signals_v3.py@@ -109,6 +109,7 @@ class SignalsV3Tests(unittest.TestCase):def test_instagram_comment_vote_uses_instagram_reference(self):"""U2: normalized_comment_vote uses the instagram reference, not the default."""strength = signals.normalized_comment_vote("instagram", 5000)+ self.assertAlmostEqual(math.log1p(5000) / 9.2, strength)self.assertGreater(strength, 0.0)self.assertLessEqual(strength, 1.0)diff --git a/tests/test_store.py b/tests/test_store.pyindex 6fbd2a78..ce571360 100644--- a/tests/test_store.py+++ b/tests/test_store.py@@ -225,17 +225,12 @@ def test_findings_from_report_includes_polymarket(sample_report):def test_findings_from_report_respects_limit(sample_report):- """Test that limit parameter works correctly."""+ """The limit applies across ranked and supplemental sources."""findings = store.findings_from_report(sample_report, limit=2)-- # Should have at most 2 items per source- source_counts = {}- for f in findings:- source = f["source"]- source_counts[source] = source_counts.get(source, 0) + 1-- for count in source_counts.values():- assert count <= 2+ assert [(f["source"], f["source_url"]) for f in findings] == [+ ("reddit", "https://reddit.com/r/test/1"),+ ("x", "https://x.com/test/status/1"),+ ]def test_findings_from_report_handles_empty_sources():diff --git a/tests/test_transcribe.py b/tests/test_transcribe.pyindex f70867cd..b15e039f 100644--- a/tests/test_transcribe.py+++ b/tests/test_transcribe.py@@ -52,10 +52,15 @@ class TestTranscribeFlow:def test_over_limit_chunks_joined_in_order(self):chunks = ["/tmp/wd/chunk_000.mp3", "/tmp/wd/chunk_001.mp3"]+ transcripts = {chunks[0]: "part one", chunks[1]: "part two"}++ def post(provider, path, key, timeout):+ return transcripts[path]+with mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"), \mock.patch.object(transcribe, "_acquire_audio", return_value="/tmp/audio.mp3"), \mock.patch.object(transcribe, "_chunk_audio", return_value=chunks), \- mock.patch.object(transcribe, "_post_audio", side_effect=["part one", "part two"]), \+ mock.patch.object(transcribe, "_post_audio", side_effect=post), \mock.patch.object(transcribe.shutil, "rmtree"), \mock.patch.object(transcribe.tempfile, "mkdtemp", return_value="/tmp/wd"):result = transcribe.transcribe_media("https://x/v", {"GROQ_API_KEY": "k"})diff --git a/tests/test_trustpilot_source.py b/tests/test_trustpilot_source.pyindex eee52026..5325feb7 100644--- a/tests/test_trustpilot_source.py+++ b/tests/test_trustpilot_source.py@@ -343,17 +343,51 @@ def test_warmup_stale_session_logs_in_once(monkeypatch):def test_warmup_concurrent_calls_single_warmup(monkeypatch):- import threading as _threading- calls = _capture_cli(monkeypatch, {"auth status": {"isFresh": True}})- threads = [- _threading.Thread(target=trustpilot.ensure_session_ready, args=("ThriftBooks",))- for _ in range(8)- ]- for t in threads:- t.start()- for t in threads:- t.join()- assert len([c for c in calls if c[1] == "auth"]) == 1 # vs-mode race guard+ import threading+ from concurrent.futures import ThreadPoolExecutor++ started = threading.Event()+ release = threading.Event()+ contender_reached = threading.Event()+ real_lock = trustpilot._warmup_lock+ calls = []++ class ObservedLock:+ def __enter__(self):+ if started.is_set():+ contender_reached.set()+ return real_lock.__enter__()++ def __exit__(self, *args):+ return real_lock.__exit__(*args)++ def blocked_cli(cmd, timeout):+ calls.append(list(cmd))+ if started.is_set():+ contender_reached.set()+ started.set()+ assert release.wait(timeout=5), "warm-up was not released"+ return {"isFresh": True}++ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)+ monkeypatch.setattr(trustpilot, "_warmup_lock", ObservedLock())+ monkeypatch.setattr(trustpilot, "_run_cli", blocked_cli)+ expected = [[trustpilot.CLI_BIN, "auth", "status", "--agent"]]+ with ThreadPoolExecutor(max_workers=2) as pool:+ first = pool.submit(trustpilot.ensure_session_ready, "ThriftBooks")+ try:+ assert started.wait(timeout=5), "first warm-up did not reach CLI"+ second = pool.submit(trustpilot.ensure_session_ready, "ThriftBooks")+ assert contender_reached.wait(timeout=5), "second caller did not reach lock or CLI"+ assert calls == expected+ assert not first.done()+ assert not second.done()+ release.set()+ first.result(timeout=5)+ second.result(timeout=5)+ finally:+ release.set()+ assert calls == expecteddef test_warmup_skips_non_brand_topic(monkeypatch):diff --git a/tests/test_xquik.py b/tests/test_xquik.pyindex 2c6bec58..a8a49105 100644--- a/tests/test_xquik.py+++ b/tests/test_xquik.py@@ -1,5 +1,6 @@import unittestfrom unittest.mock import patch+from urllib.parse import parse_qs, urlsplitfrom lib import healthfrom lib.xquik import (@@ -225,11 +226,29 @@ class TestSearchXquik(unittest.TestCase):"text": "duplicate tweet","author": {"username": "user"},}- mock_get.return_value = {"tweets": [tweet]}- result = search_xquik("test topic", "2026-01-01", "2026-03-01", depth="default", token="key")- # Even with multiple queries, same tweet ID should appear only once+ distinct = {+ "id": "333",+ "text": "another relevant post",+ "author": {"username": "other"},+ }+ mock_get.side_effect = [+ {"tweets": [tweet]},+ {"tweets": [tweet, distinct]},+ ]+ with patch("lib.xquik.expand_xquik_queries", return_value=["test topic", "topic variant"]):+ result = search_xquik("test topic", "2026-01-01", "2026-03-01", depth="default", token="key")+ self.assertEqual(+ [parse_qs(urlsplit(call.args[0]).query)["q"][0] for call in mock_get.call_args_list],+ [+ "test topic since:2026-01-01 until:2026-03-01",+ "topic variant since:2026-01-01 until:2026-03-01",+ ],+ )+ self.assertEqual(+ [item["url"] for item in result["items"]],+ ["https://x.com/user/status/222", "https://x.com/other/status/333"],+ )ids = [item.get("id") for item in result["items"]]- # All items should have unique XQ ids (deduped by tweet ID)self.assertEqual(len(ids), len(set(ids)))@patch("lib.xquik.http.get")diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.pyindex dd5711d9..74c1e204 100644--- a/tests/test_youtube_yt.py+++ b/tests/test_youtube_yt.py@@ -36,10 +36,10 @@ class TestYouTubeEngagementZero(unittest.TestCase):def test_zero_view_count_preserved(self):"""video.get('view_count') == 0 must stay 0, not become the fallback."""- import json- import tempfile- import os+ from lib.subproc import SubprocResult+ youtube_yt.reset_search_cache()+ self.addCleanup(youtube_yt.reset_search_cache)video = {"id": "abc123","title": "Test",@@ -49,23 +49,20 @@ class TestYouTubeEngagementZero(unittest.TestCase):"upload_date": "20260301","description": "desc",}- with tempfile.NamedTemporaryFile(mode="w", suffix=".jsonl", delete=False) as f:- f.write(json.dumps(video) + "\n")- f.flush()- with open(f.name) as rf:- lines = rf.readlines()-- # Re-parse as the search function would- parsed = json.loads(lines[0])- view_count = parsed.get("view_count") if parsed.get("view_count") is not None else 0- like_count = parsed.get("like_count") if parsed.get("like_count") is not None else 0- comment_count = parsed.get("comment_count") if parsed.get("comment_count") is not None else 0-- os.unlink(f.name)+ positive = dict(video, id="positive", view_count=321, like_count=7, comment_count=2)+ result = SubprocResult(+ returncode=0,+ stdout="\n".join(json.dumps(item) for item in (video, positive)),+ stderr="",+ )+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \+ mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=result):+ out = youtube_yt.search_youtube("Test", "2026-02-01", "2026-03-01")- self.assertEqual(0, view_count)- self.assertEqual(0, like_count)- self.assertEqual(0, comment_count)+ self.assertNotIn("error", out)+ self.assertEqual([item["video_id"] for item in out["items"]], ["positive", "abc123"])+ self.assertEqual(out["items"][0]["engagement"], {"views": 321, "likes": 7, "comments": 2})+ self.assertEqual(out["items"][1]["engagement"], {"views": 0, "likes": 0, "comments": 0})class TestYtDlpFlags(unittest.TestCase):@@ -1208,13 +1205,17 @@ class TestYouTubeSearchTimeoutAndCache(unittest.TestCase):) as run_mock:first = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")second = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")+ self.assertEqual(first, second)+ second["items"][0]["title"] = "mutated"+ second["items"][0]["engagement"]["views"] = -1+ third = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")self.assertEqual(run_mock.call_count, 1)self.assertEqual(len(first["items"]), 1)self.assertEqual(len(second["items"]), 1)self.assertEqual(first["items"][0]["video_id"], second["items"][0]["video_id"])- # Callers get independent copies so mutations cannot poison the cache.- second["items"][0]["title"] = "mutated"- self.assertNotEqual(first["items"][0]["title"], "mutated")+ self.assertEqual(first["items"][0]["title"], "Vuori review")+ self.assertEqual(third, first)+ self.assertEqual(third["items"][0]["engagement"]["views"], 100)def test_timeout_errors_are_not_cached(self):with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \@@ -1229,6 +1230,7 @@ class TestYouTubeSearchTimeoutAndCache(unittest.TestCase):def test_waiter_receives_leader_result_without_synthetic_timeout(self):"""A coalesced waiter must not invent a timeout while the leader runs."""import threading+ from concurrent.futures import ThreadPoolExecutorfrom lib.subproc import SubprocResultvideo = {@@ -1243,41 +1245,50 @@ class TestYouTubeSearchTimeoutAndCache(unittest.TestCase):}started = threading.Event()release = threading.Event()+ contender_reached = threading.Event()def slow_run(cmd, timeout=None):+ if started.is_set():+ contender_reached.set()started.set()- release.wait(timeout=5)+ self.assertTrue(release.wait(timeout=5), "leader was not released")return SubprocResult(returncode=0, stdout=json.dumps(video) + "\n", stderr="",)- results = []-- def leader():- results.append(- youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")- )-- def waiter():- started.wait(timeout=5)- results.append(- youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")- )-with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \- mock.patch.object(youtube_yt.subproc, "run_with_timeout", side_effect=slow_run):- t_leader = threading.Thread(target=leader)- t_waiter = threading.Thread(target=waiter)- t_leader.start()- self.assertTrue(started.wait(timeout=5))- t_waiter.start()- release.set()- t_leader.join(timeout=5)- t_waiter.join(timeout=5)+ mock.patch.object(youtube_yt.subproc, "run_with_timeout", side_effect=slow_run) as run_mock, \+ ThreadPoolExecutor(max_workers=2) as pool:+ leader = pool.submit(youtube_yt.search_youtube, "Vuori", "2026-06-01", "2026-07-01")+ try:+ self.assertTrue(started.wait(timeout=5), "leader did not start yt-dlp")+ with youtube_yt._search_cache_lock:+ [(event, _slot)] = youtube_yt._search_inflight.values()+ real_wait = event.wait++ def observed_wait(timeout=None):+ contender_reached.set()+ return real_wait(timeout)++ with mock.patch.object(event, "wait", side_effect=observed_wait) as wait_mock:+ waiter = pool.submit(youtube_yt.search_youtube, "Vuori", "2026-06-01", "2026-07-01")+ self.assertTrue(contender_reached.wait(timeout=5), "second caller did not reach wait or yt-dlp")+ self.assertEqual(run_mock.call_count, 1)+ wait_mock.assert_called_once_with()+ self.assertFalse(leader.done())+ self.assertFalse(waiter.done())+ release.set()+ results = [leader.result(timeout=5), waiter.result(timeout=5)]+ finally:+ release.set()+ self.assertEqual(run_mock.call_count, 1)self.assertEqual(len(results), 2)- self.assertTrue(all(r.get("items") for r in results))- self.assertTrue(all(not r.get("error") for r in results))+ self.assertEqual(results[0], results[1])+ for result in results:+ self.assertNotIn("error", result)+ self.assertEqual([item["video_id"] for item in result["items"]], ["waiter1"])+ self.assertEqual(result["items"][0]["engagement"], {"views": 10, "likes": 1, "comments": 0})def test_stale_leader_after_reset_does_not_pop_newer_inflight(self):"""A leader that outlives reset_search_cache must not drop the new slot."""