返回 last30days-skill
test_tiktok.py
根目录 / tests / test_tiktok.py
1 import threading
2 import unittest
3 from urllib.parse import parse_qs, urlsplit
4 from unittest.mock import MagicMock, patch
5
6 from lib import tiktok
7 from lib.tiktok import _parse_items
8
9
10 class TestTikTokAuthorTypeSafety(unittest.TestCase):
11 def _make_raw(self, **overrides):
12 base = {
13 "aweme_id": "1",
14 "desc": "test video",
15 "share_url": "https://www.tiktok.com/@u/video/1",
16 "author": {"unique_id": "testuser"},
17 "statistics": {"play_count": 100, "digg_count": 50, "comment_count": 10, "share_count": 5},
18 }
19 base.update(overrides)
20 return base
21
22 def test_author_as_dict(self):
23 items = _parse_items([self._make_raw()], "test")
24 self.assertEqual("testuser", items[0]["author_name"])
25
26 def test_author_as_string(self):
27 items = _parse_items([self._make_raw(author="stringuser")], "test")
28 self.assertEqual("stringuser", items[0]["author_name"])
29
30 def test_author_missing(self):
31 raw = self._make_raw()
32 del raw["author"]
33 items = _parse_items([raw], "test")
34 self.assertEqual("", items[0]["author_name"])
35
36 def test_author_none(self):
37 items = _parse_items([self._make_raw(author=None)], "test")
38 self.assertEqual("", items[0]["author_name"])
39
40
41 class TestTikTokStatsZeroPreserved(unittest.TestCase):
42 def test_zero_play_count(self):
43 raw = {
44 "aweme_id": "1",
45 "desc": "test",
46 "share_url": "https://www.tiktok.com/@u/video/1",
47 "author": {"unique_id": "u"},
48 "statistics": {"play_count": 0, "digg_count": 0, "comment_count": 0, "share_count": 0},
49 }
50 items = _parse_items([raw], "test")
51 self.assertEqual(0, items[0]["engagement"]["views"])
52 self.assertEqual(0, items[0]["engagement"]["likes"])
53 self.assertEqual(0, items[0]["engagement"]["comments"])
54 self.assertEqual(0, items[0]["engagement"]["shares"])
55
56 def test_stats_missing(self):
57 raw = {
58 "aweme_id": "1",
59 "desc": "test",
60 "share_url": "https://www.tiktok.com/@u/video/1",
61 "author": {"unique_id": "u"},
62 }
63 items = _parse_items([raw], "test")
64 self.assertIsNone(items[0]["engagement"]["views"])
65
66 def test_stats_as_non_dict(self):
67 raw = {
68 "aweme_id": "1",
69 "desc": "test",
70 "share_url": "https://www.tiktok.com/@u/video/1",
71 "author": {"unique_id": "u"},
72 "statistics": "invalid",
73 }
74 items = _parse_items([raw], "test")
75 self.assertIsNone(items[0]["engagement"]["views"])
76
77
78 class TestExpandTikTokQueries(unittest.TestCase):
79 """Tests for expand_tiktok_queries() multi-query generation."""
80
81 def test_default_depth_returns_two_plus_queries(self):
82 from lib.tiktok import expand_tiktok_queries
83 queries = expand_tiktok_queries("Kanye West", "default")
84 self.assertGreaterEqual(len(queries), 2)
85 # Breaking_news intent should include reaction/edit variant
86 variant_found = any(
87 "reaction" in q.lower() or "edit" in q.lower() or "trend" in q.lower()
88 for q in queries
89 )
90 self.assertTrue(variant_found, f"Expected reaction/edit/trend variant: {queries}")
91
92 def test_product_intent_includes_review_variant(self):
93 from lib.tiktok import expand_tiktok_queries
94 # "best laptop for coding" triggers the product intent (best .* for pattern)
95 queries = expand_tiktok_queries("best laptop for coding", "deep")
96 variant_found = any(
97 "review" in q.lower() or "haul" in q.lower() or "unboxing" in q.lower()
98 for q in queries
99 )
100 self.assertTrue(variant_found, f"Expected review/haul/unboxing variant: {queries}")
101
102 def test_quick_depth_returns_one_query(self):
103 from lib.tiktok import expand_tiktok_queries
104 queries = expand_tiktok_queries("Kanye West", "quick")
105 self.assertEqual(len(queries), 1)
106
107
108 class TestTikTokCommentsGate(unittest.TestCase):
109 def test_gate_requires_key_and_token(self):
110 from lib import env
111 self.assertFalse(env.is_tiktok_comments_available({}))
112 self.assertFalse(env.is_tiktok_comments_available(
113 {"SCRAPECREATORS_API_KEY": "k"}
114 ))
115 self.assertFalse(env.is_tiktok_comments_available(
116 {"INCLUDE_SOURCES": "tiktok_comments"}
117 ))
118 self.assertTrue(env.is_tiktok_comments_available(
119 {"SCRAPECREATORS_API_KEY": "k", "INCLUDE_SOURCES": "tiktok,tiktok_comments"}
120 ))
121
122 def test_gate_case_matches_youtube_pattern(self):
123 from lib import env
124 # Matches the existing youtube_comments behaviour — plain substring match via _parse_include_sources.
125 self.assertTrue(env.is_tiktok_comments_available(
126 {"SCRAPECREATORS_API_KEY": "k", "INCLUDE_SOURCES": "TIKTOK,TIKTOK_COMMENTS"}
127 ))
128
129
130 class TestTikTokEnrichWithComments(unittest.TestCase):
131 def test_empty_items_returns_empty(self):
132 from lib import tiktok
133 self.assertEqual([], tiktok.enrich_with_comments([], token="k"))
134
135 def test_missing_token_is_noop(self):
136 from lib import tiktok
137 items = [{"video_id": "1", "url": "https://www.tiktok.com/@u/video/1", "engagement": {"views": 100}}]
138 result = tiktok.enrich_with_comments(items, token="")
139 self.assertNotIn("top_comments", result[0])
140
141 def test_fetch_post_comments_parses_sc_response(self):
142 from unittest.mock import patch
143 from lib import tiktok
144
145 fake_sc_response = {
146 "comments": [
147 {"text": "meh", "user": {"nickname": "Bob"},
148 "digg_count": 3, "create_time": 1709251300},
149 {"text": "loved it", "user": {"nickname": "Alice"},
150 "digg_count": 420, "create_time": 1709251200},
151 {"text": "useful", "user": {"nickname": "Carol"},
152 "digg_count": 80, "create_time": 1709251300},
153 {"text": "", "user": {"nickname": "Skip"},
154 "digg_count": 999, "create_time": 1709251400},
155 ],
156 "total": 4,
157 }
158
159 with patch.object(tiktok.http, "get", return_value=fake_sc_response):
160 out = tiktok._fetch_post_comments(
161 "https://www.tiktok.com/@u/video/1",
162 token="k",
163 max_comments=5,
164 )
165 # Empty-text comment dropped; rest sorted desc by digg_count.
166 self.assertEqual([c["text"] for c in out], ["loved it", "useful", "meh"])
167 self.assertEqual("loved it", out[0]["text"])
168 self.assertEqual(420, out[0]["digg_count"])
169 self.assertEqual("Alice", out[0]["author"])
170 self.assertEqual("2024-03-01", out[0]["date"])
171 self.assertEqual([c["digg_count"] for c in out], [420, 80, 3])
172 capped_response = {"comments": fake_sc_response["comments"][:3]}
173 with patch.object(tiktok.http, "get", return_value=capped_response):
174 capped = tiktok._fetch_post_comments(
175 "https://www.tiktok.com/@u/video/1", token="k", max_comments=1,
176 )
177 self.assertEqual([c["text"] for c in capped], ["loved it"])
178
179 def test_fetch_post_comments_prefers_unique_id_over_nickname(self):
180 """Author prefers unique_id (@handle) over nickname (display name)."""
181 from unittest.mock import patch
182 from lib import tiktok
183
184 fake_sc_response = {
185 "comments": [
186 {"text": "first", "user": {"unique_id": "moosanoormahomed", "nickname": "Moosa Noormahomed"},
187 "digg_count": 3986, "create_time": 1709251200},
188 {"text": "second", "user": {"nickname": "Muna9e"}, # no unique_id, falls back to nickname
189 "digg_count": 925, "create_time": 1709251300},
190 {"text": "third", "user": {}, # neither - empty string
191 "digg_count": 100, "create_time": 1709251400},
192 ],
193 "total": 3,
194 }
195
196 with patch.object(tiktok.http, "get", return_value=fake_sc_response):
197 out = tiktok._fetch_post_comments(
198 "https://www.tiktok.com/@u/video/1",
199 token="k",
200 max_comments=5,
201 )
202 self.assertEqual(3, len(out))
203 # unique_id wins over nickname when both present
204 self.assertEqual("moosanoormahomed", out[0]["author"])
205 # nickname used when unique_id missing
206 self.assertEqual("Muna9e", out[1]["author"])
207 # both missing → empty string, comment still included
208 self.assertEqual("", out[2]["author"])
209
210 def test_fetch_post_comments_swallows_http_error(self):
211 from unittest.mock import patch
212 from lib import tiktok
213
214 with patch.object(tiktok.http, "get", side_effect=Exception("429 rate limit")):
215 out = tiktok._fetch_post_comments(
216 "https://www.tiktok.com/@u/video/1",
217 token="k",
218 max_comments=5,
219 )
220 self.assertEqual([], out)
221
222 def test_enrich_attaches_top_comments_to_top_ranked_items(self):
223 from unittest.mock import patch
224 from lib import tiktok
225
226 items = [
227 {"video_id": "low", "url": "https://www.tiktok.com/@u/video/low",
228 "engagement": {"views": 10, "likes": 1, "comments": 0}},
229 {"video_id": "high", "url": "https://www.tiktok.com/@u/video/high",
230 "engagement": {"views": 10000, "likes": 500, "comments": 30}},
231 {"video_id": "mid", "url": "https://www.tiktok.com/@u/video/mid",
232 "engagement": {"views": 1000, "likes": 50, "comments": 5}},
233 ]
234 with patch.object(tiktok, "_fetch_post_comments") as mock_fetch:
235 mock_fetch.return_value = [
236 {"author": "A", "text": "fire", "digg_count": 100, "date": "2024-03-01"}
237 ]
238 tiktok.enrich_with_comments(items, token="k", max_posts=2)
239 # High and mid get comments; low does not.
240 by_id = {i["video_id"]: i for i in items}
241 self.assertIn("top_comments", by_id["high"])
242 self.assertIn("top_comments", by_id["mid"])
243 self.assertNotIn("top_comments", by_id["low"])
244
245 class TestTikTokPublicComments(unittest.TestCase):
246 """Keyless top comments from TikTok's public web endpoint."""
247
248 PAYLOAD = {"comments": [
249 {"text": "second", "user": {"unique_id": "b"}, "digg_count": 8, "create_time": 1795252597},
250 {"text": "first", "user": {"unique_id": "a"}, "digg_count": 11, "create_time": 1795252597},
251 {"text": "mine", "user": {"unique_id": "Dev"}, "digg_count": 2, "create_time": 1795252597},
252 ], "total": 3}
253
254 def test_request_shape_carries_the_post_id_and_no_key(self):
255 from unittest.mock import patch
256 from lib import tiktok
257
258 with patch.object(tiktok.http, "get", return_value=self.PAYLOAD) as get:
259 out = tiktok._fetch_public_comments(
260 "https://www.tiktok.com/@dev/video/7710485679641267469?lang=en", creator="dev",
261 )
262 url = get.call_args[0][0]
263 kwargs = get.call_args[1]
264 self.assertEqual("https://www.tiktok.com/api/comment/list/", url)
265 self.assertEqual("7710485679641267469", kwargs["params"]["aweme_id"])
266 self.assertNotIn("x-api-key", {k.lower() for k in kwargs["headers"]})
267 self.assertEqual(["first", "second", "mine"], [c["text"] for c in out])
268 self.assertEqual("a", out[0]["author"])
269 self.assertEqual([False, False, True], [c["is_uploader"] for c in out])
270
271 def test_url_without_a_post_id_makes_no_request(self):
272 from unittest.mock import patch
273 from lib import tiktok
274
275 with patch.object(tiktok.http, "get") as get:
276 self.assertEqual([], tiktok._fetch_public_comments("https://www.tiktok.com/@dev"))
277 get.assert_not_called()
278
279 def test_provider_errors_and_odd_payloads_yield_nothing(self):
280 from unittest.mock import patch
281 from lib import tiktok
282
283 url = "https://www.tiktok.com/@dev/video/7710485679641267469"
284 with patch.object(tiktok.http, "get", side_effect=Exception("403")):
285 self.assertEqual([], tiktok._fetch_public_comments(url))
286 for payload in ({}, {"comments": None}, {"status_code": 10201}, {"comments": ["x", None]}):
287 with patch.object(tiktok.http, "get", return_value=payload):
288 self.assertEqual([], tiktok._fetch_public_comments(url))
289
290 def test_public_failures_stay_out_of_the_run_record(self):
291 from unittest.mock import patch
292 from lib import http, tiktok
293
294 def blocked(*_a, **_k):
295 http._raise(http.HTTPError("HTTP 403", status_code=403))
296
297 with http.capture_failures() as run_failures, \
298 patch.object(tiktok.http, "get", side_effect=blocked):
299 out = tiktok._fetch_public_comments(
300 "https://www.tiktok.com/@dev/video/7710485679641267469")
301 self.assertEqual([], out)
302 self.assertEqual([], run_failures)
303
304 def test_public_enrich_uses_the_public_endpoint_without_a_token(self):
305 from unittest.mock import patch
306 from lib import tiktok
307
308 items = [{"video_id": "1", "url": "https://www.tiktok.com/@u/video/7710485679641267469",
309 "author_name": "u", "engagement": {"views": 100}}]
310 with patch.object(tiktok, "_fetch_post_comments") as paid, \
311 patch.object(tiktok, "_fetch_public_comments",
312 return_value=[{"author": "a", "text": "hi", "digg_count": 9, "date": ""}]) as free:
313 tiktok.enrich_with_comments(items, token="", public=True)
314 paid.assert_not_called()
315 free.assert_called_once()
316 self.assertEqual("hi", items[0]["top_comments"][0]["text"])
317
318
319 class TestTikTokArabicTopicEncoding(unittest.TestCase):
320 """Regression for issue #817 across the TikTok search path."""
321
322 def _sent_url(self, mock_urlopen) -> str:
323 return mock_urlopen.call_args[0][0].full_url
324
325 @patch("lib.http.urllib.request.urlopen")
326 def test_arabic_topic_returns_success_with_ascii_encoded_url(self, mock_urlopen):
327 from lib.tiktok import search_tiktok
328 resp = MagicMock()
329 resp.__enter__ = MagicMock(return_value=resp)
330 resp.__exit__ = MagicMock(return_value=False)
331 resp.read.return_value = b'{"search_item_list": []}'
332 resp.status = 200
333 mock_urlopen.return_value = resp
334
335 topic = "اسعار التمريض المنزلي السعودية"
336 result = search_tiktok(
337 topic,
338 "2026-06-01",
339 "2026-07-13",
340 depth="quick",
341 token="dummy-key",
342 )
343 self.assertNotIn("error", result)
344 sent_url = self._sent_url(mock_urlopen)
345 sent_url.encode("ascii")
346 self.assertEqual(parse_qs(urlsplit(sent_url).query)["query"], [topic])
347
348
349 class TestTikTokBudget(unittest.TestCase):
350 def test_expired_or_cancelled_search_starts_no_requests(self):
351 cancel = threading.Event()
352 cancel.set()
353 for budget in ({"deadline": 99.0}, {"cancel": cancel}):
354 with self.subTest(budget=budget), \
355 patch("lib.tiktok.time.monotonic", return_value=100.0), \
356 patch.object(tiktok.http, "get") as get:
357 result = tiktok.search_and_enrich(
358 "travel", "2026-10-01", "2026-10-21", token="dummy-key",
359 hashtags=["travel"], creators=["traveler"], **budget,
360 )
361 self.assertEqual(result, {"items": [], "error": tiktok.BUDGET_ERROR})
362 get.assert_not_called()
363
364 def test_cancellation_keeps_video_and_skips_remaining_requests(self):
365 cancel = threading.Event()
366
367 def first_response(*args, **kwargs):
368 cancel.set()
369 return {"aweme_list": [{
370 "aweme_id": "1", "desc": "travel storytelling",
371 "author": {"unique_id": "traveler"},
372 }]}
373
374 with patch.object(tiktok.http, "get", side_effect=first_response) as get:
375 result = tiktok.search_and_enrich(
376 "travel", "2026-10-01", "2026-10-21", token="dummy-key",
377 hashtags=["travel", "unused"], creators=["traveler"], cancel=cancel,
378 )
379 self.assertEqual([item["video_id"] for item in result["items"]], ["1"])
380 self.assertEqual(result["error"], tiktok.BUDGET_ERROR)
381 get.assert_called_once()
382 self.assertIs(get.call_args.kwargs["cancel"], cancel)
383
384 def test_transcript_timeout_keeps_earlier_captions_and_videos(self):
385 raw = [{"aweme_id": str(i), "desc": f"travel video {i}",
386 "author": {"unique_id": "traveler"}} for i in range(3)]
387 with patch("lib.tiktok.time.monotonic", return_value=100.0), \
388 patch.object(tiktok.http, "get", side_effect=[
389 {"search_item_list": [{"aweme_info": item} for item in raw]},
390 {"transcript": "first spoken caption"},
391 tiktok.http.DeadlineExceeded(),
392 ]) as get:
393 result = tiktok.search_and_enrich(
394 "travel", "2026-10-01", "2026-10-21", depth="quick",
395 token="dummy-key", deadline=110.0,
396 )
397 self.assertEqual(len(result["items"]), 3)
398 self.assertEqual(result["error"], tiktok.BUDGET_ERROR)
399 self.assertEqual([item["caption_snippet"] for item in result["items"]], [
400 "first spoken caption", "travel video 1", "travel video 2",
401 ])
402 self.assertEqual(get.call_count, 3)
403 self.assertTrue(all(call.kwargs["deadline_monotonic"] == 110.0
404 for call in get.call_args_list))
405
406 def test_later_keyword_timeout_keeps_deduplicated_results(self):
407 raw = [{"aweme_id": str(i), "desc": f"travel video {i}",
408 "author": {"unique_id": "traveler"},
409 "statistics": {"play_count": i * 100}} for i in range(2)]
410 with patch("lib.tiktok.time.monotonic", return_value=100.0), \
411 patch.object(tiktok, "expand_tiktok_queries", return_value=["one", "two", "unused"]), \
412 patch.object(tiktok.http, "get", side_effect=[
413 {"search_item_list": [{"aweme_info": item} for item in raw + raw]},
414 tiktok.http.DeadlineExceeded(),
415 ]) as get:
416 result = tiktok.search_and_enrich(
417 "travel", "2026-10-01", "2026-10-21", token="dummy-key", deadline=110.0,
418 )
419 self.assertEqual([item["video_id"] for item in result["items"]], ["1", "0"])
420 self.assertEqual(result["error"], tiktok.BUDGET_ERROR)
421 self.assertEqual(get.call_count, 2)
422
423 def test_comment_enrichment_skips_expired_or_cancelled_budget(self):
424 cancel = threading.Event()
425 cancel.set()
426 items = [{"video_id": "1", "url": "https://www.tiktok.com/@u/video/1"}]
427 for budget in ({"deadline": 99.0}, {"cancel": cancel}):
428 with self.subTest(budget=budget), \
429 patch("lib.tiktok.time.monotonic", return_value=100.0), \
430 patch.object(tiktok.http, "get") as get, \
431 self.assertRaises(tiktok.http.DeadlineExceeded):
432 tiktok.enrich_with_comments(items, token="dummy-key", **budget)
433 get.assert_not_called()
434 self.assertNotIn("top_comments", items[0])
435
436
437 if __name__ == "__main__":
438 unittest.main()
439
439 lines PYTHON