返回 last30days-skill
test_person_linkedin.py
根目录 / tests / test_person_linkedin.py
1 """LinkedIn resolution for a person run: find the profile, read it, verify it.
2
3 HTTP is faked at ``lib.http.request``; assertions read what crosses that
4 boundary (URLs and payloads) and what lands in the person context.
5 """
6
7 from __future__ import annotations
8
9 import time
10 from datetime import date
11
12 import pytest
13
14 from lib import http, person, person_linkedin
15
16 NAME = "Dana Okafor"
17 EMPLOYER = "Northwind Freight:northwind.example"
18 GIVEN_URL = "https://www.linkedin.com/in/dana-okafor"
19 EXA_URL = "https://www.linkedin.com/in/dana-okafor-nwf"
20 LOOKUP_URL = "https://www.linkedin.com/in/dokafor-7"
21 DEEPLINE = "https://code.deepline.com/api/v2/integrations"
22 EXA = "https://api.exa.ai/search"
23 SC_PROFILE = "https://api.scrapecreators.com/v1/linkedin/profile"
24
25 DEEPLINE_KEY = {"DEEPLINE_API_KEY": "dl-test-key"}
26 EXA_KEY = {"EXA_API_KEY": "exa-test-key"}
27 SC_KEY = {"SCRAPECREATORS_API_KEY": "sc-test-key"}
28
29
30 def _profile(url: str, company: str, *, website: str | None = None, title: str = "VP Operations") -> dict:
31 position = {
32 "position": title,
33 "companyName": company,
34 "companyLinkedinUrl": f"https://www.linkedin.com/company/{company.lower().replace(' ', '-')}/",
35 "startDate": {"text": "Mar 2024"},
36 "endDate": {"text": "Present"},
37 }
38 if website:
39 position["companyWebsite"] = website
40 return {
41 "status": "completed",
42 "result": {"data": {"element": {
43 "firstName": "Dana",
44 "lastName": "Okafor",
45 "headline": f"{title} at {company}",
46 "linkedinUrl": url,
47 "location": {"linkedinText": "Columbus, Ohio, United States"},
48 "currentPosition": [position],
49 "experience": [
50 dict(position),
51 {"position": "Dispatcher", "companyName": "Contoso Logistics",
52 "startDate": {"text": "2019"}, "endDate": {"text": "2024"}},
53 ],
54 "websites": ["https://x.com/danaokafor"],
55 }}},
56 }
57
58
59 def _lookup(url: str | None) -> dict:
60 return {"status": "completed", "result": {"data": {"linkedin_url": url}}}
61
62
63 class FakeHTTP:
64 """Routes ``http.request`` by URL and records every call."""
65
66 def __init__(self, *, profiles=None, lookup=None, exa=None, sc_profile=None, fail=()):
67 self.profiles = profiles or {}
68 self.lookup = lookup
69 self.exa = exa or []
70 self.sc_profile = sc_profile
71 self.fail = set(fail)
72 self.calls: list[dict] = []
73
74 def __call__(self, method, url, headers=None, json_data=None, params=None, **kwargs):
75 self.calls.append({"method": method, "url": url, "json": json_data, "params": params, "kwargs": kwargs})
76 for prefix in self.fail:
77 if url.startswith(prefix):
78 raise http.HTTPError("HTTP 500", status_code=500)
79 if url == f"{DEEPLINE}/harvestapi_get_profile/execute":
80 target = json_data["payload"]["url"]
81 if target not in self.profiles:
82 raise http.HTTPError("HTTP 404", status_code=404)
83 return self.profiles[target]
84 if url == f"{DEEPLINE}/limadata_find_person_profiles/execute":
85 return _lookup(self.lookup)
86 if url == EXA:
87 return {"results": self.exa}
88 if url == SC_PROFILE:
89 return self.sc_profile or {}
90 raise AssertionError(f"unexpected request to {url}")
91
92 def to(self, url: str) -> list[dict]:
93 return [call for call in self.calls if call["url"] == url]
94
95 @property
96 def profile_reads(self) -> list[str]:
97 return [c["json"]["payload"]["url"] for c in self.to(f"{DEEPLINE}/harvestapi_get_profile/execute")]
98
99 @property
100 def lookups(self) -> list[dict]:
101 return [c["json"]["payload"] for c in self.to(f"{DEEPLINE}/limadata_find_person_profiles/execute")]
102
103
104 @pytest.fixture
105 def fake(monkeypatch):
106 def install(**kwargs) -> FakeHTTP:
107 fake_http = FakeHTTP(**kwargs)
108 monkeypatch.setattr(http, "request", fake_http)
109 return fake_http
110 return install
111
112
113 def _resolve(ctx, config, **kwargs):
114 return person_linkedin.resolve_linkedin(
115 ctx, config, deadline_monotonic=time.monotonic() + 60, run_id="run-1", **kwargs,
116 )
117
118
119 def _ctx(**flags) -> person.PersonContext:
120 return person.build_person_context(NAME, **flags)
121
122
123 class TestLookedUpCandidates:
124 def test_lookup_candidate_at_another_company_is_rejected(self, fake):
125 http_fake = fake(
126 lookup=LOOKUP_URL,
127 profiles={LOOKUP_URL: _profile(LOOKUP_URL, "Fabrikam Kitchens")},
128 )
129 ctx = _ctx(employer=EMPLOYER)
130 _resolve(ctx, DEEPLINE_KEY)
131 assert http_fake.lookups == [{
132 "full_name": NAME, "company_name": "Northwind Freight", "company_domain": "northwind.example",
133 }]
134 assert ctx.linkedin_status == "match rejected"
135 assert ctx.profile == {}
136 assert ctx.linkedin_url == ""
137 assert LOOKUP_URL not in ctx.anchors
138 assert "Fabrikam Kitchens" not in ctx.anchors
139
140 def test_exa_candidate_that_verifies_skips_the_lookup(self, fake):
141 http_fake = fake(
142 exa=[{"url": EXA_URL, "title": "Dana Okafor - VP Operations - Northwind Freight",
143 "highlights": ["Dana Okafor works at Northwind Freight"]}],
144 profiles={EXA_URL: _profile(EXA_URL, "Northwind Freight")},
145 )
146 ctx = _ctx(employer=EMPLOYER)
147 _resolve(ctx, {**DEEPLINE_KEY, **EXA_KEY})
148 assert http_fake.lookups == []
149 assert http_fake.profile_reads == [EXA_URL]
150 assert ctx.linkedin_status == "checked"
151 assert ctx.linkedin_url == EXA_URL
152 assert EXA_URL in ctx.anchors
153 assert ctx.profile["current_roles"][0]["company"] == "Northwind Freight"
154 assert ctx.profile["headline"] == "VP Operations at Northwind Freight"
155 assert any("Northwind Freight" in basis for basis in ctx.match_basis)
156 assert any("self-reported" in basis for basis in ctx.match_basis)
157
158 def test_exa_pre_search_is_bounded_by_the_resolve_deadline(self, fake):
159 http_fake = fake(lookup=LOOKUP_URL, profiles={LOOKUP_URL: _profile(LOOKUP_URL, "Northwind Freight")})
160 deadline = time.monotonic() + 60
161 person_linkedin.resolve_linkedin(
162 _ctx(employer=EMPLOYER), {**DEEPLINE_KEY, **EXA_KEY}, deadline_monotonic=deadline, run_id="run-1",
163 )
164 (exa_call,) = http_fake.to(EXA)
165 assert exa_call["kwargs"]["retries"] == 1
166 assert exa_call["kwargs"]["deadline_monotonic"] <= deadline
167
168 def test_exa_pre_search_is_skipped_when_the_deadline_leaves_room_only_for_the_paid_read(self, fake):
169 http_fake = fake(lookup=LOOKUP_URL, profiles={LOOKUP_URL: _profile(LOOKUP_URL, "Northwind Freight")})
170 ctx = _ctx(employer=EMPLOYER)
171 person_linkedin.resolve_linkedin(
172 ctx, {**DEEPLINE_KEY, **EXA_KEY}, deadline_monotonic=time.monotonic() + 20, run_id="run-1",
173 )
174 assert http_fake.to(EXA) == []
175 assert len(http_fake.lookups) == 1
176 assert ctx.linkedin_status == "checked"
177
178 def test_exa_result_without_employer_text_is_never_read(self, fake):
179 http_fake = fake(
180 exa=[{"url": EXA_URL, "title": "Dana Okafor - Chef", "highlights": ["Private dining"]},
181 {"url": "https://danaokafor.example/northwind-freight", "title": "Northwind Freight"}],
182 lookup=None,
183 )
184 ctx = _ctx(employer=EMPLOYER)
185 _resolve(ctx, {**DEEPLINE_KEY, **EXA_KEY})
186 assert http_fake.profile_reads == []
187 assert len(http_fake.lookups) == 1
188 assert ctx.linkedin_status == "profile not found"
189
190 def test_rejected_exa_candidate_is_followed_by_the_lookup(self, fake):
191 http_fake = fake(
192 exa=[{"url": EXA_URL, "title": "Dana Okafor", "highlights": ["formerly Northwind Freight"]}],
193 lookup=LOOKUP_URL,
194 profiles={
195 EXA_URL: _profile(EXA_URL, "Fabrikam Kitchens"),
196 LOOKUP_URL: _profile(LOOKUP_URL, "Northwind Freight Inc."),
197 },
198 )
199 ctx = _ctx(employer=EMPLOYER)
200 _resolve(ctx, {**DEEPLINE_KEY, **EXA_KEY})
201 assert http_fake.profile_reads == [EXA_URL, LOOKUP_URL]
202 assert ctx.linkedin_status == "checked"
203 assert ctx.linkedin_url == LOOKUP_URL
204 assert EXA_URL not in ctx.anchors
205 assert ctx.profile["current_roles"][0]["company"] == "Northwind Freight Inc."
206
207 def test_employer_domain_matches_through_company_website(self, fake):
208 fake(
209 lookup=LOOKUP_URL,
210 profiles={LOOKUP_URL: _profile(LOOKUP_URL, "NWF Group", website="https://www.northwind.example/")},
211 )
212 ctx = _ctx(employer=EMPLOYER)
213 _resolve(ctx, DEEPLINE_KEY)
214 assert ctx.linkedin_status == "checked"
215 assert any("northwind.example" in basis for basis in ctx.match_basis)
216
217 def test_exa_request_never_carries_the_email(self, fake):
218 http_fake = fake(exa=[], lookup=None)
219 ctx = _ctx(employer="Northwind Freight", email="dana.okafor@northwind.example")
220 _resolve(ctx, {**DEEPLINE_KEY, **EXA_KEY})
221 [exa_call] = http_fake.to(EXA)
222 sent = repr(exa_call)
223 assert "Dana Okafor" in sent and "Northwind Freight" in sent
224 for part in ("dana.okafor", "@", "northwind.example"):
225 assert part not in sent
226
227 def test_gmail_only_run_looks_up_by_email_and_anchors_the_result(self, fake):
228 http_fake = fake(
229 lookup=LOOKUP_URL,
230 profiles={LOOKUP_URL: _profile(LOOKUP_URL, "Fabrikam Kitchens")},
231 )
232 ctx = _ctx(email="dana.okafor@gmail.com")
233 assert ctx.identity_weak
234 _resolve(ctx, {**DEEPLINE_KEY, **EXA_KEY})
235 assert http_fake.to(EXA) == []
236 assert http_fake.lookups == [{"full_name": NAME, "email": "dana.okafor@gmail.com"}]
237 assert ctx.linkedin_status == "checked"
238 assert ctx.linkedin_url == LOOKUP_URL
239 assert LOOKUP_URL in ctx.anchors
240 assert any("email" in basis for basis in ctx.match_basis)
241 assert not ctx.identity_weak
242 assert "gmail.com" not in ctx.anchors
243
244 def test_lookup_failure_reports_failed(self, fake):
245 fake(fail=[f"{DEEPLINE}/limadata"])
246 ctx = _ctx(employer=EMPLOYER)
247 _resolve(ctx, DEEPLINE_KEY)
248 assert ctx.linkedin_status == "failed"
249 assert ctx.profile == {}
250
251
252 class TestPastPositions:
253 @staticmethod
254 def _former(end_text: str) -> dict:
255 profile = _profile(LOOKUP_URL, "Fabrikam Kitchens")
256 element = profile["result"]["data"]["element"]
257 element["experience"].insert(1, {
258 "position": "Analyst", "companyName": "Northwind Freight",
259 "startDate": {"text": "2001"}, "endDate": {"text": end_text},
260 })
261 return profile
262
263 def test_a_job_at_the_employer_that_ended_long_ago_does_not_confirm(self, fake):
264 fake(lookup=LOOKUP_URL, profiles={LOOKUP_URL: self._former("2004")})
265 ctx = _ctx(employer=EMPLOYER)
266 _resolve(ctx, DEEPLINE_KEY)
267 assert ctx.linkedin_status == "match rejected"
268 assert LOOKUP_URL not in ctx.anchors
269
270 def test_a_job_at_the_employer_that_just_ended_confirms(self, fake):
271 fake(lookup=LOOKUP_URL, profiles={LOOKUP_URL: self._former(str(date.today().year))})
272 ctx = _ctx(employer=EMPLOYER)
273 _resolve(ctx, DEEPLINE_KEY)
274 assert ctx.linkedin_status == "checked"
275 assert any("recent position" in basis for basis in ctx.match_basis)
276
277
278 class TestSuppliedUrl:
279 def test_supplied_url_is_the_anchor_and_its_employer_joins(self, fake):
280 http_fake = fake(profiles={GIVEN_URL: _profile(GIVEN_URL, "Northwind Freight")})
281 ctx = _ctx(linkedin=GIVEN_URL)
282 _resolve(ctx, DEEPLINE_KEY)
283 assert http_fake.lookups == []
284 assert http_fake.profile_reads == [GIVEN_URL]
285 assert ctx.linkedin_status == "checked"
286 assert GIVEN_URL in ctx.anchors
287 assert "Northwind Freight" in ctx.anchors
288 assert "LinkedIn URL supplied by user" in ctx.match_basis
289 assert ctx.linkedin_mismatch == ""
290
291 def test_supplied_url_at_another_employer_stays_anchored_with_a_mismatch(self, fake):
292 fake(profiles={GIVEN_URL: _profile(GIVEN_URL, "Contoso Logistics")})
293 ctx = _ctx(employer=EMPLOYER, linkedin=GIVEN_URL)
294 _resolve(ctx, DEEPLINE_KEY)
295 assert ctx.linkedin_status == "checked"
296 assert ctx.linkedin_url == GIVEN_URL
297 assert GIVEN_URL in ctx.anchors
298 assert "Contoso Logistics" in ctx.anchors
299 assert "Contoso Logistics" in ctx.linkedin_mismatch
300 assert "Northwind Freight" in ctx.linkedin_mismatch
301
302 def test_supplied_url_read_failure_keeps_the_anchor(self, fake):
303 fake(fail=[f"{DEEPLINE}/harvestapi"])
304 ctx = _ctx(linkedin=GIVEN_URL)
305 _resolve(ctx, DEEPLINE_KEY)
306 assert ctx.linkedin_status == "failed"
307 assert GIVEN_URL in ctx.anchors
308 assert ctx.profile == {}
309
310
311 class TestNoDeeplineKey:
312 def test_no_key_and_no_url_makes_no_call(self, fake):
313 http_fake = fake()
314 ctx = _ctx(employer=EMPLOYER)
315 _resolve(ctx, {**EXA_KEY, **SC_KEY, "INCLUDE_SOURCES": "linkedin"})
316 assert http_fake.calls == []
317 assert ctx.linkedin_status == "no key"
318
319 def test_scrapecreators_needs_linkedin_opt_in(self, fake):
320 http_fake = fake()
321 ctx = _ctx(employer=EMPLOYER)
322 _resolve(ctx, SC_KEY)
323 assert http_fake.calls == []
324 assert ctx.linkedin_status == "no key"
325
326 def test_scrapecreators_reads_a_supplied_url_without_presenting_roles(self, fake):
327 http_fake = fake(sc_profile={
328 "success": True,
329 "name": "Dana Okafor",
330 "location": "Columbus, Ohio",
331 "about": "Freight operations.",
332 "website": "https://danaokafor.example",
333 "experience": [{"name": "Northwind Freight", "member": {"title": "*****"}}],
334 "recentPosts": [{
335 "title": "We cut dock wait times by 30%",
336 "link": "https://www.linkedin.com/posts/dana-okafor_activity-1",
337 "datePublished": "2026-11-02",
338 "activityType": "Shared by Dana Okafor",
339 }],
340 })
341 ctx = _ctx(linkedin=GIVEN_URL)
342 _resolve(ctx, SC_KEY)
343 [call] = http_fake.to(SC_PROFILE)
344 assert call["params"] == {"url": GIVEN_URL}
345 assert ctx.linkedin_status == "checked"
346 assert ctx.profile["current_roles"] == []
347 assert ctx.profile["history"] == []
348 assert "*****" not in repr(ctx.to_dict())
349 assert "Northwind Freight" not in ctx.anchors
350 assert ctx.profile["websites"] == ["https://danaokafor.example"]
351 assert ctx.profile["posts"][0]["url"] == "https://www.linkedin.com/posts/dana-okafor_activity-1"
352 assert ctx.profile["posts"][0]["date"] == "2026-11-02"
353
354 def test_scrapecreators_failure_reports_failed(self, fake):
355 fake(fail=[SC_PROFILE])
356 ctx = _ctx(linkedin=GIVEN_URL)
357 _resolve(ctx, SC_KEY)
358 assert ctx.linkedin_status == "failed"
359 assert GIVEN_URL in ctx.anchors
360
361 def test_supplied_url_without_any_key_is_anchored_as_no_key(self, fake):
362 http_fake = fake()
363 ctx = _ctx(linkedin=GIVEN_URL)
364 _resolve(ctx, {})
365 assert http_fake.calls == []
366 assert ctx.linkedin_status == "no key"
367 assert GIVEN_URL in ctx.anchors
368
368 lines PYTHON