返回 last30days-skill
test_deepline.py
根目录 / tests / test_deepline.py
1 """Deepline client: request shape, parsing, retries, budgets, and key plumbing.
2
3 HTTP is mocked at ``urllib.request.urlopen``; assertions read what the client
4 sends across that boundary and what it returns.
5 """
6
7 from __future__ import annotations
8
9 import io
10 import json
11 import time
12 import urllib.error
13 import urllib.request
14
15 import pytest
16
17 from lib import deepline, doctor, env
18
19 PROFILE_URL = "https://www.linkedin.com/in/dana-okafor-nwf"
20 EMAIL = "dana.okafor@northwind.example"
21
22
23 def _envelope(data: dict) -> dict:
24 """The live execute response: data under ``result.data``."""
25 return {
26 "job_id": "job_fixture_1",
27 "status": "completed",
28 "result": {"data": data},
29 "billing": {"credits_charged": 0.2, "cost_usd": 0.02},
30 "executionRecovery": {"idempotencyKey": "k", "state": "completed", "replayed": False},
31 }
32
33
34 PROFILE_DATA = {
35 "element": {
36 "firstName": "Dana",
37 "lastName": "Okafor",
38 "headline": "VP Operations at Northwind Freight",
39 "linkedinUrl": PROFILE_URL,
40 "publicIdentifier": "dana-okafor-nwf",
41 "about": "Freight operations, cold chain, and late-night dispatch stories.",
42 "location": {
43 "linkedinText": "Columbus, Ohio, United States",
44 "parsed": {"city": "Columbus", "state": "Ohio", "country": "United States"},
45 },
46 "currentPosition": [
47 {
48 "position": "VP Operations",
49 "companyName": "Northwind Freight",
50 "companyLinkedinUrl": "https://www.linkedin.com/company/northwind-freight/",
51 "companyUniversalName": "northwind-freight",
52 "startDate": {"month": "Mar", "year": 2024, "text": "Mar 2024"},
53 "endDate": {"text": "Present"},
54 },
55 {
56 "position": "Board Member",
57 "companyName": "Lakeside Food Bank",
58 "startDate": {"text": "2022"},
59 },
60 ],
61 "experience": [
62 {
63 "position": "VP Operations",
64 "companyName": "Northwind Freight",
65 "companyLinkedinUrl": "https://www.linkedin.com/company/northwind-freight/",
66 "startDate": {"text": "Mar 2024"},
67 "endDate": {"text": "Present"},
68 },
69 {
70 "position": "Director of Dispatch",
71 "companyName": "Contoso Logistics",
72 "companyLinkedinUrl": "https://www.linkedin.com/company/contoso-logistics/",
73 "startDate": {"text": "Jan 2019"},
74 "endDate": {"text": "Feb 2024"},
75 },
76 ],
77 "websites": [{"url": "https://danaokafor.example"}, "https://northwind.example/team/dana"],
78 }
79 }
80
81 POSTS_DATA = {
82 "elements": [
83 {
84 "id": "7300000000000000001",
85 "linkedinUrl": "https://www.linkedin.com/posts/dana-okafor-nwf_activity-1",
86 "content": "We cut dock wait times by 30% this quarter.",
87 "postedAt": {
88 "timestamp": 1762000000000,
89 "date": "2025-11-01T12:26:40.000Z",
90 "postedAgoShort": "2w",
91 },
92 "author": {
93 "publicIdentifier": "dana-okafor-nwf",
94 "name": "Dana Okafor",
95 "linkedinUrl": PROFILE_URL,
96 },
97 "repost": None,
98 "engagement": {"likes": 120, "comments": 14, "shares": 3},
99 },
100 {
101 "id": "7300000000000000002",
102 "linkedinUrl": "https://www.linkedin.com/posts/dana-okafor-nwf_activity-2",
103 "content": "",
104 "postedAt": {"timestamp": 1761000000000},
105 "author": {"publicIdentifier": "dana-okafor-nwf", "name": "Dana Okafor"},
106 "repost": {"id": "999", "content": "Northwind Freight opens a new hub."},
107 "engagement": {"likes": 8},
108 },
109 ],
110 "pagination": {"paginationToken": "page-2-token"},
111 }
112
113
114 class _Response:
115 def __init__(self, payload, status=200):
116 self.status = status
117 self._body = json.dumps(payload).encode("utf-8")
118 self.headers = {}
119
120 def read(self, size=-1):
121 return self._body
122
123 def geturl(self):
124 return ""
125
126 def __enter__(self):
127 return self
128
129 def __exit__(self, *exc):
130 return False
131
132
133 def _http_error(code: int, body: str = "") -> urllib.error.HTTPError:
134 return urllib.error.HTTPError(
135 "https://code.deepline.com", code, "fixture", hdrs={}, fp=io.BytesIO(body.encode())
136 )
137
138
139 class _Transport:
140 """Scripted urlopen: each step is a payload dict or an exception."""
141
142 def __init__(self, *steps):
143 self.steps = list(steps)
144 self.requests: list[dict] = []
145
146 def __call__(self, req, timeout=None):
147 self.requests.append(
148 {
149 "url": req.full_url,
150 "method": req.get_method(),
151 "headers": {k.lower(): v for k, v in req.header_items()},
152 "body": json.loads(req.data.decode("utf-8")) if req.data else None,
153 }
154 )
155 step = self.steps.pop(0)
156 if callable(step):
157 step = step()
158 if isinstance(step, BaseException):
159 raise step
160 return _Response(step)
161
162
163 @pytest.fixture
164 def transport(monkeypatch):
165 def install(*steps):
166 fake = _Transport(*steps)
167 monkeypatch.setattr(urllib.request, "urlopen", fake)
168 return fake
169
170 return install
171
172
173 def _deadline(seconds: float = 60.0) -> float:
174 return time.monotonic() + seconds
175
176
177 def _client(run_id: str = "run-fixture") -> deepline.DeeplineClient:
178 return deepline.DeeplineClient("dl-test-key", run_id)
179
180
181 # -- request shape and parsing ------------------------------------------------
182
183
184 def test_profile_read_sends_execute_request_and_parses_roles(transport):
185 fake = transport(_envelope(PROFILE_DATA))
186
187 result = _client().get_profile(PROFILE_URL, deadline_monotonic=_deadline())
188
189 sent = fake.requests[0]
190 assert sent["method"] == "POST"
191 assert sent["url"] == (
192 "https://code.deepline.com/api/v2/integrations/harvestapi_get_profile/execute"
193 )
194 assert sent["headers"]["authorization"] == "Bearer dl-test-key"
195 assert sent["headers"]["content-type"] == "application/json"
196 assert sent["headers"]["idempotency-key"]
197 assert sent["body"] == {"payload": {"url": PROFILE_URL}}
198
199 assert result["status"] == "ok"
200 profile = result["data"]
201 assert profile["name"] == "Dana Okafor"
202 assert profile["headline"] == "VP Operations at Northwind Freight"
203 assert profile["location"] == "Columbus, Ohio, United States"
204 assert profile["linkedin_url"] == PROFILE_URL
205 assert profile["current_roles"][0] == {
206 "title": "VP Operations",
207 "company": "Northwind Freight",
208 "company_linkedin_url": "https://www.linkedin.com/company/northwind-freight/",
209 "company_universal_name": "northwind-freight",
210 "start_date": "Mar 2024",
211 "end_date": "Present",
212 }
213 assert profile["current_roles"][1]["company"] == "Lakeside Food Bank"
214 assert profile["current_roles"][1]["start_date"] == "2022"
215 assert [r["company"] for r in profile["history"]] == [
216 "Northwind Freight",
217 "Contoso Logistics",
218 ]
219 assert profile["history"][1]["end_date"] == "Feb 2024"
220 assert profile["websites"] == [
221 "https://danaokafor.example",
222 "https://northwind.example/team/dana",
223 ]
224 assert profile["company_linkedin_urls"] == [
225 "https://www.linkedin.com/company/northwind-freight/",
226 "https://www.linkedin.com/company/contoso-logistics/",
227 ]
228
229
230 def test_profile_parse_tolerates_missing_fields_and_legacy_envelope():
231 legacy = {"result": {"toolResponse": {"rawV2": {"element": {"firstName": "Dana"}}}}}
232 profile = deepline.parse_profile(legacy)
233 assert profile["name"] == "Dana"
234 assert profile["current_roles"] == []
235 assert profile["history"] == []
236 assert profile["websites"] == []
237 assert profile["location"] == ""
238
239 parsed_only = {"result": {"data": {"element": {"location": {"parsed": {"city": "Columbus", "country": "United States"}}, "websites": None}}}}
240 assert deepline.parse_profile(parsed_only)["location"] == "Columbus, United States"
241
242
243 def test_posts_read_parses_date_url_text_and_reshare_flag(transport):
244 fake = transport(_envelope(POSTS_DATA))
245
246 result = _client().get_posts(PROFILE_URL, deadline_monotonic=_deadline())
247
248 sent = fake.requests[0]
249 assert sent["url"].endswith("/integrations/harvestapi_get_profile_posts/execute")
250 assert sent["body"] == {"payload": {"profile": PROFILE_URL, "scrapePostedLimit": "year"}}
251
252 assert result["status"] == "ok"
253 posts = result["data"]["posts"]
254 assert result["data"]["next_token"] == "page-2-token"
255 first, second = posts
256 assert first["id"] == "7300000000000000001"
257 assert first["url"] == "https://www.linkedin.com/posts/dana-okafor-nwf_activity-1"
258 assert first["text"] == "We cut dock wait times by 30% this quarter."
259 assert first["date"] == "2025-11-01"
260 assert first["timestamp"] == 1762000000000
261 assert first["is_reshare"] is False
262 assert first["engagement"]["likes"] == 120
263 # Date derived from the millisecond timestamp when no ISO date is given.
264 assert second["date"] == "2025-10-20"
265 assert second["is_reshare"] is True
266 assert second["text"] == "Northwind Freight opens a new hub."
267
268
269 def test_posts_second_page_sends_pagination_token(transport):
270 fake = transport(_envelope({"elements": []}))
271 result = _client().get_posts(
272 PROFILE_URL, deadline_monotonic=_deadline(), pagination_token="page-2-token"
273 )
274 assert fake.requests[0]["body"]["payload"]["paginationToken"] == "page-2-token"
275 assert result["data"] == {"posts": [], "next_token": None}
276
277
278 def test_lookup_parses_candidate_urls(transport):
279 fake = transport(_envelope({"linkedin_url": PROFILE_URL, "github_url": "", "x_url": None}))
280
281 result = _client().find_profiles(
282 full_name="Dana Okafor",
283 company_name="Northwind Freight",
284 deadline_monotonic=_deadline(),
285 )
286
287 assert fake.requests[0]["url"].endswith("/integrations/limadata_find_person_profiles/execute")
288 assert fake.requests[0]["body"] == {
289 "payload": {"full_name": "Dana Okafor", "company_name": "Northwind Freight"}
290 }
291 assert result["status"] == "ok"
292 assert result["data"] == {"linkedin_url": PROFILE_URL, "github_url": None, "x_url": None}
293
294
295 # -- idempotency, retries, deadlines -------------------------------------------
296
297
298 def test_timeout_then_success_reuses_the_same_idempotency_key(transport):
299 fake = transport(TimeoutError("timed out"), _envelope(PROFILE_DATA))
300
301 result = _client().get_profile(PROFILE_URL, deadline_monotonic=_deadline())
302
303 assert result["status"] == "ok"
304 assert len(fake.requests) == 2
305 keys = {r["headers"]["idempotency-key"] for r in fake.requests}
306 assert len(keys) == 1
307
308
309 def test_5xx_is_retried_once_then_reported(transport):
310 fake = transport(_http_error(502), _http_error(503))
311 result = _client().get_profile(PROFILE_URL, deadline_monotonic=_deadline())
312 assert len(fake.requests) == 2
313 assert result["status"] == "error"
314 assert result["data"] is None
315
316
317 def test_no_retry_when_time_left_cannot_cover_a_fresh_attempt(transport, monkeypatch):
318 monkeypatch.setattr(deepline, "MIN_ATTEMPT_SECONDS", 0.5)
319
320 def slow_timeout():
321 time.sleep(0.3)
322 raise TimeoutError("timed out")
323
324 fake = transport(slow_timeout, _envelope(PROFILE_DATA))
325 result = _client().get_profile(PROFILE_URL, deadline_monotonic=time.monotonic() + 0.7)
326 assert len(fake.requests) == 1
327 assert result["status"] == "timeout"
328
329
330 def test_call_is_skipped_when_deadline_is_too_close(transport):
331 fake = transport(_envelope(PROFILE_DATA))
332 client = _client()
333 result = client.get_profile(PROFILE_URL, deadline_monotonic=time.monotonic() + 1.0)
334 assert fake.requests == []
335 assert result["status"] == "timeout"
336 # A skipped call spends no budget.
337 assert client.calls_made(deepline.TOOL_PROFILE) == 0
338
339
340 def test_idempotency_key_depends_on_run_tool_and_input_and_hides_email(transport):
341 fake = transport(*[_envelope({"linkedin_url": ""})] * 3)
342 deepline.DeeplineClient("k", "run-a").find_profiles(email=EMAIL, deadline_monotonic=_deadline())
343 deepline.DeeplineClient("k", "run-b").find_profiles(email=EMAIL, deadline_monotonic=_deadline())
344 deepline.DeeplineClient("k", "run-a").find_profiles(
345 email="other@northwind.example", deadline_monotonic=_deadline()
346 )
347 keys = [r["headers"]["idempotency-key"] for r in fake.requests]
348 assert len(set(keys)) == 3
349 for key in keys:
350 assert "@" not in key and "dana" not in key.lower()
351
352
353 # -- named failure states, stop rules, and caps ---------------------------------
354
355
356 @pytest.mark.parametrize(
357 ("code", "status"),
358 [(401, "auth failed"), (429, "rate limited"), (402, "out of credits")],
359 )
360 def test_http_failures_map_to_named_states(transport, code, status):
361 transport(_http_error(code, '{"error": "fixture"}'))
362 result = _client().get_profile(PROFILE_URL, deadline_monotonic=_deadline())
363 assert result == {"status": status, "data": None, "detail": result["detail"]}
364
365
366 def test_402_stops_further_deepline_calls_for_the_run(transport):
367 fake = transport(_http_error(402, '{"error": "insufficient credits"}'), _envelope(POSTS_DATA))
368 client = _client()
369
370 first = client.get_profile(PROFILE_URL, deadline_monotonic=_deadline())
371 second = client.get_posts(PROFILE_URL, deadline_monotonic=_deadline())
372
373 assert first["status"] == "out of credits"
374 assert second["status"] == "out of credits"
375 assert len(fake.requests) == 1
376 assert client.stopped == "out of credits"
377 assert {"tool": deepline.TOOL_PROFILE, "status": "out of credits"} in client.events
378
379
380 def test_budget_caps_refuse_second_lookup_and_third_profile_read(transport):
381 fake = transport(
382 _envelope({"linkedin_url": PROFILE_URL}),
383 _envelope(PROFILE_DATA),
384 _envelope(PROFILE_DATA),
385 )
386 client = _client()
387
388 assert client.find_profiles(
389 full_name="Dana Okafor", company_name="Northwind Freight", deadline_monotonic=_deadline()
390 )["status"] == "ok"
391 second_lookup = client.find_profiles(
392 full_name="Dana Okafor", company_domain="northwind.example", deadline_monotonic=_deadline()
393 )
394 assert client.get_profile(PROFILE_URL, deadline_monotonic=_deadline())["status"] == "ok"
395 assert client.get_profile(PROFILE_URL + "-2", deadline_monotonic=_deadline())["status"] == "ok"
396 third_read = client.get_profile(PROFILE_URL + "-3", deadline_monotonic=_deadline())
397
398 assert second_lookup["status"] == "over budget"
399 assert third_read["status"] == "over budget"
400 assert len(fake.requests) == 3
401 assert {"tool": deepline.TOOL_LOOKUP, "status": "over budget"} in client.events
402
403
404 def test_post_pages_are_capped_at_two(transport):
405 fake = transport(_envelope(POSTS_DATA), _envelope({"elements": []}))
406 client = _client()
407 client.get_posts(PROFILE_URL, deadline_monotonic=_deadline())
408 client.get_posts(PROFILE_URL, deadline_monotonic=_deadline(), pagination_token="page-2-token")
409 third = client.get_posts(PROFILE_URL, deadline_monotonic=_deadline(), pagination_token="p3")
410 assert third["status"] == "over budget"
411 assert len(fake.requests) == 2
412
413
414 def test_unexpected_response_shape_is_an_error_not_an_exception(transport):
415 transport({"status": "failed", "error": "upstream"})
416 result = _client().get_profile(PROFILE_URL, deadline_monotonic=_deadline())
417 assert result["status"] == "error"
418 assert result["data"] is None
419
420
421 # -- privacy -------------------------------------------------------------------
422
423
424 def test_email_never_appears_in_log_output(transport, monkeypatch, capsys):
425 monkeypatch.setenv("LAST30DAYS_DEBUG", "1")
426 transport(
427 _http_error(500, json.dumps({"error": "bad input", "email": EMAIL})),
428 _http_error(500, json.dumps({"error": "bad input", "email": EMAIL})),
429 )
430 result = _client().find_profiles(email=EMAIL, deadline_monotonic=_deadline())
431 assert result["status"] == "error"
432 captured = capsys.readouterr()
433 output = captured.err + captured.out
434 assert "Deepline" in output # the client does log the call
435 assert EMAIL not in output
436 assert "dana.okafor" not in output
437
438
439 # -- key plumbing: run and doctor read the same availability -------------------
440
441
442 def test_env_file_key_is_seen_by_run_and_doctor():
443 env.CONFIG_FILE.write_text("DEEPLINE_API_KEY=dl-from-dotenv\n", encoding="utf-8")
444 env.CONFIG_FILE.chmod(0o600)
445
446 config = env.get_config()
447
448 assert config["DEEPLINE_API_KEY"] == "dl-from-dotenv"
449 assert deepline.is_available(config) is True
450 client = deepline.from_config(config, "run-fixture")
451 assert client is not None and client.api_key == "dl-from-dotenv"
452 record = doctor._SOURCE_BUILDERS["deepline"](config)
453 assert record["status"] == "ok"
454 assert "deepline" in doctor.SOURCE_ORDER
455
456
457 def test_doctor_reports_deepline_unconfigured_without_key():
458 config = env.get_config()
459 assert deepline.is_available(config) is False
460 assert deepline.from_config(config, "run-fixture") is None
461 record = doctor._SOURCE_BUILDERS["deepline"](config)
462 assert record["status"] == "unconfigured"
463 assert "DEEPLINE_API_KEY" in record["fix"]
464
464 lines PYTHON