SPB Git

Repository Public

test_sdk_python.py 10.8 KB 219 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/integration/test_sdk_python.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"""Python SDK against the real in-process stack (gateway, worker, fixture website)."""42import asyncio43import hashlib44import sys45from pathlib import Path4647import httpx48import pytest4950sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "sdk" / "python"))5152import spider_sdk as sdk53from spider_sdk import AsyncSpider, Budgets, ExtractOptions, PolicyOptions5455pytestmark = pytest.mark.pg565758class Tap(httpx.AsyncBaseTransport):59    """Real transport that records requests and can lose the answer of the first matching request."""6061    def __init__(self, drop_first: str | None = None):62        self.inner = httpx.AsyncHTTPTransport()63        self.requests: list[httpx.Request] = []64        self.drop_first = drop_first65        self.dropped = 06667    async def handle_async_request(self, request: httpx.Request) -> httpx.Response:68        self.requests.append(request)69        resp = await self.inner.handle_async_request(request)70        if self.drop_first and request.url.path == self.drop_first and not self.dropped:71            self.dropped += 172            await resp.aread()  # the server did process the request; only its answer is lost73            await resp.aclose()74            raise httpx.ReadError("connection reset before the response arrived", request=request)75        return resp7677    async def aclose(self) -> None:78        await self.inner.aclose()798081def client(stack, **kw) -> AsyncSpider:82    return AsyncSpider(stack.base, stack.admin_key, **kw)838485async def test_scrape_and_wait(stack):86    await stack.start_worker()87    async with client(stack) as c:88        assert (await c.health())["status"] == "ok"89        out = await c.scrape_and_wait(stack.url("/about"), render="http", wait_timeout=60,90                                      extract=ExtractOptions(formats=["markdown", "json", "text"]))91        assert out.succeeded, out.job92        assert out.job["status_url"] == f"/v1/jobs/{out.job['job_id']}"93        assert len(out.results) == 1 and out.results[0]["http_status"] == 20094        item = out.results[0]95        assert item["content"]["markdown"].strip() and item["url"] == stack.url("/about")96        # the snapshot is reachable by id and through the history of its URL97        snap = await c.get_snapshot(item["snapshot_id"])98        assert snap["content_hash"] == item["content_hash"]99        hist = await c.snapshot_history(stack.url("/about"))100        assert [h["snapshot_id"] for h in hist["items"]] == [item["snapshot_id"]]101    ua = next(q for q in stack.site.state.requests if q.path == "/about").headers.get("User-Agent", "")102    assert ua.startswith("SpiderBot/")  # the SDK's own user agent never reaches the collected site103104105async def test_crawl_iterates_all_results_across_pages(stack):106    await stack.start_worker()107    tap = Tap()108    async with client(stack, transport=tap) as c:109        job = await c.crawl(stack.url("/blog?page=1"), render="http", use_sitemaps=False,110                            budgets=Budgets(max_pages=8, max_depth=1),111                            policy=PolicyOptions(include_paths=["^/blog"]),112                            extract=ExtractOptions(formats=["markdown", "json", "text"]))113        final = await c.wait_for_job(job["job_id"], timeout=90, poll_interval=0.1)114        assert final["status"] in ("succeeded", "partial"), final115        before = len(tap.requests)116        urls = [i["url"] async for i in c.iter_results(job["job_id"], page_size=2, include_content=False)]117        pages = [r for r in tap.requests[before:] if r.url.path.endswith("/results")]118        expected = [i["url"] for i in await stack.results(job["job_id"])]119        assert urls == expected and len(urls) == len(set(urls)) >= 5120        assert len(pages) == -(-len(urls) // 2) >= 3  # one request per page, no extra one121        assert [r.url.params.get("cursor") is None for r in pages] == [True] + [False] * (len(pages) - 1)122        # the same job through the listing and the site reports123        assert job["job_id"] in [j["job_id"] async for j in c.iter_jobs(kind="crawl", page_size=1)]124        cov = await c.site_coverage(final["site_id"], job_id=job["job_id"])125        assert cov["real_coverage"] == "unknown" and cov["succeeded"] >= len(urls)126        graph = await c.site_graph(final["site_id"], job_id=job["job_id"], limit=5)127        assert len(graph["nodes"]) == 5 and graph["next_cursor"]128        lines = (await c.export(job["job_id"], format="jsonl")).decode().strip().splitlines()129        assert len(lines) == len(urls)130131132async def test_events_until_job_finished(stack):133    await stack.start_worker()134    async with client(stack) as c:135        job = await c.scrape(stack.url("/legal"), render="http")136        events = [e async for e in c.stream_events(job["job_id"])]137        assert events and events[-1].type == "job.finished"138        assert all(e.id and e.id.isdigit() for e in events)139        assert [int(e.id) for e in events] == sorted({int(e.id) for e in events})140        assert isinstance(events[-1].data, dict) and events[-1].data["status"] == "succeeded"141        # resuming after the last id replays nothing; waiting through events returns the final job142        job2 = await c.scrape(stack.url("/landing"), render="http")143        final = await c.wait_for_job(job2["job_id"], use_events=True, timeout=60)144        assert final["status"] == "succeeded"145146147async def test_artifact_download_is_hash_verified(stack):148    await stack.start_worker()149    async with client(stack) as c:150        out = await c.scrape_and_wait(stack.url("/about"), render="http", wait_timeout=60)151        arts = out.results[0]["artifacts"]152        assert {"html", "markdown"} <= {a["kind"] for a in arts}153        for a in arts:154            data = await c.get_artifact(a["artifact_id"], expected_sha256=a["sha256"])155            assert hashlib.sha256(data).hexdigest() == a["sha256"] and len(data) == a["bytes"]156        with pytest.raises(sdk.ArtifactIntegrityError):157            await c.get_artifact(arts[0]["artifact_id"], expected_sha256="0" * 64)158        with pytest.raises(sdk.NotFoundError) as e:159            await c.get_artifact("00000000-0000-4000-8000-000000000000")160        assert e.value.code == "not_found" and e.value.request_id161162163async def test_mandatory_policy_is_a_typed_validation_error(stack):164    async with client(stack) as c:165        for field in ("respect_robots_txt", "stop_on_access_denied"):166            with pytest.raises(sdk.MandatoryPolicyError) as e:167                await c.request("POST", "/v1/scrape", json={"url": stack.url("/about"), "policy": {field: False}})168            x = e.value169            assert isinstance(x, sdk.ValidationError) and (x.status, x.code) == (422, "mandatory_policy")170            assert x.request_id and any(field in d["loc"] for d in x.details)171            with pytest.raises(ValueError, match="mandatory policy"):  # the typed surface refuses before sending172                await c.scrape(stack.url("/about"), policy={field: False})173        assert (await c.list_jobs())["items"] == []  # nothing was created174175176async def test_dropped_response_is_retried_into_the_same_job(stack):177    tap = Tap(drop_first="/v1/scrape")178    async with client(stack, transport=tap, backoff_base=0.01) as c:179        job = await c.scrape(stack.url("/about"), render="http")180        posts = [r for r in tap.requests if r.url.path == "/v1/scrape"]181        assert tap.dropped == 1 and len(posts) == 2182        assert posts[0].headers["idempotency-key"] == posts[1].headers["idempotency-key"]183        assert job.get("idempotent_replay") is True184        jobs = [j async for j in c.iter_jobs()]185        assert [j["job_id"] for j in jobs] == [job["job_id"]]  # two submissions, one job186        # the same key with another request is a conflict, typed and not retried187        n = len(tap.requests)188        with pytest.raises(sdk.IdempotencyConflictError):189            await c.scrape(stack.url("/legal"), render="http", idempotency_key=posts[0].headers["idempotency-key"])190        assert len(tap.requests) == n + 1191192193async def test_typed_errors_from_the_real_gateway(stack):194    async with AsyncSpider(stack.base, "sk_not_a_real_key") as bad:195        with pytest.raises(sdk.AuthenticationError) as e:196            await bad.list_jobs()197        assert e.value.status == 401 and "sk_not_a_real_key" not in str(e.value)198    async with client(stack) as c:199        with pytest.raises(sdk.NotFoundError):200            await c.get_job("00000000-0000-4000-8000-000000000000")201        with pytest.raises(sdk.ValidationError) as e:202            await c.list_jobs(cursor="garbage")203        assert (e.value.status, e.value.code) == (400, "invalid_cursor")204        with pytest.raises(sdk.ValidationError) as e:205            await c.request("POST", "/v1/scrape", json={"url": stack.url("/about"), "no_such_option": 1})206        assert e.value.code == "validation_error" and not isinstance(e.value, sdk.MandatoryPolicyError)207        assert len(await c.webhook_secret()) == 64 and (await c.me())["scopes"]208209210async def test_blocking_client_against_the_real_gateway(stack):211    await stack.start_worker()212213    def run() -> tuple[dict, list[str]]:214        with sdk.Spider(stack.base, stack.admin_key) as c:215            out = c.scrape_and_wait(stack.url("/legal"), render="http", wait_timeout=60)216            return out.job, [i["url"] for i in c.iter_results(out.job["job_id"])]217    job, urls = await asyncio.to_thread(run)218    assert job["status"] == "succeeded" and urls == [stack.url("/legal")]219
Files main
Menu

Theme