返回 last30days-skill
test_shortform_ab.py
根目录 / tests / test_shortform_ab.py
1 """Metric math for scripts/shortform_ab.py (offline, no engine runs)."""
2
3 from __future__ import annotations
4
5 import importlib.util
6 import sys
7 from pathlib import Path
8
9 _PATH = Path(__file__).resolve().parent.parent / "scripts" / "shortform_ab.py"
10 _SPEC = importlib.util.spec_from_file_location("shortform_ab", _PATH)
11 ab = importlib.util.module_from_spec(_SPEC)
12 sys.modules["shortform_ab"] = ab
13 _SPEC.loader.exec_module(ab)
14
15
16 def _tt(vid: str, views: int | None = None, day: str | None = "2026-11-10", **extra):
17 item = {"url": f"https://www.tiktok.com/@someone/video/{vid}", "published_at": day,
18 "engagement": {"views": views} if views is not None else {}}
19 item.update(extra)
20 return item
21
22
23 def _ig(code: str, likes: int | None = None, kind: str = "reel"):
24 return {"url": f"https://www.instagram.com/{kind}/{code}/", "engagement": {"likes": likes}}
25
26
27 def test_video_id_tiktok():
28 assert ab.video_id("tiktok", "https://www.tiktok.com/@a.b/video/7710481357683576094?lang=en") == "7710481357683576094"
29 assert ab.video_id("tiktok", "https://www.tiktok.com/@a/photo/7500000000000000001") == "7500000000000000001"
30 assert ab.video_id("tiktok", "https://www.tiktok.com/@a") is None
31 assert ab.video_id("tiktok", "") is None
32
33
34 def test_video_id_instagram():
35 assert ab.video_id("instagram", "https://www.instagram.com/reel/DfYRA2ghafT/") == "DfYRA2ghafT"
36 assert ab.video_id("instagram", "https://instagram.com/p/C-x_Y1z/?igsh=1") == "C-x_Y1z"
37 assert ab.video_id("instagram", "https://www.instagram.com/reels/Abc123/") == "Abc123"
38 assert ab.video_id("instagram", "https://www.instagram.com/someuser/") is None
39
40
41 def test_window_counts_splits_in_window_stale_and_undated():
42 items = [_tt("1", day="2026-10-22"), _tt("2", day="2026-11-21T08:00:00"),
43 _tt("3", day="2026-10-21"), _tt("4", day="2024-05-01"), _tt("5", day=None),
44 _tt("6", day="not a date")]
45 assert ab.window_counts(items, "2026-10-22", "2026-11-21") == {"in_window": 2, "stale": 2, "undated": 2}
46
47
48 def test_recall():
49 assert ab.recall({"a", "b", "c", "d"}, {"a", "c", "z"}) == 0.5
50 assert ab.recall(set(), {"a"}) is None
51 assert ab.recall({"a"}, set()) == 0.0
52
53
54 def test_head_recall_uses_top_ten_by_views_for_tiktok():
55 baseline = [_tt(str(i), views=i * 100) for i in range(1, 16)] # top 10 are ids 6..15
56 arm_ids = {"15", "14", "13", "12", "1", "2"}
57 assert ab.head_ids("tiktok", baseline) == [str(i) for i in range(15, 5, -1)]
58 assert ab.head_recall("tiktok", baseline, arm_ids) == 0.4
59
60
61 def test_head_recall_uses_likes_for_instagram_and_small_baselines():
62 baseline = [_ig("AAA", likes=5), _ig("BBB", likes=50), _ig("CCC", likes=None, kind="p")]
63 assert ab.head_ids("instagram", baseline) == ["BBB", "AAA", "CCC"]
64 assert ab.head_recall("instagram", baseline, {"BBB"}) == 1 / 3
65 assert ab.head_recall("instagram", [], {"BBB"}) is None
66
67
68 def test_completeness_per_field():
69 items = [
70 {"published_at": "2026-11-01", "author": "x", "body": "cap",
71 "engagement": {"views": 1, "likes": 2, "comments": 0}},
72 {"published_at": None, "author": "", "snippet": "",
73 "engagement": {"likes": 3}},
74 ]
75 comp = ab.completeness(items)
76 assert comp == {"date": 0.5, "creator": 0.5, "views": 0.5, "likes": 1.0, "comments": 0.5, "caption": 0.5}
77 assert ab.completeness([])["date"] is None
78
79
80 def test_p90_nearest_rank_and_median():
81 assert ab.p90([float(i) for i in range(1, 11)]) == 9.0
82 assert ab.p90([5.0]) == 5.0
83 assert ab.p90([]) is None
84 assert ab.median([1, None, 3]) == 2
85
86
87 def _verdict(**overrides):
88 base = dict(
89 arm_in_window=[10, 12, 8], a_in_window=[20, 20, 20],
90 arm_head_recall=[0.5, 0.4, None], arm_stale=[0, 0, 0],
91 arm_wall=[40.0, 50.0, 60.0], a_wall=[45.0, 50.0, 55.0],
92 )
93 base.update(overrides)
94 return ab.parity_verdict(**base)
95
96
97 def test_parity_pass():
98 verdict = _verdict()
99 assert verdict["pass"] is True
100 assert all(verdict["checks"].values())
101
102
103 def test_parity_fails_each_bar():
104 assert _verdict(arm_in_window=[9, 9, 9])["checks"]["in_window"] is False
105 assert _verdict(arm_head_recall=[0.3, 0.39])["checks"]["head_recall"] is False
106 assert _verdict(arm_head_recall=[None])["checks"]["head_recall"] is False
107 assert _verdict(arm_stale=[0, 1, 0])["checks"]["stale"] is False
108 assert _verdict(arm_wall=[86.0, 86.0, 86.0])["checks"]["wall"] is False # A p90 55 + 30 = 85
109 slow = _verdict(arm_wall=[180.0], a_wall=[170.0])
110 assert slow["checks"]["wall"] is False and slow["pass"] is False
111
112
113 def test_strip_sc_keys_drops_only_scrapecreators_lines():
114 text = "A=1\nSCRAPECREATORS_API_KEY=dummy\nexport SCRAPE_CREATORS_API_KEY=dummy\n# note\nSERPER_API_KEY=x\n"
115 assert ab.strip_sc_keys(text) == "A=1\n# note\nSERPER_API_KEY=x\n"
116
117
118 def test_slugify():
119 assert ab.slugify("Claude Code") == "claude-code"
120 assert ab.slugify(" Dubai chocolate!! ") == "dubai-chocolate"
121
122
123 def test_host_flags_reach_the_host_arms_only(tmp_path):
124 (tmp_path / "claude-code.host.json").write_text(
125 '{"tiktok_creators": ["@chase_ai_", "promptwarrior"], "tiktok_hashtags": ["#claudecode"]}')
126 flags = ab.host_flags(tmp_path, "Claude Code")
127 assert flags == ["--tiktok-creators=chase_ai_,promptwarrior", "--tiktok-hashtags=claudecode"]
128 assert ab.host_flags(tmp_path, "Labubu") == []
129 assert ab.host_flags(None, "Claude Code") == []
130 for arm in ("A", "C", "D"):
131 assert flags[0] in ab.arm_command("Claude Code", arm, None, flags)
132 for arm in ("B", "B-nofresh"):
133 assert flags[0] not in ab.arm_command("Claude Code", arm, None, flags)
134
135
136 def test_quotable_counts_items_whose_best_community_comment_clears_the_floor():
137 items = [
138 {"metadata": {"top_comments": [{"digg_count": 31}, {"digg_count": 7}]}},
139 {"metadata": {"top_comments": [{"digg_count": 4}]}},
140 {"metadata": {"top_comments": [{"digg_count": 90, "is_uploader": True}, {"digg_count": 2}]}},
141 {"top_comments": [{"likes": 5}]},
142 {},
143 ]
144 assert ab.quotable(items) == 2
145 assert ab.median_views([_tt("1", 10), _tt("2", 30), _tt("3")]) == 20
146
147
148 def test_keyless_arms_read_no_secret_store(tmp_path, monkeypatch):
149 monkeypatch.setenv("SCRAPECREATORS_API_KEY", "dummy-not-a-key")
150 monkeypatch.setenv("LAST30DAYS_KEYCHAIN_ALIASES", '{"SCRAPECREATORS_API_KEY": "other"}')
151 for arm in ("B", "C", "D"):
152 env = ab.arm_env(arm, str(tmp_path), skip_keychain=False)
153 assert "SCRAPECREATORS_API_KEY" not in env
154 assert env["LAST30DAYS_SKIP_KEYCHAIN"] == "1"
155 assert "LAST30DAYS_KEYCHAIN_ALIASES" not in env
156 assert env["PASSWORD_STORE_DIR"].startswith(str(tmp_path))
157 assert ab.arm_env("A", str(tmp_path), skip_keychain=False)["SCRAPECREATORS_API_KEY"] == "dummy-not-a-key"
158
158 lines PYTHON