Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/integration/test_api_contract.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"""Public contract: OpenAPI document, mandated routes, response shapes, pagination, error model."""42import base6443import json44from pathlib import Path4546import pytest47from apihelpers import (48 all_results,49 assert_error,50 assert_utc_timestamps,51 client_for,52 db,53 finished_crawl,54 is_uuid,55)5657pytestmark = pytest.mark.pg58ROOT = Path(__file__).resolve().parents[2]59MANDATED = [60 ("post", "/v1/scrape"), ("post", "/v1/crawl"), ("post", "/v1/map"), ("post", "/v1/screenshot"),61 ("post", "/v1/deep-capture"), ("post", "/v1/extract"), ("post", "/v1/ocr"), ("post", "/v1/vision"),62 ("post", "/v1/batch"), ("post", "/v1/monitor"), ("post", "/v1/diff"), ("post", "/v1/search"),63 ("get", "/v1/jobs/{job_id}"), ("post", "/v1/jobs/{job_id}/cancel"), ("get", "/v1/jobs/{job_id}/results"),64 ("get", "/v1/artifacts/{artifact_id}"), ("get", "/v1/sites/{site_id}/graph"),65 ("get", "/v1/sites/{site_id}/coverage"), ("get", "/v1/health"), ("get", "/v1/metrics"),66]676869def _cursor(*parts) -> str:70 return base64.urlsafe_b64encode(json.dumps(parts).encode()).decode().rstrip("=")717273async def test_openapi_document_is_published_valid_and_complete(stack):74 from openapi_spec_validator import validate75 live = (await client_for(stack).get("/v1/openapi.json")).json()76 committed = json.loads((ROOT / "docs" / "openapi.json").read_text())77 assert live == committed, "docs/openapi.json is stale: run .venv/bin/python scripts/export_openapi.py"78 assert live["openapi"].startswith("3.1")79 validate(live) # raises on any violation of the OpenAPI 3.1 schema80 for method, path in MANDATED:81 assert method in live["paths"].get(path, {}), f"{method.upper()} {path} is missing from the contract"82 assert not [p for p in live["paths"] if p.startswith("/internal")], "the worker API must not be published"83 # request models are closed: an unknown field is an error, not an ignored option84 for name in ("ScrapeRequest", "CrawlRequest", "PolicyOptions", "Budgets", "BatchRequest", "MonitorRequest"):85 assert live["components"]["schemas"][name].get("additionalProperties") is False, name868788async def test_mandated_routes_are_routed_and_guarded(stack):89 """Each mandated route exists on the running gateway: anonymous callers get 401 (never 404/405)."""90 anon = client_for(stack)91 for method, path in MANDATED:92 if path == "/v1/health":93 continue94 url = path.replace("{job_id}", "00000000-0000-0000-0000-000000000000") \95 .replace("{site_id}", "00000000-0000-0000-0000-000000000000") \96 .replace("{artifact_id}", "00000000-0000-0000-0000-000000000000")97 r = await anon.request(method.upper(), url, json={} if method == "post" else None)98 assert_error(r, 401, "unauthorized")99 assert (await anon.get("/v1/health")).status_code == 200100101102async def test_real_job_responses_ids_timestamps_and_shapes(stack):103 job = await finished_crawl(stack)104 jid = job["job_id"]105 c = stack.client106 # ---- job107 again = (await c.get(f"/v1/jobs/{jid}")).json()108 assert again["job_id"] == jid and is_uuid(jid) and is_uuid(job["site_id"])109 assert again["status_url"] == f"/v1/jobs/{jid}" and again["results_url"] == f"/v1/jobs/{jid}/results"110 assert again["created_at"] == job["created_at"] and again["finished_at"] == job["finished_at"]111 assert_utc_timestamps(again, min_count=4)112 assert again["created_at"] <= again["started_at"] <= again["finished_at"]113 assert again["progress"]["urls"].get("fetched", 0) >= 3114 assert again["request"]["url"] == stack.url("/blog?page=1")115 # ---- results116 items = await all_results(c, jid)117 n_db = await db(stack, "select count(*) from snapshots where job_id=$1", jid, one=True)118 assert len(items) == n_db >= 3119 assert_utc_timestamps(items, min_count=len(items))120 for it in items:121 assert is_uuid(it["snapshot_id"]) and it["http_status"] == 200 and it["url"].startswith(stack.site.base_url)122 assert len(it["content_hash"]) == 64 and it["content"]["markdown"].strip()123 for a in it["artifacts"]:124 assert is_uuid(a["artifact_id"]) and len(a["sha256"]) == 64 and a["bytes"] > 0125 assert a["url"].startswith(f"/v1/artifacts/{a['artifact_id']}?exp=")126 # ids are stable between two reads127 assert [i["snapshot_id"] for i in await all_results(c, jid)] == [i["snapshot_id"] for i in items]128 snap = (await c.get(f"/v1/snapshots/{items[0]['snapshot_id']}")).json()129 assert snap["snapshot_id"] == items[0]["snapshot_id"] and snap["content_hash"] == items[0]["content_hash"]130 # ---- jobs list, sites, graph, coverage, frontier, events131 listing = (await c.get("/v1/jobs")).json()132 assert [j["job_id"] for j in listing["items"]] == [jid] and listing["next_cursor"] is None133 assert_utc_timestamps(listing)134 sites = (await c.get("/v1/sites")).json()["items"]135 assert [s["site_id"] for s in sites] == [job["site_id"]] and sites[0]["origin"] == stack.site.base_url136 assert_utc_timestamps(sites)137 graph = (await c.get(f"/v1/sites/{job['site_id']}/graph")).json()138 assert graph["job_id"] == jid and len(graph["nodes"]) == sum(again["progress"]["urls"].values())139 assert_utc_timestamps(graph, min_count=len(graph["nodes"]))140 node_ids = {n["id"] for n in graph["nodes"]}141 assert all(e["source"] in node_ids for e in graph["edges"]) and graph["edges"]142 cov = (await c.get(f"/v1/sites/{job['site_id']}/coverage")).json()143 assert cov["job_id"] == jid and cov["succeeded"] == len(items) and cov["real_coverage"] == "unknown"144 assert cov["discovered"]["urls_admitted"] == len(graph["nodes"])145 front = (await c.get(f"/v1/jobs/{jid}/frontier")).json()146 assert {f["id"] for f in front["items"]} == node_ids147 assert_utc_timestamps(front, min_count=len(node_ids))148 ev = (await c.get(f"/v1/jobs/{jid}/events")).text149 assert "event: job.created" in ev and "event: job.finished" in ev150 for line in ev.splitlines():151 if line.startswith("data: "):152 at = json.loads(line[6:])["at"]153 assert at.endswith("Z") and "+00:00" not in at, at154 assert_utc_timestamps((await c.get("/v1/keys")).json())155 assert_utc_timestamps((await c.get("/v1/audit")).json(), min_count=0)156157158async def test_cursor_pagination_terminates_without_repeat_or_skip(stack):159 job = await finished_crawl(stack, max_pages=9, max_depth=2)160 jid = job["job_id"]161 c = stack.client162 expected = [str(r["id"]) for r in await db(163 stack, "select id from snapshots where job_id=$1 order by captured_at, id", jid)]164 assert len(expected) >= 5165 seen, cur, pages = [], None, 0166 while True:167 r = await c.get(f"/v1/jobs/{jid}/results", params={"limit": 1, "include_content": "false"}168 | ({"cursor": cur} if cur else {}))169 assert r.status_code == 200, r.text170 page = r.json()171 assert len(page["items"]) <= 1172 seen += [i["snapshot_id"] for i in page["items"]]173 cur = page["next_cursor"]174 pages += 1175 assert pages <= len(expected) + 1, "pagination does not terminate"176 if not cur:177 break178 assert seen == expected, "limit=1 pagination repeated or skipped items"179 assert pages == len(expected), "the last page must not be followed by an empty one"180 # same guarantee on the graph (integer cursor) and on the job list (timestamp + id cursor)181 nodes, cur = [], None182 while True:183 g = (await c.get(f"/v1/sites/{job['site_id']}/graph", params={"limit": 2} | ({"cursor": cur} if cur else {}))).json()184 nodes += [n["id"] for n in g["nodes"]]185 cur = g["next_cursor"]186 if not cur:187 break188 assert nodes == [r["id"] for r in await db(stack, "select id from urls where job_id=$1 order by id", jid)]189 for i in range(4):190 assert (await c.post("/v1/scrape", json={"url": stack.url(f"/blog/post-{i + 1}"), "render": "http"})).status_code == 202191 ids, cur = [], None192 while True:193 lj = (await c.get("/v1/jobs", params={"limit": 1} | ({"cursor": cur} if cur else {}))).json()194 ids += [j["job_id"] for j in lj["items"]]195 cur = lj["next_cursor"]196 if not cur:197 break198 assert len(ids) == len(set(ids)) == 5199 assert ids == [str(r["id"]) for r in await db(stack, "select id from jobs order by created_at desc, id desc")]200201202async def test_malformed_cursors_are_client_errors(stack):203 job = await finished_crawl(stack, max_pages=3)204 c = stack.client205 bad = ["!!!", "AAAA", _cursor(1), _cursor("x", "y"), _cursor({"a": 1}), _cursor("2026-01-01T00:00:00Z"),206 _cursor(None, None), base64.urlsafe_b64encode(b'{"a":1}').decode().rstrip("="), _cursor([1], [2])]207 for cur in bad:208 for url in (f"/v1/jobs/{job['job_id']}/results", "/v1/jobs", f"/v1/sites/{job['site_id']}/graph"):209 if url.endswith("/graph") and cur == _cursor(1):210 continue # a one-integer cursor is the valid graph form211 assert_error(await c.get(url, params={"cursor": cur}), 400, "invalid_cursor")212 if cur != _cursor(1):213 assert_error(await c.post("/v1/search", json={"query": "ferry", "cursor": cur}), 400, "invalid_cursor")214215216async def test_every_4xx_has_the_structured_error_body(stack):217 c = stack.client218 anon = client_for(stack)219 _, ro = await _key(stack, ["read"])220 nil = "00000000-0000-0000-0000-000000000000"221 assert_error(await anon.get("/v1/jobs"), 401, "unauthorized")222 assert_error(await client_for(stack, ro).post("/v1/scrape", json={"url": stack.url("/")}), 403, "forbidden")223 assert_error(await c.get(f"/v1/jobs/{nil}"), 404, "not_found")224 assert_error(await c.get("/v1/jobs/not-a-uuid"), 404, "not_found")225 assert_error(await c.get("/v1/no-such-route"), 404, "not_found")226 assert_error(await c.get("/v1/scrape"), 405, "method_not_allowed")227 assert_error(await c.post("/v1/scrape", json={"url": stack.url("/"), "nope": 1}), 422, "validation_error")228 assert_error(await c.post("/v1/scrape", content=b"{not json", headers={"content-type": "application/json"}),229 422, "validation_error")230 assert_error(await c.get("/v1/jobs", params={"limit": 0}), 422, "validation_error")231 assert_error(await c.post("/v1/session", json={}), 400, "bad_request")232 assert_error(await c.post("/v1/jobs/" + nil + "/retry"), 404, "not_found")233 # identifiers that are not UUIDs are a clean 404 on every id route, never a 500234 for method, url in (("delete", "/v1/keys/zzz"), ("post", "/v1/keys/zzz/rotate"), ("delete", "/v1/policies/zzz"),235 ("post", "/v1/workers/zzz/drain"), ("post", "/v1/connectors/zzz/validate"),236 ("post", "/v1/connectors/zzz/status?status=active"), ("post", "/v1/monitors/zzz/enable"),237 ("get", "/v1/snapshots/zzz"), ("get", "/v1/artifacts/zzz"), ("delete", "/v1/jobs/zzz"),238 ("get", "/v1/sites/zzz/graph"), ("get", "/v1/sites/zzz/coverage"),239 ("get", "/v1/jobs/zzz/frontier"), ("post", "/v1/jobs/zzz/cancel")):240 assert_error(await c.request(method.upper(), url), 404, "not_found")241 assert_error(await c.get("/v1/changes", params={"schedule_id": "zzz"}), 422, "validation_error")242 assert_error(await c.post("/v1/diff", json={"snapshot_a": "zzz", "snapshot_b": nil}), 404, "not_found")243 assert_error(await c.post("/v1/ocr", json={"artifact_id": "zzz"}), 404, "not_found")244 # a filter the database rejects is described in the API's terms, not the driver's245 for bad in ({"site_id": "zzz"}, {"since": "not a date"}, {"until": "2026-13-45"}):246 e = assert_error(await c.post("/v1/search", json={"query": "x"} | bad), 400, "invalid_filter")247 assert "$" not in e["message"] and "argument" not in e["message"] and "zzz" not in e["message"], e248249250async def _key(stack, scopes):251 from apihelpers import make_key252 return await make_key(stack, scopes)253