Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/unit/sdk/test_sdk_client.py8# Module : Tests9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Retries, idempotency, pagination, events, artifacts and error mapping of the Python SDK (httpx.MockTransport)."""42import hashlib43import json4445import httpx46import pytest47import spider_sdk as sdk48from sdk_testkit import API_KEY, Script, err, ok4950JOB = {"job_id": "j1", "status": "queued", "status_url": "/v1/jobs/j1", "results_url": "/v1/jobs/j1/results",51 "events_url": "/v1/jobs/j1/events"}525354# ----------------------------------------------------------------------------- retries and idempotency55async def test_submission_is_retried_with_the_same_idempotency_key():56 s = Script(err(503, "unavailable"), httpx.ReadTimeout("lost answer"), ok(JOB, 202))57 async with s.client() as c:58 job = await c.scrape("https://example.org/")59 assert job["job_id"] == "j1" and len(s.requests) == 360 keys = {r.headers["idempotency-key"] for r in s.requests}61 assert len(keys) == 1 and len(keys.pop()) == 3662 assert len({r.content for r in s.requests}) == 1 # same body every time63 assert len(s.sleeps) == 2 and 0.25 <= s.sleeps[0] <= 0.5 and 0.5 <= s.sleeps[1] <= 1.0 # backoff + jitter646566async def test_each_logical_call_gets_its_own_key_and_a_given_key_is_kept():67 s = Script(ok(JOB, 202), ok(JOB, 202), ok(JOB, 202))68 async with s.client() as c:69 await c.scrape("https://example.org/")70 await c.scrape("https://example.org/")71 await c.crawl("https://example.org/", idempotency_key="order-42")72 k = [r.headers["idempotency-key"] for r in s.requests]73 assert k[0] != k[1] and k[2] == "order-42"747576async def test_retries_are_bounded():77 s = Script(*[err(503, "unavailable") for _ in range(3)])78 async with s.client(max_retries=2) as c:79 with pytest.raises(sdk.ServerError) as e:80 await c.get_job("j1")81 assert len(s.requests) == 3 and e.value.status == 503 and not s.steps828384@pytest.mark.parametrize("status", [502, 503, 504])85async def test_gateway_errors_are_retried_on_reads(status):86 s = Script(err(status, "upstream"), ok(JOB))87 async with s.client() as c:88 assert (await c.get_job("j1"))["job_id"] == "j1"89 assert len(s.requests) == 2909192async def test_500_is_not_retried():93 s = Script(err(500, "internal_error"))94 async with s.client() as c:95 with pytest.raises(sdk.ServerError):96 await c.get_job("j1")97 assert len(s.requests) == 19899100async def test_429_honours_retry_after_header_then_body():101 s = Script(err(429, "rate_limited", headers={"Retry-After": "7"}),102 err(429, "rate_limited", details={"retry_after_s": 3}), ok(JOB))103 async with s.client() as c:104 await c.get_job("j1")105 assert s.sleeps == [7.0, 3.0]106107108async def test_429_is_retried_even_without_idempotency_key_but_gives_up_typed():109 s = Script(err(429, "rate_limited", details={"retry_after_s": 1}), ok({"id": "m1"}, 201))110 async with s.client() as c:111 assert (await c.create_monitor("m", {"url": "https://example.org/"}))["id"] == "m1"112 s = Script(*[err(429, "rate_limited", details={"retry_after_s": 1}) for _ in range(2)])113 async with s.client(max_retries=1) as c:114 with pytest.raises(sdk.RateLimitError) as e:115 await c.get_job("j1")116 assert e.value.retry_after == 1.0 and e.value.code == "rate_limited" and s.sleeps == [1.0]117118119async def test_quota_without_retry_after_and_excessive_retry_after_are_not_retried():120 s = Script(err(429, "quota_exceeded", details={"quota": "max_jobs_per_day", "limit": 5}))121 async with s.client() as c:122 with pytest.raises(sdk.QuotaExceededError) as e:123 await c.scrape("https://example.org/")124 assert len(s.requests) == 1 and e.value.details["quota"] == "max_jobs_per_day"125 assert isinstance(e.value, sdk.RateLimitError)126 s = Script(err(429, "rate_limited", headers={"Retry-After": "3600"}))127 async with s.client() as c:128 with pytest.raises(sdk.RateLimitError):129 await c.get_job("j1")130 assert s.sleeps == []131132133async def test_post_without_idempotency_key_is_not_retried_after_an_ambiguous_failure():134 for step in (err(503, "unavailable"), httpx.ReadTimeout("x"), httpx.RemoteProtocolError("x")):135 s = Script(step)136 async with s.client() as c:137 with pytest.raises((sdk.ServerError, sdk.TransportError)):138 await c.create_monitor("m", {"url": "https://example.org/"})139 assert len(s.requests) == 1 and "idempotency-key" not in s.requests[0].headers140 s = Script(err(503, "unavailable"))141 async with s.client() as c:142 with pytest.raises(sdk.ServerError):143 await c.request("POST", "/v1/scrape", json={"url": "https://example.org/"})144 assert len(s.requests) == 1145146147async def test_connection_never_established_is_always_retried():148 s = Script(httpx.ConnectError("refused"), httpx.ConnectTimeout("slow"), ok({"id": "m1"}, 201))149 async with s.client() as c:150 await c.create_monitor("m", {"url": "https://example.org/"})151 assert len(s.requests) == 3152 s = Script(*[httpx.ConnectError("refused") for _ in range(4)])153 async with s.client() as c:154 with pytest.raises(sdk.TransportError) as e:155 await c.health()156 assert len(s.requests) == 4 and API_KEY not in str(e.value)157158159async def test_low_level_request_with_a_key_is_retried():160 s = Script(err(502, "bad_gateway"), ok(JOB, 202))161 async with s.client() as c:162 out = await c.request("POST", "/v1/scrape", json={"url": "https://example.org/"}, idempotency_key="k1")163 assert out["job_id"] == "j1" and [r.headers["idempotency-key"] for r in s.requests] == ["k1", "k1"]164165166@pytest.mark.parametrize("status,code,cls", [167 (400, "invalid_cursor", sdk.ValidationError),168 (401, "unauthorized", sdk.AuthenticationError),169 (403, "forbidden", sdk.PermissionDeniedError),170 (404, "not_found", sdk.NotFoundError),171 (409, "idempotency_conflict", sdk.IdempotencyConflictError),172 (409, "connector_inactive", sdk.ConflictError),173 (422, "validation_error", sdk.ValidationError),174 (422, "mandatory_policy", sdk.MandatoryPolicyError),175 (501, "not_implemented", sdk.ServerError),176])177async def test_errors_are_typed_and_4xx_is_never_retried(status, code, cls):178 details = [{"loc": "policy.respect_robots_txt", "msg": "…"}]179 s = Script(err(status, code, "explained", details))180 async with s.client() as c:181 with pytest.raises(cls) as e:182 await c.scrape("https://example.org/")183 x = e.value184 assert len(s.requests) == 1 and s.sleeps == []185 assert (x.status, x.code, x.message, x.details, x.request_id) == (status, code, "explained", details, "rid-1")186 assert isinstance(x, sdk.APIError) and isinstance(x, sdk.SpiderError)187 if status in (401, 403):188 assert isinstance(x, sdk.AuthError)189 if code == "mandatory_policy":190 assert isinstance(x, sdk.ValidationError)191192193async def test_non_json_error_body_still_gives_a_typed_error():194 s = Script(httpx.Response(404, text="<html>nginx</html>", headers={"X-Request-Id": "edge-9"}))195 async with s.client() as c:196 with pytest.raises(sdk.NotFoundError) as e:197 await c.get_job("j1")198 assert e.value.code == "http_error" and e.value.request_id == "edge-9" and "nginx" in e.value.message199200201# ----------------------------------------------------------------------------- client hygiene202async def test_key_user_agent_and_urls():203 s = Script(ok(JOB), ok(JOB))204 async with s.client(user_agent="marge/1.0") as c:205 await c.get_job("a/b?c")206 await c.snapshot_history("https://example.org/?q=1")207 assert API_KEY not in repr(c)208 r = s.requests[0]209 assert r.headers["authorization"] == f"Bearer {API_KEY}"210 assert r.headers["user-agent"] == f"spider-sdk-python/{sdk.__version__} marge/1.0"211 assert r.url.raw_path == b"/v1/jobs/a%2Fb%3Fc" # identifiers cannot escape their path segment212 assert all(API_KEY not in str(q.url) for q in s.requests)213 assert s.requests[1].url.params["url"] == "https://example.org/?q=1"214215216@pytest.mark.parametrize("base,key", [("ftp://x", "k"), ("https://user:pw@x", "k"), ("https://x?key=1", "k"),217 ("https://x", ""), ("https://x", "a b")])218def test_constructor_refuses_unsafe_configuration(base, key):219 with pytest.raises(ValueError):220 sdk.AsyncSpider(base, key)221222223async def test_redirects_are_not_followed():224 s = Script(httpx.Response(302, headers={"Location": "https://elsewhere.example/steal"}))225 async with s.client() as c:226 await c.request("GET", "/v1/health")227 assert len(s.requests) == 1228229230# ----------------------------------------------------------------------------- pagination and waiting231async def test_iter_results_follows_next_cursor():232 pages = [{"items": [{"url": "a"}, {"url": "b"}], "next_cursor": "c1"},233 {"items": [{"url": "c"}], "next_cursor": "c2"}, {"items": [], "next_cursor": None}]234 s = Script(*[ok(p) for p in pages])235 async with s.client() as c:236 urls = [i["url"] async for i in c.iter_results("j1", page_size=2, include_content=False)]237 assert urls == ["a", "b", "c"]238 assert [r.url.params.get("cursor") for r in s.requests] == [None, "c1", "c2"]239 assert all(r.url.params["limit"] == "2" and r.url.params["include_content"] == "false" for r in s.requests)240241242async def test_iter_jobs_and_iter_search_follow_next_cursor():243 s = Script(ok({"items": [{"job_id": "1"}], "next_cursor": "n"}), ok({"items": [{"job_id": "2"}]}),244 ok({"items": [{"url": "u1"}], "next_cursor": "o"}), ok({"items": [{"url": "u2"}], "next_cursor": None}))245 async with s.client() as c:246 assert [j["job_id"] async for j in c.iter_jobs(kind="crawl")] == ["1", "2"]247 assert [h["url"] async for h in c.iter_search("harbour")] == ["u1", "u2"]248 assert s.requests[1].url.params["cursor"] == "n"249 assert s.bodies()[2:] == [{"query": "harbour"}, {"query": "harbour", "cursor": "o"}]250251252async def test_wait_for_job_polls_with_backoff_until_terminal():253 s = Script(ok(JOB), ok(JOB | {"status": "running"}), ok(JOB | {"status": "running"}),254 ok(JOB | {"status": "partial"}))255 async with s.client() as c:256 job = await c.wait_for_job("j1", poll_interval=0.2, max_poll_interval=0.4)257 assert job["status"] == "partial" and s.sleeps == pytest.approx([0.2, 0.3, 0.4])258259260@pytest.mark.parametrize("state", sdk.JOB_STATES)261async def test_terminal_states(state):262 assert sdk.is_terminal({"status": state}) == (state not in ("queued", "running"))263264265async def test_wait_for_job_times_out_without_cancelling():266 s = Script(ok(JOB | {"status": "running"}))267 async with s.client() as c:268 with pytest.raises(sdk.JobTimeoutError) as e:269 await c.wait_for_job("j1", timeout=0)270 assert e.value.last_status == "running" and isinstance(e.value, TimeoutError)271 assert [r.method for r in s.requests] == ["GET"]272273274async def test_scrape_and_wait_returns_job_and_all_results():275 s = Script(ok(JOB, 202), ok(JOB | {"status": "succeeded"}),276 ok({"items": [{"url": "a"}], "not_collected": [{"url": "x", "status": "blocked"}], "next_cursor": "n"}),277 ok({"items": [{"url": "b"}], "not_collected": [], "next_cursor": None}))278 async with s.client() as c:279 out = await c.scrape_and_wait("https://example.org/", render="http")280 assert out.succeeded and [i["url"] for i in out.results] == ["a", "b"] and len(out.not_collected) == 1281 assert s.bodies()[0] == {"url": "https://example.org/", "render": "http"}282283284# ----------------------------------------------------------------------------- events285SSE = (b": keep-alive\n\n"286 b'id: 1\nevent: job.progress\ndata: {"pages": 1}\n\n'287 b'id: 2\r\nevent: url.fetched\r\ndata: {"url":\r\ndata: "https://example.org/"}\r\n\r\n'288 b"event: note\ndata: not json\n\n"289 b'id: 3\nevent: job.finished\ndata: {"status": "succeeded"}\n\n'290 b'id: 4\nevent: never\ndata: {}\n\n')291292293def sse(body: bytes) -> httpx.Response:294 return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)295296297async def test_stream_events_parses_sse_and_stops_at_job_finished():298 s = Script(sse(SSE))299 async with s.client() as c:300 events = [e async for e in c.stream_events("j1")]301 assert [(e.id, e.type) for e in events] == [("1", "job.progress"), ("2", "url.fetched"), ("2", "note"),302 ("3", "job.finished")]303 assert events[1].data == {"url": "https://example.org/"} and events[2].data == "not json"304 assert s.requests[0].headers["accept"] == "text/event-stream"305 assert "last-event-id" not in s.requests[0].headers306307308async def test_stream_events_resumes_with_last_event_id():309 first = b'id: 7\nevent: job.progress\ndata: {}\n\n' # the stream ends before job.finished310 s = Script(sse(first), sse(b'id: 8\nevent: job.finished\ndata: {}\n\n'))311 async with s.client() as c:312 ids = [e.id async for e in c.stream_events("j1", last_event_id="5")]313 assert ids == ["7", "8"]314 assert [r.headers.get("last-event-id") for r in s.requests] == ["5", "7"]315316317async def test_stream_events_gives_up_on_a_stream_that_never_delivers():318 s = Script(*[sse(b"") for _ in range(3)])319 async with s.client(max_retries=2) as c:320 with pytest.raises(sdk.TransportError):321 _ = [e async for e in c.stream_events("j1")]322 assert len(s.requests) == 3323324325async def test_wait_for_job_via_events():326 s = Script(sse(SSE), ok(JOB | {"status": "succeeded"}))327 async with s.client() as c:328 job = await c.wait_for_job("j1", use_events=True)329 assert job["status"] == "succeeded" and [r.url.path for r in s.requests] == ["/v1/jobs/j1/events", "/v1/jobs/j1"]330331332def test_sse_parser_line_by_line():333 p = sdk.SSEParser()334 out = [p.feed(line) for line in ["retry: 10", "id: 9", "data: 1", "data: 2", "", "", ": c", "data", ""]]335 events = [e for e in out if e]336 assert events[0] == sdk.Event("message", "1\n2", "9") and p.last_event_id == "9"337 assert len(events) == 1 # an empty data field with no event name dispatches nothing338339340# ----------------------------------------------------------------------------- artifacts and export341async def test_get_artifact_verifies_the_announced_hash():342 data = b"\x89PNG fixture bytes"343 good = hashlib.sha256(data).hexdigest()344345 def resp(sha):346 return httpx.Response(200, content=data, headers={"X-Spider-Sha256": sha} if sha else {})347 s = Script(resp(good), resp(good.upper()), resp("0" * 64), resp(None), resp(good))348 async with s.client() as c:349 assert await c.get_artifact("a1") == data350 assert await c.get_artifact("a1", expected_sha256=good) == data351 with pytest.raises(sdk.ArtifactIntegrityError) as e:352 await c.get_artifact("a1")353 assert e.value.expected == "0" * 64 and e.value.actual == good354 with pytest.raises(sdk.ArtifactIntegrityError):355 await c.get_artifact("a1") # no header: integrity cannot be established356 with pytest.raises(sdk.ArtifactIntegrityError):357 await c.get_artifact("a1", expected_sha256="1" * 64)358 assert s.requests[0].url.path == "/v1/artifacts/a1" and not s.requests[0].url.query359360361async def test_export_returns_bytes():362 s = Script(httpx.Response(200, content=b'{"url":"a"}\n', headers={"content-type": "application/x-ndjson"}))363 async with s.client() as c:364 assert json.loads(await c.export("j1", mask_pii=True)) == {"url": "a"}365 assert dict(s.requests[0].url.params) == {"format": "jsonl", "mask": "pii"}366367368# ----------------------------------------------------------------------------- synchronous client369def test_sync_client_has_the_same_surface_and_works():370 import inspect371 public = {n for n, f in vars(sdk.AsyncSpider).items() if not n.startswith("_") and n != "aclose"372 and (inspect.iscoroutinefunction(f) or inspect.isasyncgenfunction(f))}373 assert public and all(callable(getattr(sdk.Spider, n)) for n in public)374 assert inspect.signature(sdk.Spider.scrape) == inspect.signature(sdk.AsyncSpider.scrape)375 s = Script(err(503, "unavailable"), ok(JOB, 202), ok(JOB | {"status": "succeeded"}),376 ok({"items": [{"url": "a"}], "next_cursor": "n"}), ok({"items": [{"url": "b"}]}),377 sse(SSE), err(404, "not_found"))378 with sdk.Spider("http://spider.test", API_KEY, transport=httpx.MockTransport(s.handler), sleep=s.sleep) as c:379 assert API_KEY not in repr(c)380 job = c.scrape("https://example.org/")381 assert c.wait_for_job(job["job_id"])["status"] == "succeeded"382 assert [i["url"] for i in c.iter_results("j1")] == ["a", "b"]383 assert [e.type for e in c.stream_events("j1")][-1] == "job.finished"384 with pytest.raises(sdk.NotFoundError):385 c.get_job("nope")386 assert s.requests[0].headers["idempotency-key"] == s.requests[1].headers["idempotency-key"]387 c.close() # closing twice is harmless388