返回 last30days-skill
test_competitors.py
根目录 / tests / test_competitors.py
1 """Tests for scripts/lib/competitors.discover_competitors."""
2
3 from __future__ import annotations
4
5 import io
6 import unittest
7 from contextlib import redirect_stderr
8 from unittest import mock
9
10 from lib import competitors
11
12
13 def _serp(items: list[tuple[str, str]]) -> list[dict]:
14 """Build a minimal SERP items list from (title, snippet) pairs."""
15 return [
16 {"title": title, "snippet": snippet, "url": "https://example.test/"}
17 for title, snippet in items
18 ]
19
20 OPENAI_SERP = _serp(
21 [
22 ("OpenAI vs Anthropic vs xAI: which is better?", "xAI and Anthropic now compete directly with OpenAI."),
23 ("Top OpenAI alternatives in 2026", "Anthropic, Google Gemini, and xAI are the leading alternatives this year."),
24 ("xAI and Anthropic challenge OpenAI dominance", "xAI and Anthropic push Google Gemini hard; xAI keeps shipping."),
25 ("Anthropic vs xAI: head to head", "Anthropic and xAI trade punches; Google Gemini is not far behind."),
26 ]
27 )
28
29 KANYE_SERP = _serp(
30 [
31 ("Kanye West vs Drake: the feud explained", "Drake responded to Kanye with a diss track."),
32 ("Top rappers of the decade: Kendrick Lamar, Drake, J Cole", "Kendrick Lamar released a new album; Drake toured Europe."),
33 ("Drake and Kendrick Lamar trade shots", "J Cole stayed out of the Drake vs Kendrick Lamar feud."),
34 ]
35 )
36
37
38 class CompetitorDiscoveryTests(unittest.TestCase):
39 def _run(self, serp: list[dict], topic: str, count: int = 3) -> list[str]:
40 config = {"BRAVE_API_KEY": "test-key"}
41 with mock.patch.object(
42 competitors.grounding, "web_search", return_value=(serp, {})
43 ):
44 with redirect_stderr(io.StringIO()):
45 return competitors.discover_competitors(topic, count, config)
46
47 def test_openai_surfaces_anthropic_and_peers(self):
48 results = self._run(OPENAI_SERP, "OpenAI", count=3)
49 self.assertEqual(len(results), 3)
50 joined = " ".join(results)
51 self.assertIn("Anthropic", joined)
52 self.assertIn("xAI", joined)
53 # Should not surface the topic itself
54 self.assertNotIn("OpenAI", results)
55 self.assertFalse(
56 any("OpenAI" in entity for entity in results),
57 f"Topic token leaked into results: {results}",
58 )
59
60 def test_kanye_surfaces_rap_peers(self):
61 results = self._run(KANYE_SERP, "Kanye West", count=2)
62 self.assertEqual(len(results), 2)
63 joined = " ".join(results)
64 self.assertTrue(
65 "Drake" in joined and "Kendrick Lamar" in joined,
66 f"Expected Drake and Kendrick Lamar in {results}",
67 )
68
69 def test_empty_serp_returns_empty(self):
70 results = self._run([], "OpenAI", count=3)
71 self.assertEqual(results, [])
72
73 def test_no_backend_returns_empty(self):
74 err = io.StringIO()
75 with redirect_stderr(err):
76 results = competitors.discover_competitors("OpenAI", 3, config={})
77 self.assertEqual(results, [])
78 self.assertIn("No web search backend", err.getvalue())
79
80 def test_backend_error_returns_empty(self):
81 config = {"BRAVE_API_KEY": "test-key"}
82
83 def boom(*_args, **_kwargs):
84 raise RuntimeError("SERP provider offline")
85
86 err = io.StringIO()
87 with mock.patch.object(competitors.grounding, "web_search", side_effect=boom):
88 with redirect_stderr(err):
89 results = competitors.discover_competitors("OpenAI", 3, config)
90 self.assertEqual(results, [])
91 self.assertIn("Search failed", err.getvalue())
92
93 def test_topic_tokens_filtered(self):
94 """Candidates overlapping topic tokens are rejected."""
95 serp = _serp(
96 [
97 ("Open AI vs Anthropic", "Open AI, Anthropic, and Google lead."),
98 ("OpenAI Alternatives: Anthropic", "Anthropic is a competitor to Open AI."),
99 ]
100 )
101 results = self._run(serp, "OpenAI", count=3)
102 # "Open AI" shares the "openai" lowercased-concatenation? Actually tokenizer
103 # splits "Open AI" into ["open", "ai"]. Topic "OpenAI" tokenizes to ["openai"].
104 # They do not overlap at the token level, which is fine — the filter is
105 # best-effort. We only assert that bare "OpenAI" is filtered and real
106 # competitors still surface.
107 self.assertNotIn("OpenAI", results)
108 self.assertIn("Anthropic", results)
109
110 def test_deduplicates_case_insensitively(self):
111 serp = _serp(
112 [
113 ("Anthropic vs Gemini", "anthropic is strong."),
114 ("ANTHROPIC makes Claude", "Anthropic announced Claude 4."),
115 ]
116 )
117 results = self._run(serp, "OpenAI", count=3)
118 # "Anthropic" should appear exactly once (first-seen capitalization wins).
119 anthropic_matches = [r for r in results if r.lower() == "anthropic"]
120 self.assertEqual(len(anthropic_matches), 1)
121
122 def test_count_one_returns_single(self):
123 results = self._run(OPENAI_SERP, "OpenAI", count=1)
124 self.assertEqual(len(results), 1)
125
126 def test_stopword_only_candidates_rejected(self):
127 serp = _serp(
128 [
129 ("Top Alternatives", "Best Competitors and Top Tools."),
130 ("Free Software Reviews", "Complete Guide to The Options."),
131 ]
132 )
133 results = self._run(serp, "Widget", count=5)
134 self.assertEqual(
135 results, [],
136 f"Stopword-only phrases should not be returned: got {results}",
137 )
138
139 def test_count_zero_returns_empty(self):
140 results = self._run(OPENAI_SERP, "OpenAI", count=0)
141 self.assertEqual(results, [])
142
143 def test_exa_company_search_is_used_even_when_brave_is_the_web_backend(self):
144 config = {"BRAVE_API_KEY": "brave-key", "EXA_API_KEY": "exa-key"}
145 exa_items = [
146 {"title": "OpenAI", "url": "https://openai.com/"},
147 {"title": "Anthropic | Building reliable AI", "url": "https://www.anthropic.com/"},
148 {"title": "Anthropic", "url": "https://www.anthropic.com/about"},
149 {"title": "xAI - Grok", "url": "https://x.ai/"},
150 {"title": "Google DeepMind", "url": "https://deepmind.google/"},
151 ]
152 with mock.patch.object(
153 competitors.grounding, "exa_company_search",
154 return_value=(exa_items, {"label": "exa", "category": "company"}),
155 ) as exa, mock.patch.object(
156 competitors.grounding, "web_search",
157 ) as web:
158 with redirect_stderr(io.StringIO()):
159 results = competitors.discover_competitors(
160 "OpenAI", 2, config, is_company=True,
161 )
162 self.assertEqual(results, ["Anthropic", "xAI"])
163 exa.assert_called_once()
164 web.assert_not_called()
165 self.assertIn("OpenAI", exa.call_args.args[0])
166 self.assertTrue(exa.call_args.kwargs.get("objective"))
167
168 def test_exa_partial_results_are_filled_from_keyword_serps(self):
169 config = {"BRAVE_API_KEY": "brave-key", "EXA_API_KEY": "exa-key"}
170 exa_items = [
171 {"title": "Anthropic", "url": "https://www.anthropic.com/"},
172 ]
173 with mock.patch.object(
174 competitors.grounding, "exa_company_search",
175 return_value=(exa_items, {}),
176 ), mock.patch.object(
177 competitors.grounding, "web_search", return_value=(OPENAI_SERP, {}),
178 ):
179 with redirect_stderr(io.StringIO()):
180 results = competitors.discover_competitors(
181 "OpenAI", 3, config, is_company=True,
182 )
183 self.assertEqual(results[0], "Anthropic")
184 self.assertEqual(len(results), 3)
185 self.assertNotIn("OpenAI", results)
186
187 def test_exa_failure_falls_back_to_keyword_serps(self):
188 config = {"BRAVE_API_KEY": "brave-key", "EXA_API_KEY": "exa-key"}
189 with mock.patch.object(
190 competitors.grounding, "exa_company_search",
191 side_effect=RuntimeError("Exa 400"),
192 ), mock.patch.object(
193 competitors.grounding, "web_search", return_value=(OPENAI_SERP, {}),
194 ):
195 err = io.StringIO()
196 with redirect_stderr(err):
197 results = competitors.discover_competitors(
198 "OpenAI", 2, config, is_company=True,
199 )
200 self.assertTrue(results)
201 self.assertIn("Exa company search failed", err.getvalue())
202
203 def test_brave_only_skips_exa_company_search(self):
204 config = {"BRAVE_API_KEY": "brave-key"}
205 with mock.patch.object(
206 competitors.grounding, "exa_company_search",
207 ) as exa, mock.patch.object(
208 competitors.grounding, "web_search", return_value=(OPENAI_SERP, {}),
209 ):
210 with redirect_stderr(io.StringIO()):
211 results = competitors.discover_competitors("OpenAI", 2, config)
212 exa.assert_not_called()
213 self.assertTrue(results)
214
215 def test_non_company_topic_does_not_use_exa_company_index(self):
216 config = {"BRAVE_API_KEY": "brave-key", "EXA_API_KEY": "exa-key"}
217 with mock.patch.object(
218 competitors.grounding, "exa_company_search",
219 ) as exa, mock.patch.object(
220 competitors.grounding, "web_search", return_value=(KANYE_SERP, {}),
221 ):
222 with redirect_stderr(io.StringIO()):
223 results = competitors.discover_competitors("Kanye West", 2, config)
224 exa.assert_not_called()
225 joined = " ".join(results)
226 self.assertTrue(
227 "Drake" in joined and "Kendrick Lamar" in joined,
228 f"Expected Drake and Kendrick Lamar in {results}",
229 )
230
231 def test_exa_human_site_keeps_keyword_competitor_path(self):
232 config = {
233 "BRAVE_API_KEY": "brave-key",
234 "EXA_API_KEY": "exa-key",
235 "_company": {
236 "company": "Kanye West",
237 "company_site": "https://kanyewest.com/",
238 "company_source": "exa",
239 "company_peer_discovery": "keyword",
240 },
241 }
242 with mock.patch.object(
243 competitors.grounding, "exa_company_search",
244 ) as exa, mock.patch.object(
245 competitors.grounding, "web_search", return_value=(KANYE_SERP, {}),
246 ):
247 with redirect_stderr(io.StringIO()):
248 results = competitors.discover_competitors("Kanye West", 2, config)
249 exa.assert_not_called()
250 joined = " ".join(results)
251 self.assertTrue(
252 "Drake" in joined and "Kendrick Lamar" in joined,
253 f"Expected Drake and Kendrick Lamar in {results}",
254 )
255
256 def test_company_led_by_person_skips_exa_company_index(self):
257 config = {
258 "BRAVE_API_KEY": "brave-key",
259 "EXA_API_KEY": "exa-key",
260 "_company": {
261 "company": "Nvidia",
262 "company_site": "https://www.nvidia.com/",
263 "company_via_person": True,
264 },
265 }
266 with mock.patch.object(
267 competitors.grounding, "exa_company_search",
268 ) as exa, mock.patch.object(
269 competitors.grounding, "web_search", return_value=(OPENAI_SERP, {}),
270 ):
271 with redirect_stderr(io.StringIO()):
272 results = competitors.discover_competitors("Jensen Huang", 2, config)
273 exa.assert_not_called()
274 self.assertTrue(results)
275
276 def test_exa_non_business_site_keeps_keyword_competitor_path(self):
277 config = {
278 "BRAVE_API_KEY": "brave-key",
279 "EXA_API_KEY": "exa-key",
280 "_company": {
281 "company": "Python",
282 "company_site": "https://python.org/",
283 "company_source": "exa",
284 "company_peer_discovery": "keyword",
285 },
286 }
287 with mock.patch.object(
288 competitors.grounding, "exa_company_search",
289 ) as exa, mock.patch.object(
290 competitors.grounding, "web_search", return_value=(OPENAI_SERP, {}),
291 ):
292 with redirect_stderr(io.StringIO()):
293 results = competitors.discover_competitors("Python", 2, config)
294 exa.assert_not_called()
295 self.assertTrue(results)
296
297 def test_exa_food_homonym_keeps_company_competitor_index(self):
298 config = {
299 "EXA_API_KEY": "exa-key",
300 "_company": {
301 "company": "Granola",
302 "company_site": "https://granola.so/",
303 "company_source": "exa",
304 },
305 }
306 exa_items = [
307 {"title": "Otter", "url": "https://otter.ai/"},
308 {"title": "Fireflies", "url": "https://fireflies.ai/"},
309 ]
310 with mock.patch.object(
311 competitors.grounding, "exa_company_search",
312 return_value=(exa_items, {"label": "exa", "category": "company"}),
313 ) as exa, mock.patch.object(
314 competitors.grounding, "web_search",
315 ) as web:
316 with redirect_stderr(io.StringIO()):
317 results = competitors.discover_competitors("Granola", 2, config)
318 exa.assert_called_once()
319 web.assert_not_called()
320 self.assertEqual(results, ["Otter", "Fireflies"])
321
322 def test_exa_strips_trailing_and_unbalanced_parentheticals(self):
323 config = {"EXA_API_KEY": "exa-key"}
324 exa_items = [
325 {"title": "xPay (YC W24", "url": "https://xpay.example/"},
326 {"title": "Adyen (payments)", "url": "https://www.adyen.com/"},
327 {"title": "(YC W24)", "url": "https://www.ycombinator.com/"},
328 {"title": "Klarna [fintech]", "url": "https://www.klarna.com/"},
329 {"title": " [stealth] ", "url": "https://example.test/empty"},
330 {"title": "Payoneer - global payments", "url": "https://www.payoneer.com/"},
331 ]
332 with mock.patch.object(
333 competitors.grounding, "exa_company_search",
334 return_value=(exa_items, {"label": "exa", "category": "company"}),
335 ) as exa, mock.patch.object(
336 competitors.grounding, "web_search",
337 ) as web:
338 with redirect_stderr(io.StringIO()):
339 results = competitors.discover_competitors(
340 "Stripe", 4, config, is_company=True,
341 )
342 self.assertEqual(results, ["xPay", "Adyen", "Klarna", "Payoneer"])
343 self.assertFalse(any("(" in name or "[" in name for name in results))
344 exa.assert_called_once()
345 web.assert_not_called()
346
347 class NullSnippetTest(unittest.TestCase):
348 def test_null_title_or_snippet_contributes_no_text(self):
349 serp = [
350 {"title": "Anthropic", "snippet": None, "url": "https://example.test/1"},
351 {"title": "Mistral AI", "snippet": None, "url": "https://example.test/2"},
352 {"title": "Cohere", "snippet": None, "url": "https://example.test/3"},
353 ]
354 self.assertEqual(
355 competitors._extract_peer_entities(serp, "open models", limit=3),
356 ["Anthropic", "Mistral AI", "Cohere"],
357 )
358
359 def test_null_title_still_reads_snippet(self):
360 serp = [
361 {
362 "title": None,
363 "snippet": "Anthropic and Mistral AI lead the open models space.",
364 "url": "https://example.test/1",
365 },
366 {"title": "Cohere", "snippet": None, "url": "https://example.test/2"},
367 ]
368 self.assertEqual(
369 competitors._extract_peer_entities(serp, "open models", limit=3),
370 ["Anthropic", "Mistral AI", "Cohere"],
371 )
372
373
374 if __name__ == "__main__":
375 unittest.main()
376
376 lines PYTHON