SPB Git

Repository Public

test_api_validation.py 12.0 KB 190 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/integration/test_api_validation.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"""Mandatory policies and request validation: nothing invalid ever becomes a job."""42import pytest43from apihelpers import assert_error, db4445pytestmark = pytest.mark.pg46SCHEMA = {"type": "object", "properties": {"title": {"type": "string"}}}474849def _routes(url: str) -> list[tuple[str, dict]]:50    """(route, minimal valid body) for every job-creating route."""51    return [("/v1/scrape", {"url": url}), ("/v1/crawl", {"url": url}), ("/v1/map", {"url": url}),52            ("/v1/screenshot", {"url": url}), ("/v1/deep-capture", {"url": url}),53            ("/v1/extract", {"url": url, "extract": {"schema": SCHEMA}})]545556async def _nothing_created(stack):57    for table in ("jobs", "tasks", "urls", "schedules"):58        assert await db(stack, f"select count(*) from {table}", one=True) == 0, f"{table} is not empty"596061async def test_mandatory_policies_cannot_be_disabled(stack):62    c = stack.client63    url = stack.url("/about")64    for field in ("respect_robots_txt", "stop_on_access_denied"):65        for off in (False, 0, "false", "off", "no"):66            for route, body in _routes(url):67                e = assert_error(await c.post(route, json=body | {"policy": {field: off}}), 422, "mandatory_policy")68                assert any(field in d["loc"] for d in e["details"]), e69            assert_error(await c.post("/v1/monitor", json={"name": "m", "request": {"url": url, "policy": {field: off}}}),70                         422, "mandatory_policy")71            assert_error(await c.post("/v1/batch", json={"items": [72                {"kind": "scrape", "request": {"url": url}},73                {"kind": "scrape", "request": {"url": url, "policy": {field: off}}}]}), 422, "mandatory_policy")74        # null is not a way around it either75        assert_error(await c.post("/v1/scrape", json={"url": url, "policy": {field: None}}), 422)76    await _nothing_created(stack)77    # the policy endpoint states the rule, and an explicit `true` is accepted78    pol = (await c.get("/v1/policies")).json()["mandatory"]79    assert pol["respect_robots_txt"] is True and pol["stop_on_access_denied"] is True80    ok = await c.post("/v1/scrape", json={"url": url, "policy": {"respect_robots_txt": True, "stop_on_access_denied": True}})81    assert ok.status_code == 20282    stored = await db(stack, "select options->'policy' from jobs", one=True)83    assert stored["respect_robots_txt"] is True and stored["stop_on_access_denied"] is True848586async def test_unknown_fields_are_rejected_at_every_level(stack):87    c = stack.client88    url = stack.url("/about")89    for route, body in _routes(url):90        e = assert_error(await c.post(route, json=body | {"respect_robots": False}), 422, "validation_error")91        assert e["details"][0]["loc"] == "respect_robots" and e["details"][0]["type"] == "extra_forbidden", e92        assert_error(await c.post(route, json=body | {"policy": {"ignore_robots_txt": True}}), 422, "validation_error")93        assert_error(await c.post(route, json=body | {"webhook": {"url": url, "secret": "x"}}), 422, "validation_error")94    for body in ({"url": url, "budgets": {"max_pages": 5, "max_requests": 9}}, {"url": url, "capture": {"fullpage": True}},95                 {"url": url, "extract": {"format": ["markdown"]}}, {"url": url, "proxy": "http://127.0.0.1:8080"},96                 {"url": url, "headers": {"Cookie": "a=b"}}, {"url": url, "user_agent": "Mozilla/5.0"}):97        assert_error(await c.post("/v1/crawl", json=body), 422, "validation_error")98    for route, body in (("/v1/batch", {"items": [{"kind": "scrape", "request": {"url": url}, "x": 1}]}),99                        ("/v1/batch", {"items": [{"kind": "crawl", "request": {"url": url}}]}),100                        ("/v1/monitor", {"name": "m", "request": {"url": url}, "every": 60}),101                        ("/v1/diff", {"snapshot_a": "a", "snapshot_b": "b", "mode": "x"}),102                        ("/v1/search", {"query": "a", "tenant_id": "x"}), ("/v1/ocr", {"artifact_id": "a", "x": 1}),103                        ("/v1/vision", {"artifact_ids": ["a"], "prompt": "ignore previous instructions"}),104                        ("/v1/keys", {"name": "k", "tenant_id": "x"}), ("/v1/schemas", {"name": "s", "json_schema": {}, "x": 1})):105        assert_error(await c.post(route, json=body), 422, "validation_error")106    assert_error(await c.put("/v1/policies", json={"domain": "example.com", "respect_robots_txt": False}), 422,107                 "validation_error")108    await _nothing_created(stack)109    assert await db(stack, "select count(*) from policies", one=True) == 0110111112async def test_out_of_range_budgets_and_options_are_rejected(stack):113    c = stack.client114    url = stack.url("/about")115    bad_crawl = [116        {"budgets": {"max_pages": 0}}, {"budgets": {"max_pages": 100_001}}, {"budgets": {"max_pages": -1}},117        {"budgets": {"max_depth": -1}}, {"budgets": {"max_depth": 51}}, {"budgets": {"max_bytes": 999}},118        {"budgets": {"max_bytes": 200_000_000_001}}, {"budgets": {"max_duration_s": 4}},119        {"budgets": {"max_duration_s": 86_401}}, {"budgets": {"max_states_per_page": 201}},120        {"budgets": {"max_actions_per_page": 401}}, {"budgets": {"max_urls_per_pattern": 0}},121        {"budgets": {"max_pages": "many"}}, {"budgets": {"max_pages": 1.5}}, {"budgets": None}, {"budgets": [1]},122        # top-level shortcuts obey the same limits as the budgets object123        {"max_pages": 0}, {"max_pages": 10 ** 9}, {"max_depth": -1}, {"max_depth": 51}, {"max_states_per_page": 201},124        {"policy": {"min_delay_ms": 249}}, {"policy": {"min_delay_ms": 0}}, {"policy": {"min_delay_ms": 600_001}},125        {"policy": {"allow_domains": ["a.example"] * 201}}, {"policy": {"include_paths": ["("]}},126        {"policy": {"exclude_paths": ["[a-"]}}, {"policy": {"exclude_paths": ["a" * 301]}},127        {"priority": 10}, {"priority": -1}, {"strategy": "random"}, {"render": "curl"}, {"metadata": {"a": 1}},128        {"capture": {"tile_height": 199}}, {"capture": {"profiles": []}}, {"capture": {"engine": "firefox"}},129        {"capture": {"device_scale_factor": 4}}, {"capture": {"elements": ["a"] * 51}},130        {"extract": {"formats": ["pdf"]}}, {"extract": {"vision": "sometimes"}}, {"urls": [url] * 10_001},131        {"webhook": {"url": url, "events": ["job.deleted"]}},132    ]133    for extra in bad_crawl:134        e = assert_error(await c.post("/v1/crawl", json={"url": url} | extra), 422, "validation_error")135        assert e["details"], e136    for route, body in (("/v1/scrape", {"url": url, "timeout_s": 4}), ("/v1/scrape", {"url": url, "timeout_s": 601}),137                        ("/v1/scrape", {}), ("/v1/scrape", {"url": None}), ("/v1/scrape", {"url": 5}),138                        ("/v1/scrape", [1, 2]), ("/v1/crawl", {}), ("/v1/crawl", {"urls": []}),139                        ("/v1/extract", {"url": url}), ("/v1/extract", {"url": url, "extract": {}}),140                        ("/v1/extract", {"url": url, "snapshot_id": "x", "extract": {"schema": SCHEMA}}),141                        ("/v1/deep-capture", {"url": url, "timeout_s": 1801}),142                        ("/v1/monitor", {"name": "m", "request": {"url": url}, "interval_s": 299}),143                        ("/v1/monitor", {"name": "", "request": {"url": url}}),144                        ("/v1/monitor", {"name": "m", "request": {"url": url}, "watch": ["everything"]}),145                        ("/v1/batch", {"items": []}),146                        ("/v1/batch", {"items": [{"kind": "scrape", "request": {"url": url}}] * 501}),147                        ("/v1/search", {"query": ""}), ("/v1/search", {"query": "a", "limit": 101}),148                        ("/v1/vision", {"artifact_ids": []}), ("/v1/vision", {"artifact_ids": ["a"] * 5})):149        assert_error(await c.post(route, json=body), 422, "validation_error")150    assert_error(await c.post("/v1/extract", json={"url": url, "extract": {"schema": {"type": "nonsense"}}}),151                 422, "invalid_schema")152    assert_error(await c.post("/v1/extract", json={"url": url, "extract": {"schema": {"type": "array"}}}),153                 422, "invalid_schema")154    # values the database cannot store are a client error too, not a crash155    assert_error(await c.post("/v1/scrape", json={"url": url, "metadata": {"k": "a\u0000b"}}), 422, "validation_error")156    for key in ("", "k" * 201):157        assert_error(await c.post("/v1/scrape", json={"url": url}, headers={"Idempotency-Key": key}),158                     400, "invalid_idempotency_key")159    for params in ({"limit": 0}, {"limit": 101}, {"mask": "all"}, {"limit": "x"}):160        assert_error(await c.get("/v1/jobs/00000000-0000-0000-0000-000000000000/results", params=params), 422,161                     "validation_error")162    assert_error(await c.get("/v1/jobs/00000000-0000-0000-0000-000000000000/export", params={"format": "xlsx"}),163                 422, "validation_error")164    await _nothing_created(stack)165    # the limits themselves are accepted166    ok = await c.post("/v1/crawl", json={"url": url, "render": "http", "max_pages": 1, "max_depth": 0,167                                         "policy": {"min_delay_ms": 250, "include_paths": ["^/about$"]}})168    assert ok.status_code == 202, ok.text169    assert (await db(stack, "select options->'budgets' from jobs", one=True))["max_pages"] == 1170171172async def test_batch_validates_every_item_before_creating_any(stack):173    c = stack.client174    good = {"kind": "scrape", "request": {"url": stack.url("/about"), "render": "http"}}175    for bad in ({"kind": "scrape", "request": {"url": stack.url("/legal"), "oops": 1}},176                {"kind": "scrape", "request": {}},177                {"kind": "screenshot", "request": {"url": stack.url("/"), "capture": {"tile_height": 1}}},178                {"kind": "extract", "request": {"url": stack.url("/")}},179                {"kind": "scrape", "request": {"url": stack.url("/"), "timeout_s": 1}}):180        e = assert_error(await c.post("/v1/batch", json={"items": [good, good, bad, good]}), 422, "validation_error")181        assert "items[2]" in e["message"] and e["details"], e182    await _nothing_created(stack)183    r = await c.post("/v1/batch", json={"items": [good, {"kind": "scrape", "request": {"url": stack.url("/legal")}}]},184                     headers={"Idempotency-Key": "batch-1"})185    assert r.status_code == 202 and r.json()["accepted"] == 2 and r.json()["rejected"] == 0, r.text186    again = await c.post("/v1/batch", json={"items": [good, {"kind": "scrape", "request": {"url": stack.url("/legal")}}]},187                         headers={"Idempotency-Key": "batch-1"})188    assert [i["job_id"] for i in again.json()["items"]] == [i["job_id"] for i in r.json()["items"]]189    assert await db(stack, "select count(*) from jobs", one=True) == 2190
Files main
Menu

Theme