返回 last30days-skill
test_linkedin.py
根目录 / tests / test_linkedin.py
1 import unittest
2 from unittest import mock
3
4 from lib.linkedin import (
5 _best_author_match,
6 _extract_posts,
7 _int_field,
8 _parse_date,
9 enrich_articles,
10 parse_linkedin_response,
11 parse_person_profile,
12 parse_profile_articles,
13 read_profile,
14 search_linkedin,
15 )
16
17
18 class TestParseLinkedinResponse(unittest.TestCase):
19 def _make_post(self, **overrides):
20 # Mirrors the live ScrapeCreators /v1/linkedin/search/posts post object:
21 # body in `description`, timestamp in `datePublished`, author as a nested
22 # dict, engagement in `likeCount`/`commentCount`, comments as a list.
23 base = {
24 "url": "https://www.linkedin.com/posts/example_123",
25 "datePublished": "2026-06-01T12:30:00.000Z",
26 "description": "Excited to share our latest product update.",
27 "author": {
28 "name": "Jane Doe",
29 "url": "https://www.linkedin.com/in/janedoe",
30 "followers": 1234,
31 },
32 "comments": [{"author": "Bob", "text": "nice", "linkedinUrl": "x"}],
33 "likeCount": 42,
34 "commentCount": 5,
35 }
36 base.update(overrides)
37 return base
38
39 def test_real_shape_post_parses_all_fields(self):
40 items = parse_linkedin_response({"posts": [self._make_post()]})
41 self.assertEqual(1, len(items))
42 item = items[0]
43 self.assertEqual("https://www.linkedin.com/posts/example_123", item["url"])
44 self.assertEqual("Excited to share our latest product update.", item["text"])
45 self.assertEqual("Jane Doe", item["author"])
46 self.assertEqual("https://www.linkedin.com/in/janedoe", item["author_url"])
47 self.assertEqual("2026-06-01", item["date"])
48 self.assertEqual(42, item["engagement"]["likes"])
49 self.assertEqual(5, item["engagement"]["comments"])
50 self.assertFalse(item["is_article"])
51
52 def test_description_and_datepublished_only_parses_nonempty(self):
53 # Regression guard for the exact bug that shipped: the live API uses
54 # `description` + `datePublished`, and a parser keyed on `text`/`date`
55 # dropped every post (10 raw -> 0 items). This must stay non-empty.
56 raw = {
57 "description": "body via description field",
58 "datePublished": "2026-06-10T09:00:00Z",
59 "url": "https://www.linkedin.com/posts/abc",
60 }
61 items = parse_linkedin_response({"posts": [raw]})
62 self.assertEqual(1, len(items))
63 self.assertEqual("body via description field", items[0]["text"])
64 self.assertEqual("2026-06-10", items[0]["date"])
65
66 def test_empty_posts_returns_empty_list(self):
67 self.assertEqual([], parse_linkedin_response({"posts": []}))
68 self.assertEqual([], parse_linkedin_response({}))
69
70 def test_post_without_text_is_skipped(self):
71 raw = self._make_post()
72 del raw["description"]
73 items = parse_linkedin_response({"posts": [raw]})
74 self.assertEqual([], items)
75
76 def test_non_dict_post_is_skipped(self):
77 items = parse_linkedin_response({"posts": ["not-a-dict", None]})
78 self.assertEqual([], items)
79
80 def test_author_as_dict(self):
81 raw = self._make_post(author={"name": "Jane Doe", "full_name": "Jane M Doe"})
82 items = parse_linkedin_response({"posts": [raw]})
83 self.assertEqual("Jane Doe", items[0]["author"])
84
85 def test_author_dict_falls_back_to_full_name(self):
86 raw = self._make_post(author={"full_name": "Jane M Doe"})
87 items = parse_linkedin_response({"posts": [raw]})
88 self.assertEqual("Jane M Doe", items[0]["author"])
89
90 def test_author_missing_defaults_to_empty_string(self):
91 raw = self._make_post()
92 del raw["author"]
93 items = parse_linkedin_response({"posts": [raw]})
94 self.assertEqual("", items[0]["author"])
95
96 def test_id_falls_back_to_generated_index(self):
97 # The live post object carries no top-level id/urn; the parser
98 # synthesizes a stable per-index id.
99 raw = self._make_post()
100 items = parse_linkedin_response({"posts": [raw]})
101 self.assertEqual("LI1", items[0]["id"])
102
103 def test_explicit_urn_used_as_id(self):
104 raw = self._make_post(urn="urn:li:activity:999")
105 items = parse_linkedin_response({"posts": [raw]})
106 self.assertEqual("urn:li:activity:999", items[0]["id"])
107
108 def test_alternate_field_names(self):
109 raw = {
110 "postId": "p1",
111 "content": "alternate field names",
112 "postUrl": "https://example.com/p1",
113 "authorName": "Alt Author",
114 "postedAt": "2026-05-15T10:00:00Z",
115 "likesCount": 10,
116 "commentsCount": 3,
117 "shares": 1,
118 }
119 items = parse_linkedin_response({"posts": [raw]})
120 item = items[0]
121 self.assertEqual("p1", item["id"])
122 self.assertEqual("alternate field names", item["text"])
123 self.assertEqual("https://example.com/p1", item["url"])
124 self.assertEqual("Alt Author", item["author"])
125 self.assertEqual("2026-05-15", item["date"])
126 self.assertEqual(10, item["engagement"]["likes"])
127 self.assertEqual(3, item["engagement"]["comments"])
128 self.assertEqual(1, item["engagement"]["reposts"])
129
130
131 class TestExtractPosts(unittest.TestCase):
132 def test_extracts_from_posts_key(self):
133 self.assertEqual([{"a": 1}], _extract_posts({"posts": [{"a": 1}]}))
134
135 def test_extracts_from_items_key(self):
136 self.assertEqual([{"a": 1}], _extract_posts({"items": [{"a": 1}]}))
137
138 def test_extracts_from_data_key(self):
139 self.assertEqual([{"a": 1}], _extract_posts({"data": [{"a": 1}]}))
140
141 def test_extracts_from_results_key(self):
142 self.assertEqual([{"a": 1}], _extract_posts({"results": [{"a": 1}]}))
143
144 def test_non_dict_response_returns_empty(self):
145 self.assertEqual([], _extract_posts(["not", "a", "dict"]))
146 self.assertEqual([], _extract_posts(None))
147
148 def test_no_matching_key_returns_empty(self):
149 self.assertEqual([], _extract_posts({"unexpected": [1, 2, 3]}))
150
151
152 class TestParseDate(unittest.TestCase):
153 def test_extracts_date_from_iso_string(self):
154 self.assertEqual("2026-06-01", _parse_date("2026-06-01T12:30:00Z"))
155
156 def test_plain_date_string(self):
157 self.assertEqual("2026-06-01", _parse_date("2026-06-01"))
158
159 def test_none_returns_none(self):
160 self.assertIsNone(_parse_date(None))
161
162 def test_empty_string_returns_none(self):
163 self.assertIsNone(_parse_date(""))
164
165 def test_no_date_pattern_returns_none(self):
166 self.assertIsNone(_parse_date("not a date"))
167
168
169 class TestIntField(unittest.TestCase):
170 def test_returns_first_present_key(self):
171 self.assertEqual(5, _int_field({"likes": 5, "likesCount": 10}, "likes", "likesCount"))
172
173 def test_falls_back_to_second_key(self):
174 self.assertEqual(10, _int_field({"likesCount": 10}, "likes", "likesCount"))
175
176 def test_missing_all_keys_returns_zero(self):
177 self.assertEqual(0, _int_field({}, "likes", "likesCount"))
178
179 def test_non_numeric_value_returns_zero(self):
180 self.assertEqual(0, _int_field({"likes": "not-a-number"}, "likes"))
181
182 def test_string_numeric_value_is_coerced(self):
183 self.assertEqual(7, _int_field({"likes": "7"}, "likes"))
184
185
186 class TestSearchLinkedin(unittest.TestCase):
187 def test_no_token_returns_empty_without_network_call(self):
188 with mock.patch("lib.linkedin.http.request") as mock_request:
189 result = search_linkedin("AI agents", "2026-05-27", "2026-06-26", token="")
190 self.assertEqual({"posts": []}, result)
191 mock_request.assert_not_called()
192
193 def test_successful_search_returns_capped_posts(self):
194 raw_posts = [{"text": f"post {i}"} for i in range(20)]
195 with mock.patch(
196 "lib.linkedin.http.request", return_value={"posts": raw_posts}
197 ):
198 result = search_linkedin(
199 "AI agents", "2026-05-27", "2026-06-26", depth="quick", token="fake-token"
200 )
201 # "quick" depth caps at 10 results per DEPTH_CONFIG
202 self.assertEqual(10, len(result["posts"]))
203
204 def test_http_error_returns_empty_with_error_message(self):
205 from lib import http as http_module
206
207 with mock.patch(
208 "lib.linkedin.http.request",
209 side_effect=http_module.HTTPError("rate limited", status_code=429),
210 ):
211 result = search_linkedin(
212 "AI agents", "2026-05-27", "2026-06-26", token="fake-token"
213 )
214 self.assertEqual([], result["posts"])
215 self.assertIn("error", result)
216
217
218 class TestDateRangeFiltering(unittest.TestCase):
219 def test_filters_out_posts_outside_range(self):
220 posts = [
221 {"text": "in range", "date": "2026-06-15"},
222 {"text": "too old", "date": "2026-01-01"},
223 ]
224 items = parse_linkedin_response(
225 {"posts": posts}, from_date="2026-05-27", to_date="2026-06-26"
226 )
227 self.assertEqual(1, len(items))
228 self.assertEqual("in range", items[0]["text"])
229
230 def test_keeps_all_when_none_in_range(self):
231 # Graceful fallback: SC doesn't always return a parseable date, so if
232 # the filter would drop everything, keep the unfiltered set instead
233 # of returning zero results.
234 posts = [
235 {"text": "old post", "date": "2026-01-01"},
236 {"text": "older post", "date": "2025-12-01"},
237 ]
238 items = parse_linkedin_response(
239 {"posts": posts}, from_date="2026-05-27", to_date="2026-06-26"
240 )
241 self.assertEqual(2, len(items))
242
243 def test_no_filtering_when_dates_not_provided(self):
244 posts = [{"text": "any date", "date": "2020-01-01"}]
245 items = parse_linkedin_response({"posts": posts})
246 self.assertEqual(1, len(items))
247
248 def test_posts_without_date_excluded_from_in_range_but_not_counted_as_failure(self):
249 posts = [
250 {"text": "has date in range", "date": "2026-06-15"},
251 {"text": "no date at all"},
252 ]
253 items = parse_linkedin_response(
254 {"posts": posts}, from_date="2026-05-27", to_date="2026-06-26"
255 )
256 # Only the dated, in-range post survives; the undated one isn't
257 # counted toward "in range" and gets dropped since in_range is non-empty.
258 self.assertEqual(1, len(items))
259 self.assertEqual("has date in range", items[0]["text"])
260
261
262 class TestArticleDetection(unittest.TestCase):
263 def test_pulse_url_tagged_as_article_and_boosted(self):
264 raw = {
265 "description": "long-form piece",
266 "datePublished": "2026-06-10",
267 "url": "https://www.linkedin.com/pulse/wtf-is-a-loop-matt-van-horn-abc",
268 }
269 item = parse_linkedin_response({"posts": [raw]})[0]
270 self.assertTrue(item["is_article"])
271 self.assertEqual(0.9, item["relevance"])
272
273 def test_posts_url_not_article_default_relevance(self):
274 raw = {
275 "description": "ordinary status update",
276 "datePublished": "2026-06-10",
277 "url": "https://www.linkedin.com/posts/example_123",
278 }
279 item = parse_linkedin_response({"posts": [raw]})[0]
280 self.assertFalse(item["is_article"])
281 self.assertEqual(0.5, item["relevance"])
282
283
284 class TestProfileArticles(unittest.TestCase):
285 def _profile(self, **overrides):
286 base = {
287 "name": "Matt Van Horn",
288 "articles": [
289 {
290 "headline": "WTF Is a Loop? Part 2",
291 "url": "https://www.linkedin.com/pulse/wtf-loop-part-2-abc",
292 "datePublished": "2026-06-20T21:06:18.000+00:00",
293 "articleBody": "",
294 },
295 {
296 "headline": "Every Agentic Engineering Hack I Know",
297 "url": "https://www.linkedin.com/pulse/every-hack-def",
298 "datePublished": "2026-06-04T02:31:36.000+00:00",
299 "articleBody": "",
300 },
301 ],
302 }
303 base.update(overrides)
304 return base
305
306 def test_articles_parse_as_high_signal(self):
307 items = parse_profile_articles(self._profile())
308 self.assertEqual(2, len(items))
309 for it in items:
310 self.assertTrue(it["is_article"])
311 self.assertEqual(0.9, it["relevance"])
312 self.assertEqual("Matt Van Horn", it["author"])
313 self.assertEqual("WTF Is a Loop? Part 2", items[0]["text"])
314
315 def test_articles_respect_date_range(self):
316 items = parse_profile_articles(
317 self._profile(), from_date="2026-06-15", to_date="2026-06-26"
318 )
319 self.assertEqual(1, len(items))
320 self.assertEqual("WTF Is a Loop? Part 2", items[0]["text"])
321
322 def test_empty_or_missing_articles(self):
323 self.assertEqual([], parse_profile_articles({"name": "X"}))
324 self.assertEqual([], parse_profile_articles({"name": "X", "articles": []}))
325
326 def test_article_without_headline_skipped(self):
327 prof = {"name": "X", "articles": [{"url": "u", "datePublished": "2026-06-10"}]}
328 self.assertEqual([], parse_profile_articles(prof))
329
330
331 class TestBestAuthorMatch(unittest.TestCase):
332 _MVH = "https://www.linkedin.com/in/mattvanhorn"
333 _DT = "https://www.linkedin.com/in/daisuketanaka"
334 _ERIC = "https://www.linkedin.com/in/ericosiu"
335
336 def test_exact_person_topic_matches(self):
337 items = [{"author": "Matt Van Horn", "author_url": self._MVH}]
338 self.assertEqual(self._MVH, _best_author_match(items, "Matt Van Horn"))
339
340 def test_name_contained_in_longer_topic(self):
341 items = [{"author": "Matt Van Horn", "author_url": self._MVH}]
342 self.assertEqual(
343 self._MVH, _best_author_match(items, "what is Matt Van Horn building")
344 )
345
346 def test_single_word_topic_never_enriches(self):
347 # "AI" is one token — a keyword topic, not a person.
348 items = [{"author": "Daisuke Tanaka", "author_url": self._DT}]
349 self.assertEqual("", _best_author_match(items, "AI"))
350
351 def test_no_substring_false_positive_across_token_boundaries(self):
352 # Regression for the Greptile finding: a topic token must not match
353 # inside an unrelated author's name. "ai" must not hit "daisuke".
354 items = [{"author": "Daisuke Tanaka", "author_url": self._DT}]
355 self.assertEqual("", _best_author_match(items, "AI agents"))
356
357 def test_picks_matching_author_not_first(self):
358 items = [
359 {"author": "Eric Siu", "author_url": self._ERIC},
360 {"author": "Matt Van Horn", "author_url": self._MVH},
361 ]
362 self.assertEqual(self._MVH, _best_author_match(items, "Matt Van Horn loops"))
363
364
365 class TestEnrichArticles(unittest.TestCase):
366 def _person_items(self):
367 # Parsed post items as enrich_articles receives them: a person-topic
368 # search returns posts authored by the subject.
369 return [
370 {"author": "Eric Siu", "author_url": "https://www.linkedin.com/in/ericosiu"},
371 {"author": "Matt Van Horn", "author_url": "https://www.linkedin.com/in/mattvanhorn"},
372 ]
373
374 def test_person_topic_enriches_via_one_profile_call(self):
375 profile = {
376 "name": "Matt Van Horn",
377 "articles": [
378 {"headline": "WTF Is a Loop?", "url": "https://www.linkedin.com/pulse/a", "datePublished": "2026-06-20"},
379 ],
380 }
381 with mock.patch(
382 "lib.linkedin.http.request", return_value=profile
383 ) as mock_request:
384 arts = enrich_articles(
385 self._person_items(), "Matt Van Horn", token="fake",
386 from_date="2026-05-27", to_date="2026-06-26",
387 )
388 self.assertEqual(1, len(arts))
389 self.assertTrue(arts[0]["is_article"])
390 self.assertEqual(0.9, arts[0]["relevance"])
391 # Bounded: exactly one profile call.
392 self.assertEqual(1, mock_request.call_count)
393 # And it fetched the matching author's profile, not the first author.
394 called_profile = mock_request.call_args.kwargs["params"]["url"]
395 self.assertIn("mattvanhorn", called_profile)
396
397 def test_keyword_topic_makes_no_profile_call(self):
398 with mock.patch("lib.linkedin.http.request") as mock_request:
399 arts = enrich_articles(
400 self._person_items(), "AI agents", token="fake",
401 from_date="2026-05-27", to_date="2026-06-26",
402 )
403 self.assertEqual([], arts)
404 mock_request.assert_not_called()
405
406 def test_no_token_no_call(self):
407 with mock.patch("lib.linkedin.http.request") as mock_request:
408 arts = enrich_articles(self._person_items(), "Matt Van Horn", token="")
409 self.assertEqual([], arts)
410 mock_request.assert_not_called()
411
412 def test_profile_error_returns_empty(self):
413 from lib import http as http_module
414
415 with mock.patch(
416 "lib.linkedin.http.request",
417 side_effect=http_module.HTTPError("boom", status_code=500),
418 ):
419 arts = enrich_articles(self._person_items(), "Matt Van Horn", token="fake")
420 self.assertEqual([], arts)
421
422 def test_no_author_url_no_call(self):
423 items = [{"author": "Matt Van Horn", "author_url": ""}]
424 with mock.patch("lib.linkedin.http.request") as mock_request:
425 arts = enrich_articles(items, "Matt Van Horn", token="fake")
426 self.assertEqual([], arts)
427 mock_request.assert_not_called()
428
429
430 class TestPersonProfile(unittest.TestCase):
431 """The ScrapeCreators profile read for a person run: posts and links only."""
432
433 PROFILE = {
434 "success": True,
435 "name": "Dana Okafor",
436 "location": "Columbus, Ohio",
437 "websites": [{"url": "https://danaokafor.example"}, "https://github.com/dokafor"],
438 "experience": [{"name": "Northwind Freight", "member": {"title": "*****"}}],
439 "recentPosts": [
440 {"title": "Dock wait times are down", "link": "https://www.linkedin.com/posts/a",
441 "datePublished": "2026-11-02T08:00:00Z", "activityType": "Shared by Dana Okafor"},
442 {"title": "A colleague's launch", "link": "https://www.linkedin.com/posts/b",
443 "activityType": "Reposted by Dana Okafor"},
444 {"title": "Someone else's post", "link": "https://www.linkedin.com/posts/c",
445 "activityType": "Liked by Dana Okafor"},
446 ],
447 }
448
449 def test_masked_titles_never_become_roles(self):
450 parsed = parse_person_profile(self.PROFILE)
451 self.assertEqual([], parsed["current_roles"])
452 self.assertEqual([], parsed["history"])
453 self.assertNotIn("*****", repr(parsed))
454
455 def test_keeps_own_posts_and_reshares_not_likes(self):
456 posts = parse_person_profile(self.PROFILE)["posts"]
457 self.assertEqual(["https://www.linkedin.com/posts/a", "https://www.linkedin.com/posts/b"],
458 [p["url"] for p in posts])
459 self.assertEqual("2026-11-02", posts[0]["date"])
460 self.assertEqual([False, True], [p["is_reshare"] for p in posts])
461
462 def test_links_come_from_listed_websites(self):
463 self.assertEqual(
464 ["https://danaokafor.example", "https://github.com/dokafor"],
465 parse_person_profile(self.PROFILE)["websites"],
466 )
467
468 def test_read_failure_is_a_status(self):
469 from lib import http as http_module
470
471 with mock.patch(
472 "lib.linkedin.http.request",
473 side_effect=http_module.HTTPError("boom", status_code=500),
474 ):
475 result = read_profile("https://www.linkedin.com/in/dana-okafor", "fake")
476 self.assertEqual("failed", result["status"])
477 self.assertIsNone(result["data"])
478
479
480 class TestLinkedinPlanner(unittest.TestCase):
481 def test_planner_capability(self):
482 from lib import planner
483
484 self.assertEqual(
485 {"discussion", "social"},
486 planner.SOURCE_CAPABILITIES.get("linkedin"),
487 )
488
489
490 if __name__ == "__main__":
491 unittest.main()
492
492 lines PYTHON