| 1 | """Tests for polymarket.py - Polymarket prediction market search.""" |
| 2 | |
| 3 | import copy |
| 4 | import json |
| 5 | from unittest.mock import Mock, patch |
| 6 | |
| 7 | import pytest |
| 8 | |
| 9 | from lib import polymarket |
| 10 | |
| 11 | # === Helper Functions === |
| 12 | |
| 13 | |
| 14 | def create_mock_event( |
| 15 | event_id="evt-123", |
| 16 | title="Test Event", |
| 17 | slug="test-event", |
| 18 | volume24hr=100000, |
| 19 | liquidity=50000, |
| 20 | closed=False, |
| 21 | markets=None, |
| 22 | ): |
| 23 | """Create a mock Polymarket event.""" |
| 24 | if markets is None: |
| 25 | markets = [create_mock_market()] |
| 26 | |
| 27 | return { |
| 28 | "id": event_id, |
| 29 | "title": title, |
| 30 | "slug": slug, |
| 31 | "active": True, |
| 32 | "closed": closed, |
| 33 | "volume24hr": volume24hr, |
| 34 | "liquidity": liquidity, |
| 35 | "markets": markets, |
| 36 | } |
| 37 | |
| 38 | |
| 39 | def create_mock_market( |
| 40 | market_id="mkt-123", |
| 41 | question="Will X happen?", |
| 42 | outcomes='["Yes", "No"]', |
| 43 | prices='["0.60", "0.40"]', |
| 44 | volume="100000", |
| 45 | liquidity="50000", |
| 46 | closed=False, |
| 47 | ): |
| 48 | """Create a mock Polymarket market.""" |
| 49 | return { |
| 50 | "id": market_id, |
| 51 | "question": question, |
| 52 | "active": True, |
| 53 | "closed": closed, |
| 54 | "outcomes": outcomes, |
| 55 | "outcomePrices": prices, |
| 56 | "volume": volume, |
| 57 | "liquidity": liquidity, |
| 58 | } |
| 59 | |
| 60 | # === Tests for _extract_core_subject() === |
| 61 | |
| 62 | |
| 63 | def test_extract_core_subject_basic(): |
| 64 | """Test basic subject extraction.""" |
| 65 | result = polymarket._extract_core_subject("AI frameworks") |
| 66 | assert result == "AI frameworks" |
| 67 | |
| 68 | |
| 69 | def test_extract_core_subject_with_time_prefix(): |
| 70 | """Test stripping time prefixes.""" |
| 71 | result = polymarket._extract_core_subject("last 7 days AI frameworks") |
| 72 | assert result == "AI frameworks" |
| 73 | |
| 74 | |
| 75 | def test_extract_core_subject_with_question_prefix(): |
| 76 | """Test stripping question prefixes.""" |
| 77 | result = polymarket._extract_core_subject("what are people saying about Kanye West") |
| 78 | assert result == "Kanye West" |
| 79 | |
| 80 | |
| 81 | def test_extract_core_subject_multiple_prefixes(): |
| 82 | """Test handling multiple prefix patterns.""" |
| 83 | result = polymarket._extract_core_subject("research AI models") |
| 84 | assert result == "AI models" |
| 85 | |
| 86 | # === Tests for filter_items_against_topic() === |
| 87 | |
| 88 | |
| 89 | def test_topic_filter_blocks_shared_domain_token_when_hard_word_misses(): |
| 90 | """Mixed topics must not accept unrelated markets via a shared domain token.""" |
| 91 | items = [{"title": "Will the Kyoto Protocol survive?"}] |
| 92 | assert polymarket.filter_items_against_topic("MCP protocol benchmark", items) == [] |
| 93 | |
| 94 | # === Tests for _parse_outcome_prices() === |
| 95 | |
| 96 | |
| 97 | def test_parse_outcome_prices_basic(): |
| 98 | """Test basic outcome price parsing.""" |
| 99 | market = { |
| 100 | "outcomes": '["Yes", "No"]', |
| 101 | "outcomePrices": '["0.65", "0.35"]', |
| 102 | } |
| 103 | |
| 104 | result = polymarket._parse_outcome_prices(market) |
| 105 | |
| 106 | assert len(result) == 2 |
| 107 | assert result[0] == ("Yes", 0.65) |
| 108 | assert result[1] == ("No", 0.35) |
| 109 | |
| 110 | |
| 111 | def test_parse_outcome_prices_already_parsed(): |
| 112 | """Test handling when outcomes/prices are already lists.""" |
| 113 | market = { |
| 114 | "outcomes": ["Yes", "No"], |
| 115 | "outcomePrices": ["0.70", "0.30"], |
| 116 | } |
| 117 | |
| 118 | result = polymarket._parse_outcome_prices(market) |
| 119 | |
| 120 | assert len(result) == 2 |
| 121 | assert result[0][0] == "Yes" |
| 122 | assert result[0][1] == 0.70 |
| 123 | |
| 124 | |
| 125 | def test_parse_outcome_prices_multi_outcome(): |
| 126 | """Test multi-outcome markets.""" |
| 127 | market = { |
| 128 | "outcomes": '["Team A", "Team B", "Team C", "Team D"]', |
| 129 | "outcomePrices": '["0.40", "0.30", "0.20", "0.10"]', |
| 130 | } |
| 131 | |
| 132 | result = polymarket._parse_outcome_prices(market) |
| 133 | |
| 134 | assert len(result) == 4 |
| 135 | assert result[0] == ("Team A", 0.40) |
| 136 | assert result[3] == ("Team D", 0.10) |
| 137 | |
| 138 | |
| 139 | def test_parse_outcome_prices_missing_data(): |
| 140 | """Test handling of missing outcome prices.""" |
| 141 | market = {"outcomes": '["Yes"]'} |
| 142 | |
| 143 | result = polymarket._parse_outcome_prices(market) |
| 144 | |
| 145 | assert result == [] |
| 146 | |
| 147 | |
| 148 | def test_parse_outcome_prices_invalid_json(): |
| 149 | """Test handling of invalid JSON.""" |
| 150 | market = { |
| 151 | "outcomes": "not valid json", |
| 152 | "outcomePrices": "also not valid", |
| 153 | } |
| 154 | |
| 155 | result = polymarket._parse_outcome_prices(market) |
| 156 | |
| 157 | assert result == [] |
| 158 | |
| 159 | # === Tests for _format_price_movement() === |
| 160 | |
| 161 | |
| 162 | def test_format_price_movement_one_day(): |
| 163 | """Test formatting one-day price movement.""" |
| 164 | market = { |
| 165 | "oneDayPriceChange": 0.05, # Up 5% |
| 166 | "oneWeekPriceChange": 0.02, |
| 167 | "oneMonthPriceChange": 0.01, |
| 168 | } |
| 169 | |
| 170 | result = polymarket._format_price_movement(market) |
| 171 | |
| 172 | assert "up" in result |
| 173 | assert "5.0%" in result |
| 174 | assert "today" in result |
| 175 | |
| 176 | |
| 177 | def test_format_price_movement_negative(): |
| 178 | """Test formatting negative price movement.""" |
| 179 | market = { |
| 180 | "oneDayPriceChange": -0.15, # Down 15% |
| 181 | } |
| 182 | |
| 183 | result = polymarket._format_price_movement(market) |
| 184 | |
| 185 | assert "down" in result |
| 186 | assert "15.0%" in result |
| 187 | |
| 188 | |
| 189 | def test_format_price_movement_picks_largest(): |
| 190 | """Test that largest change is picked.""" |
| 191 | market = { |
| 192 | "oneDayPriceChange": 0.02, |
| 193 | "oneWeekPriceChange": 0.10, # Largest |
| 194 | "oneMonthPriceChange": 0.05, |
| 195 | } |
| 196 | |
| 197 | result = polymarket._format_price_movement(market) |
| 198 | |
| 199 | assert "10.0%" in result |
| 200 | assert "this week" in result |
| 201 | |
| 202 | |
| 203 | def test_format_price_movement_below_threshold(): |
| 204 | """Test that small changes return None.""" |
| 205 | market = { |
| 206 | "oneDayPriceChange": 0.005, # 0.5%, below 1% threshold |
| 207 | } |
| 208 | |
| 209 | result = polymarket._format_price_movement(market) |
| 210 | |
| 211 | assert result is None |
| 212 | |
| 213 | |
| 214 | def test_format_price_movement_missing_data(): |
| 215 | """Test handling of missing price change data.""" |
| 216 | market = {} |
| 217 | |
| 218 | result = polymarket._format_price_movement(market) |
| 219 | |
| 220 | assert result is None |
| 221 | |
| 222 | # === Tests for _shorten_question() === |
| 223 | |
| 224 | |
| 225 | def test_shorten_question_will_pattern(): |
| 226 | """Test shortening 'Will X...' questions.""" |
| 227 | result = polymarket._shorten_question("Will Arizona win the NCAA Tournament?") |
| 228 | |
| 229 | assert result == "Arizona" |
| 230 | |
| 231 | |
| 232 | def test_shorten_question_complex_will(): |
| 233 | """Test shortening complex Will questions.""" |
| 234 | result = polymarket._shorten_question("Will Duke be a number 1 seed?") |
| 235 | |
| 236 | assert result == "Duke" |
| 237 | |
| 238 | |
| 239 | def test_shorten_question_no_pattern(): |
| 240 | """Test questions that don't match patterns.""" |
| 241 | result = polymarket._shorten_question("Arizona wins championship") |
| 242 | |
| 243 | # Should return original or truncated |
| 244 | assert len(result) > 0 |
| 245 | |
| 246 | |
| 247 | def test_shorten_question_long(): |
| 248 | """Test truncation of very long questions.""" |
| 249 | long_q = "A" * 100 |
| 250 | result = polymarket._shorten_question(long_q) |
| 251 | |
| 252 | assert len(result) <= 40 |
| 253 | |
| 254 | |
| 255 | def test_shorten_question_fallback_strips_leading_article(): |
| 256 | """The truncation fallback must not keep a leading article like 'an' or 'the'. |
| 257 | |
| 258 | Without stripping, a question like 'an Anthropic Claude model scores...' yields |
| 259 | a lead name of just 'an', which renders as the mangled 'an 19%' footer fragment. |
| 260 | """ |
| 261 | result = polymarket._shorten_question( |
| 262 | "an Anthropic Claude model scores at the top of the leaderboard this month" |
| 263 | ) |
| 264 | lower = result.lower() |
| 265 | assert not lower.startswith("a ") |
| 266 | assert not lower.startswith("an ") |
| 267 | assert not lower.startswith("the ") |
| 268 | |
| 269 | |
| 270 | def test_shorten_question_fallback_keeps_non_article_lead(): |
| 271 | """Stripping only removes a leading article, not the first informative word.""" |
| 272 | result = polymarket._shorten_question( |
| 273 | "Anthropic ships a major Claude model update before the end of this month" |
| 274 | ) |
| 275 | assert result.lower().startswith("anthropic") |
| 276 | |
| 277 | # === Tests for search_polymarket() === |
| 278 | |
| 279 | |
| 280 | def test_search_polymarket_result_cap(): |
| 281 | """Test that result cap configuration exists.""" |
| 282 | assert "quick" in polymarket.RESULT_CAP |
| 283 | assert "default" in polymarket.RESULT_CAP |
| 284 | assert "deep" in polymarket.RESULT_CAP |
| 285 | |
| 286 | # Deep should return more results |
| 287 | assert polymarket.RESULT_CAP["deep"] >= polymarket.RESULT_CAP["quick"] |
| 288 | |
| 289 | |
| 290 | @patch('lib.polymarket.http.request') |
| 291 | def test_search_polymarket_http_error_handling(mock_request): |
| 292 | """Test graceful handling of HTTP errors.""" |
| 293 | from lib.http import HTTPError |
| 294 | mock_request.side_effect = HTTPError("HTTP 429: Rate limit", status_code=429) |
| 295 | |
| 296 | result = polymarket.search_polymarket("test", "2026-01-01", "2026-01-31") |
| 297 | |
| 298 | assert mock_request.call_count > 0 |
| 299 | assert all(call.args[0] == "GET" for call in mock_request.call_args_list) |
| 300 | assert result["events"] == [] |
| 301 | assert "HTTP 429: Rate limit" in result["error"] |
| 302 | |
| 303 | # Gamma public-search, answered by search term. |
| 304 | def _gamma(responses): |
| 305 | """A stand-in for http.request that answers each public-search by its q.""" |
| 306 | calls = [] |
| 307 | |
| 308 | def request(method, url, **_kwargs): |
| 309 | from urllib.parse import parse_qs, urlsplit |
| 310 | params = {k: v[0] for k, v in parse_qs(urlsplit(url).query).items()} |
| 311 | calls.append(params) |
| 312 | return copy.deepcopy(responses.get(params["q"], {"events": []})) |
| 313 | |
| 314 | return request, calls |
| 315 | |
| 316 | |
| 317 | def _search_event(event_id, title, labels=(), closed=False, neg_risk=False): |
| 318 | markets = [create_mock_market(market_id=f"{event_id}-{n}", question=f"Will {label} win?") |
| 319 | for n, label in enumerate(labels)] |
| 320 | for market, label in zip(markets, labels): |
| 321 | market["groupItemTitle"] = label |
| 322 | return {**create_mock_event(event_id=event_id, title=title, closed=closed, |
| 323 | markets=markets or None), "negRisk": neg_risk} |
| 324 | |
| 325 | |
| 326 | def test_search_issues_one_volume_sorted_call_per_term(monkeypatch): |
| 327 | request, calls = _gamma({"49ers": {"events": [_search_event("1", "49ers vs Vikings")]}}) |
| 328 | monkeypatch.setattr(polymarket.http, "request", request) |
| 329 | |
| 330 | result = polymarket.search_polymarket("49ers", "2026-10-17", "2026-11-16") |
| 331 | |
| 332 | assert calls == [{ |
| 333 | "q": "49ers", "sort": "volume", "events_status": "active", |
| 334 | "keep_closed_markets": "0", "limit_per_type": "20", |
| 335 | }] |
| 336 | assert [event["id"] for event in result["events"]] == ["1"] |
| 337 | |
| 338 | |
| 339 | @pytest.mark.parametrize("depth, limit", [("quick", "10"), ("deep", "50")]) |
| 340 | def test_search_depth_sets_the_page_size(monkeypatch, depth, limit): |
| 341 | request, calls = _gamma({}) |
| 342 | monkeypatch.setattr(polymarket.http, "request", request) |
| 343 | polymarket.search_polymarket("49ers", "2026-10-17", "2026-11-16", depth=depth) |
| 344 | assert [call["limit_per_type"] for call in calls] == [limit] |
| 345 | |
| 346 | |
| 347 | def test_search_runs_each_alias_and_merges_events_by_id(monkeypatch): |
| 348 | shared = _search_event("7", "F1: Las Vegas Grand Prix Winner") |
| 349 | request, calls = _gamma({ |
| 350 | "Formula 1": {"events": [shared]}, |
| 351 | "F1": {"events": [copy.deepcopy(shared), _search_event("8", "F1: Action of the Year")]}, |
| 352 | }) |
| 353 | monkeypatch.setattr(polymarket.http, "request", request) |
| 354 | |
| 355 | result = polymarket.search_polymarket( |
| 356 | "Formula 1", "2026-10-17", "2026-11-16", |
| 357 | hints=polymarket.PolymarketHints.coerce({"aliases": ["F1"]}), |
| 358 | ) |
| 359 | |
| 360 | assert sorted(call["q"] for call in calls) == ["F1", "Formula 1"] |
| 361 | assert [event["id"] for event in result["events"]] == ["7", "8"] |
| 362 | |
| 363 | |
| 364 | ROOKIES = ["Yaxel Lendeborg", "Cameron Boozer", "AJ Dybantsa", "Darryn Peterson"] |
| 365 | |
| 366 | |
| 367 | def test_search_looks_up_a_related_name_only_when_the_pool_lacks_it(monkeypatch): |
| 368 | rookie = _search_event("2", "NBA: 2026-27 Rookie of the Year", labels=ROOKIES, neg_risk=True) |
| 369 | request, calls = _gamma({"Warriors": {"events": [ |
| 370 | _search_event("1", "NBA: 2027 Champion", labels=["Golden State Warriors"]), rookie, |
| 371 | ]}}) |
| 372 | monkeypatch.setattr(polymarket.http, "request", request) |
| 373 | |
| 374 | polymarket.search_polymarket( |
| 375 | "Warriors", "2026-10-17", "2026-11-16", |
| 376 | hints=polymarket.PolymarketHints.coerce({"related": [ |
| 377 | {"name": "Yaxel Lendeborg", "relation": "player"}, |
| 378 | {"name": "Stephen Curry", "relation": "player"}, |
| 379 | ]}), |
| 380 | ) |
| 381 | |
| 382 | assert [call["q"] for call in calls] == ["Warriors", "Stephen Curry"] |
| 383 | |
| 384 | |
| 385 | def test_search_looks_up_a_related_name_the_pool_holds_only_outside_a_race(monkeypatch): |
| 386 | # A game prop naming the player is not the award race the name leads. |
| 387 | prop = _search_event("3", "Warriors vs. Lakers: Player Props", |
| 388 | labels=["Yaxel Lendeborg", "Stephen Curry"]) |
| 389 | small = _search_event("4", "Who scores first?", labels=ROOKIES[:3], neg_risk=True) |
| 390 | request, calls = _gamma({"Warriors": {"events": [prop, small]}}) |
| 391 | monkeypatch.setattr(polymarket.http, "request", request) |
| 392 | |
| 393 | polymarket.search_polymarket( |
| 394 | "Warriors", "2026-10-17", "2026-11-16", |
| 395 | hints=polymarket.PolymarketHints.coerce({"related": [ |
| 396 | {"name": "Yaxel Lendeborg", "relation": "player"}, |
| 397 | {"name": "Cameron Boozer", "relation": "player"}, |
| 398 | ]}), |
| 399 | ) |
| 400 | |
| 401 | assert sorted(call["q"] for call in calls) == ["Cameron Boozer", "Warriors", "Yaxel Lendeborg"] |
| 402 | |
| 403 | |
| 404 | def test_search_drops_events_gamma_returns_closed(monkeypatch): |
| 405 | request, _calls = _gamma({"49ers": {"events": [ |
| 406 | _search_event("1", "49ers open"), _search_event("2", "49ers closed", closed=True), |
| 407 | ]}}) |
| 408 | monkeypatch.setattr(polymarket.http, "request", request) |
| 409 | result = polymarket.search_polymarket("49ers", "2026-10-17", "2026-11-16") |
| 410 | assert [event["id"] for event in result["events"]] == ["1"] |
| 411 | |
| 412 | |
| 413 | class _Response: |
| 414 | status = 200 |
| 415 | |
| 416 | def __init__(self, body): |
| 417 | self._body = json.dumps(body).encode() |
| 418 | self.headers = {} |
| 419 | |
| 420 | def read(self, size=-1): |
| 421 | return self._body |
| 422 | |
| 423 | def __enter__(self): |
| 424 | return self |
| 425 | |
| 426 | def __exit__(self, *_exc): |
| 427 | return False |
| 428 | |
| 429 | |
| 430 | def _rate_limited(url): |
| 431 | import io |
| 432 | import urllib.error |
| 433 | return urllib.error.HTTPError(url, 429, "Too Many Requests", {}, io.BytesIO(b"")) |
| 434 | |
| 435 | |
| 436 | def test_search_retries_a_rate_limited_call(monkeypatch): |
| 437 | answers = [_rate_limited, lambda _url: _Response({"events": [_search_event("1", "49ers")]})] |
| 438 | |
| 439 | def urlopen(req, timeout=None): |
| 440 | answer = answers.pop(0)(req.full_url) |
| 441 | if isinstance(answer, Exception): |
| 442 | raise answer |
| 443 | return answer |
| 444 | |
| 445 | monkeypatch.setattr("lib.http.urllib.request.urlopen", urlopen) |
| 446 | monkeypatch.setattr("lib.http.time.sleep", lambda _seconds: None) |
| 447 | |
| 448 | result = polymarket.search_polymarket("49ers", "2026-10-17", "2026-11-16") |
| 449 | |
| 450 | assert [event["id"] for event in result["events"]] == ["1"] |
| 451 | assert "error" not in result |
| 452 | |
| 453 | |
| 454 | def test_search_reports_partial_when_one_term_fails_and_another_returns(monkeypatch): |
| 455 | request, _calls = _gamma({"Formula 1": {"events": [_search_event("7", "F1: Las Vegas Grand Prix")]}}) |
| 456 | |
| 457 | def flaky(method, url, **kwargs): |
| 458 | if "q=F1&" in url: |
| 459 | return {"events": [], "error": "HTTP 429: Rate limit"} |
| 460 | return request(method, url, **kwargs) |
| 461 | |
| 462 | monkeypatch.setattr(polymarket.http, "request", flaky) |
| 463 | |
| 464 | result = polymarket.search_polymarket( |
| 465 | "Formula 1", "2026-10-17", "2026-11-16", |
| 466 | hints=polymarket.PolymarketHints.coerce({"aliases": ["F1"]}), |
| 467 | ) |
| 468 | |
| 469 | assert [event["id"] for event in result["events"]] == ["7"] |
| 470 | assert result["partial"] is True |
| 471 | assert "429" in result["error"] |
| 472 | |
| 473 | |
| 474 | def test_search_passes_the_deadline_to_every_call(monkeypatch): |
| 475 | seen = [] |
| 476 | |
| 477 | def request(method, url, **kwargs): |
| 478 | seen.append(kwargs.get("deadline_monotonic")) |
| 479 | return {"events": []} |
| 480 | |
| 481 | monkeypatch.setattr(polymarket.http, "request", request) |
| 482 | polymarket.search_polymarket( |
| 483 | "Formula 1", "2026-10-17", "2026-11-16", |
| 484 | hints=polymarket.PolymarketHints.coerce({"aliases": ["F1"]}), deadline=1234.5, |
| 485 | ) |
| 486 | assert seen == [1234.5, 1234.5] |
| 487 | |
| 488 | |
| 489 | def test_search_skips_related_names_once_the_deadline_has_passed(monkeypatch): |
| 490 | request, calls = _gamma({"Warriors": {"events": [_search_event("1", "NBA: 2027 Champion")]}}) |
| 491 | monkeypatch.setattr(polymarket.http, "request", request) |
| 492 | |
| 493 | result = polymarket.search_polymarket( |
| 494 | "Warriors", "2026-10-17", "2026-11-16", |
| 495 | hints=polymarket.PolymarketHints.coerce({"related": [ |
| 496 | {"name": "Stephen Curry", "relation": "player"}, |
| 497 | ]}), |
| 498 | deadline=0.0, |
| 499 | ) |
| 500 | |
| 501 | assert [call["q"] for call in calls] == ["Warriors"] |
| 502 | assert result["partial"] is True |
| 503 | assert "deadline" in result["error"] |
| 504 | |
| 505 | |
| 506 | # === Tests for parse_polymarket_response() === |
| 507 | |
| 508 | |
| 509 | def test_parse_polymarket_response_basic(): |
| 510 | """Test basic response parsing.""" |
| 511 | response = { |
| 512 | "events": [create_mock_event( |
| 513 | title="Will AI surpass humans?", |
| 514 | volume24hr=500000, |
| 515 | )] |
| 516 | } |
| 517 | |
| 518 | items = polymarket.parse_polymarket_response(response, topic="AI") |
| 519 | |
| 520 | assert len(items) == 1 |
| 521 | assert items[0]["event_id"] == "evt-123" |
| 522 | assert items[0]["title"] == "Will AI surpass humans?" |
| 523 | assert items[0]["outcome_prices"] == [("Yes", 0.6), ("No", 0.4)] |
| 524 | |
| 525 | |
| 526 | def test_parse_polymarket_response_filters_closed(): |
| 527 | """Test that closed events are filtered.""" |
| 528 | response = { |
| 529 | "events": [ |
| 530 | create_mock_event(event_id="open", slug="open-event", closed=False, |
| 531 | markets=[create_mock_market(market_id="open-market")]), |
| 532 | create_mock_event(event_id="closed", slug="closed-event", closed=True, |
| 533 | markets=[create_mock_market(market_id="still-open-market")]), |
| 534 | ] |
| 535 | } |
| 536 | |
| 537 | items = polymarket.parse_polymarket_response(response) |
| 538 | |
| 539 | assert [item["event_id"] for item in items] == ["open"] |
| 540 | historical = polymarket.parse_polymarket_response(response, include_closed=True) |
| 541 | assert [item["event_id"] for item in historical] == ["open", "closed"] |
| 542 | |
| 543 | |
| 544 | def test_parse_polymarket_response_empty(): |
| 545 | """Test handling of empty response.""" |
| 546 | response = {"events": []} |
| 547 | |
| 548 | items = polymarket.parse_polymarket_response(response) |
| 549 | |
| 550 | assert items == [] |
| 551 | |
| 552 | |
| 553 | def test_parse_polymarket_response_market_url(): |
| 554 | """Test that Polymarket URLs are generated.""" |
| 555 | response = { |
| 556 | "events": [create_mock_event( |
| 557 | slug="test-event-slug", |
| 558 | title="Test Event" |
| 559 | )] |
| 560 | } |
| 561 | |
| 562 | items = polymarket.parse_polymarket_response(response, topic="test") |
| 563 | |
| 564 | assert len(items) == 1 |
| 565 | assert items[0]["url"] == "https://polymarket.com/event/test-event-slug" |
| 566 | |
| 567 | |
| 568 | def test_parse_polymarket_response_engagement(): |
| 569 | """Test that engagement/volume metrics are captured.""" |
| 570 | response = { |
| 571 | "events": [create_mock_event( |
| 572 | title="AI Event", |
| 573 | volume24hr=250000, |
| 574 | liquidity=100000, |
| 575 | markets=[{**create_mock_market(liquidity="1234"), "volume24hr": 5678}], |
| 576 | )] |
| 577 | } |
| 578 | |
| 579 | items = polymarket.parse_polymarket_response(response, topic="AI") |
| 580 | |
| 581 | assert len(items) == 1 |
| 582 | assert items[0]["volume24hr"] == 250000.0 |
| 583 | assert items[0]["liquidity"] == 100000.0 |
| 584 | |
| 585 | |
| 586 | def _claude_downtime_response(): |
| 587 | """An off-topic Polymarket event that mentions only the generic word 'Claude'.""" |
| 588 | return { |
| 589 | "events": [ |
| 590 | create_mock_event( |
| 591 | event_id="evt-noise", |
| 592 | title="Will Claude go down 3-5 times in June?", |
| 593 | slug="claude-downtime", |
| 594 | ), |
| 595 | ] |
| 596 | } |
| 597 | |
| 598 | |
| 599 | def test_parse_polymarket_response_filters_noise_on_full_subquery(): |
| 600 | """A multi-word subquery filters off-topic 'Claude downtime' noise. |
| 601 | |
| 602 | The downtime title names 'Claude' but not the whole phrase 'Claude Code |
| 603 | subagents workflow', so the entity matcher drops it. |
| 604 | """ |
| 605 | items = polymarket.parse_polymarket_response( |
| 606 | _claude_downtime_response(), topic="Claude Code subagents workflow" |
| 607 | ) |
| 608 | assert items == [] |
| 609 | |
| 610 | |
| 611 | def test_parse_polymarket_response_narrow_subquery_leaks_noise(): |
| 612 | """The SAME off-topic market leaks through a single-word subquery. |
| 613 | |
| 614 | 'claude' is named in the title, so the downtime market passes. Because the |
| 615 | pipeline previously fed the per-subquery search_query, filtering swung |
| 616 | between these two outcomes across the fanout; keying off the stable |
| 617 | original topic makes it consistent. |
| 618 | """ |
| 619 | items = polymarket.parse_polymarket_response( |
| 620 | _claude_downtime_response(), topic="claude" |
| 621 | ) |
| 622 | assert len(items) == 1 |
| 623 | |
| 624 | # === Tests for engagement scoring === |
| 625 | |
| 626 | |
| 627 | def test_engagement_with_volume(): |
| 628 | """Missing event metrics fall back to the selected market's values.""" |
| 629 | response = { |
| 630 | "events": [create_mock_event( |
| 631 | title="Test", |
| 632 | volume24hr=0, |
| 633 | liquidity=0, |
| 634 | markets=[{**create_mock_market(liquidity="6789"), "volume24hr": "1234"}], |
| 635 | )] |
| 636 | } |
| 637 | |
| 638 | items = polymarket.parse_polymarket_response(response, topic="test") |
| 639 | |
| 640 | assert len(items) == 1 |
| 641 | assert items[0]["volume24hr"] == 1234.0 |
| 642 | assert items[0]["liquidity"] == 6789.0 |
| 643 | |
| 644 | # === Tests for per-item relevance floor === |
| 645 | |
| 646 | |
| 647 | def test_per_item_relevance_floor_no_drops_when_all_high(): |
| 648 | """Nothing dropped when all items are above the floor.""" |
| 649 | response = {"events": [ |
| 650 | create_mock_event(event_id=event_id, title=f"Prediction market {event_id}") |
| 651 | for event_id in ["a", "b", "c"] |
| 652 | ]} |
| 653 | items = polymarket.parse_polymarket_response(response, topic="market") |
| 654 | assert [item["event_id"] for item in items] == ["a", "b", "c"] |
| 655 | assert all(item["relevance"] >= 0.30 for item in items) |
| 656 | |
| 657 | if __name__ == "__main__": |
| 658 | pytest.main([__file__, "-v"]) |
| 659 |