返回 last30days-skill
test_polymarket_hints_plan.py
根目录 / tests / test_polymarket_hints_plan.py
1 """The host plan's Polymarket hints: validation, plan round-trip, and per-entity runs."""
2
3 import json
4 from dataclasses import asdict
5 from unittest.mock import patch
6
7 import pytest
8
9 import last30days as cli
10 from lib import pipeline, planner, polymarket, schema
11 from tests.competitor_cli_audit_helpers import run_competitor_cli
12
13
14 def host_plan(**extra):
15 return {
16 "intent": "factual",
17 "freshness_mode": "balanced_recent",
18 "cluster_mode": "none",
19 "subqueries": [{
20 "label": "primary", "search_query": "Formula 1", "ranking_query": "Formula 1",
21 "sources": ["polymarket"], "weight": 1.0,
22 }],
23 **extra,
24 }
25
26
27 WARRIORS = {
28 "kind": "team",
29 "aliases": ["Golden State Warriors"],
30 "related": [
31 {"name": "Yaxel Lendeborg", "relation": "player"},
32 {"name": "Stephen Curry", "relation": "player"},
33 ],
34 }
35
36
37 def sanitize(raw, topic="Formula 1"):
38 return planner._sanitize_plan(raw, topic=topic, depth="default",
39 available_sources=["polymarket"], requested_sources=["polymarket"])
40
41
42 def polymarket_config(external_plan, topic="Formula 1"):
43 with patch.object(pipeline, "_retrieve_stream", return_value=([], {})) as retrieve:
44 pipeline.run(topic=topic, config={}, mock=True, web_backend="none",
45 requested_sources=["polymarket"], depth="default", external_plan=external_plan)
46 configs = [call.kwargs["config"] for call in retrieve.call_args_list
47 if call.kwargs["source"] == "polymarket"]
48 assert configs
49 return configs[0]
50
51
52 def test_alias_hint_reaches_the_polymarket_fetch():
53 raw = host_plan(polymarket_hints={"aliases": ["F1"]})
54 planner.validate_external_plan(raw)
55 config = polymarket_config(raw)
56 hints = polymarket.PolymarketHints.coerce(config["_polymarket_hints"])
57 assert hints.aliases == ("F1",)
58 assert hints.kind is None
59 assert hints.related == ()
60
61
62 def test_team_hint_with_related_players_reaches_the_fetch():
63 raw = host_plan(polymarket_hints=WARRIORS)
64 planner.validate_external_plan(raw)
65 hints = polymarket.PolymarketHints.coerce(polymarket_config(raw, "Warriors")["_polymarket_hints"])
66 assert hints.kind == "team"
67 assert hints.aliases == ("Golden State Warriors",)
68 assert hints.related == (
69 polymarket.RelatedName("Yaxel Lendeborg", "player"),
70 polymarket.RelatedName("Stephen Curry", "player"),
71 )
72
73
74 def test_hints_survive_sanitize_and_round_trip():
75 plan = sanitize(host_plan(polymarket_hints=WARRIORS), "Warriors")
76 assert plan.polymarket_hints == WARRIORS
77 assert schema.query_plan_from_dict(asdict(plan)) == plan
78 assert schema.query_plan_from_dict(schema.to_dict(plan)) == plan
79
80
81 @pytest.mark.parametrize("hints,message", [
82 ("F1", "polymarket_hints must be an object"),
83 ({"kind": "league"}, "polymarket_hints.kind"),
84 ({"aliases": "F1"}, "polymarket_hints.aliases"),
85 ({"aliases": ["F1", ""]}, "polymarket_hints.aliases"),
86 ({"aliases": ["x" * 81]}, "polymarket_hints.aliases"),
87 ({"aliases": ["a", "b", "c", "d", "e", "f"]}, "polymarket_hints.aliases"),
88 ({"related": {"name": "Stephen Curry", "relation": "player"}}, "polymarket_hints.related"),
89 ({"related": [{"name": "Stephen Curry", "relation": "coach"}]}, "polymarket_hints.related"),
90 ({"related": [{"name": "", "relation": "player"}]}, "polymarket_hints.related"),
91 ({"related": [{"name": f"P{i}", "relation": "player"} for i in range(6)]},
92 "polymarket_hints.related"),
93 ({"aliases": ["F1"], "teams": ["Ferrari"]}, "polymarket_hints"),
94 ])
95 def test_invalid_hints_are_rejected_with_a_clear_message(hints, message):
96 with pytest.raises(ValueError, match=message):
97 planner.validate_external_plan(host_plan(polymarket_hints=hints))
98
99
100 def test_plan_without_hints_is_unchanged():
101 raw = host_plan()
102 planner.validate_external_plan(raw)
103 plan = sanitize(raw)
104 assert plan.polymarket_hints is None
105 assert "polymarket_hints" not in schema.to_dict(plan)
106 legacy = schema.to_dict(plan)
107 assert schema.query_plan_from_dict(legacy) == plan
108 assert "_polymarket_hints" not in polymarket_config(raw)
109
110
111 def test_internal_planner_drops_malformed_hints_and_keeps_its_plan():
112 plan = sanitize(host_plan(polymarket_hints={"kind": "league", "aliases": "F1"}))
113 assert plan.subqueries
114 assert plan.polymarket_hints is None
115
116
117 def test_competitors_plan_accepts_and_validates_peer_hints(capsys):
118 out = cli.parse_competitors_plan(json.dumps({"Warriors": {"polymarket_hints": WARRIORS}}))
119 assert out["warriors"]["polymarket_hints"] == WARRIORS
120 assert "Unknown fields" not in capsys.readouterr().err
121 with pytest.raises(SystemExit):
122 cli.parse_competitors_plan(json.dumps({"Warriors": {"polymarket_hints": {"kind": "league"}}}))
123 assert "polymarket_hints.kind" in capsys.readouterr().err
124
125
126 def test_main_hints_and_keywords_do_not_leak_and_peer_hints_apply(monkeypatch, tmp_path):
127 main_plan = host_plan(polymarket_hints={"kind": "team", "aliases": ["MainBrand FC"]})
128 plan_file = tmp_path / "main-plan.json"
129 plan_file.write_text(json.dumps(main_plan), encoding="utf-8")
130 peer_hints = {"kind": "company", "aliases": ["Peer One Inc"]}
131 observed = run_competitor_cli(monkeypatch, tmp_path, args=[
132 "--plan", str(plan_file),
133 "--polymarket-keywords", "mainbrand",
134 "--competitors-plan", json.dumps({"PeerOne": {"polymarket_hints": peer_hints}}),
135 ])
136
137 assert observed.calls["MainBrand"]["external_plan"]["polymarket_hints"] == main_plan["polymarket_hints"]
138 assert observed.calls["MainBrand"]["config"]["_polymarket_keywords"] == ["mainbrand"]
139 for peer in ("PeerOne", "PeerTwo"):
140 assert "_polymarket_keywords" not in observed.calls[peer]["config"]
141 assert observed.calls["PeerOne"]["config"]["_polymarket_hints"] == {**peer_hints, "related": []}
142 assert "_polymarket_hints" not in observed.calls["PeerTwo"]["config"]
143
143 lines PYTHON