SPB Git

Repository Public

test_crawl.py 6.1 KB 126 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER7# File             : tests/integration/test_crawl.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# =============================================================================4041import json42from pathlib import Path4344import pytest4546pytestmark = pytest.mark.pg47MANIFEST = json.loads((Path(__file__).resolve().parents[1] / "fixtures" / "site" / "manifest.json").read_text())484950async def test_scrape_single_page(stack):51    await stack.start_worker()52    r = await stack.client.post("/v1/scrape", json={"url": stack.url("/about"), "render": "http"})53    assert r.status_code == 202, r.text54    job = await stack.wait(r.json()["job_id"])55    assert job["status"] == "succeeded", job56    items = await stack.results(job["job_id"])57    assert len(items) == 1 and items[0]["http_status"] == 20058    assert items[0]["content"]["markdown"].strip()59    kinds = {a["kind"] for a in items[0]["artifacts"]}60    assert {"html", "markdown", "extract_json"} <= kinds61    ua = [q for q in stack.site.state.requests if q.path == "/about"][0].headers.get("User-Agent", "")62    assert ua.startswith("SpiderBot/") and "+https://" in ua636465def _expected(kind_filter):66    return [u for u in MANIFEST["urls"] if kind_filter(u)]676869async def _crawl(stack, **extra):70    body = {"url": stack.url("/"), "render": "http", "budgets": {"max_pages": 2000, "max_depth": 12, "max_urls_per_pattern": 25},71            "use_sitemaps": True, "extract": {"formats": ["markdown", "json"]}} | extra72    r = await stack.client.post("/v1/crawl", json=body)73    assert r.status_code == 202, r.text74    return await stack.wait(r.json()["job_id"], timeout=240)757677async def test_full_http_crawl_matches_manifest(stack):78    """Every URL an HTML crawler can discover is fetched; forbidden URLs are never requested; traps are bounded."""79    await stack.start_worker(concurrency=8)80    # the simulated walls live on the same host: a CAPTCHA there suspends the host (tested separately)81    job = await _crawl(stack, policy={"exclude_paths": ["^/wall/"]})82    assert job["status"] in ("partial", "succeeded"), job83    requested = stack.site.state.paths()84    # 1. nothing forbidden by robots.txt was requested, although linked and listed in the sitemap85    forbidden = [u["path"] for u in _expected(lambda u: u["expected"] == "forbidden_robots")]86    hit = [p for p in forbidden if p.split("?")[0] in requested]87    assert not hit, f"robots-disallowed URLs were requested: {hit}"88    # 2. no side effect of any kind89    assert stack.site.state.side_effects == []90    assert all(q.method in ("GET", "HEAD") for q in stack.site.state.requests)91    # 3. every expected page reachable without a browser was fetched92    front = []93    after = 094    while True:95        page = (await stack.client.get(f"/v1/jobs/{job['job_id']}/frontier", params={"limit": 1000, "after": after})).json()96        front += page["items"]97        after = page["next_after"]98        if not after:99            break100    base = stack.site.base_url101    got = {f["url"][len(base):]: f for f in front}102    must = _expected(lambda u: u["expected"] == "crawl" and u["discovered_via"] not in ("browser_route",)103                     and "browser" not in (u.get("requires") or [])104                     and not u["path"].startswith(("/wall/", "/login"))105                     and not str(u.get("discovered_from") or "").startswith("/wall/"))106    missing = [u["path"] for u in must if u["path"] not in got and u["path"].split("?")[0] not in requested]107    assert not missing, f"expected URLs never fetched: {missing}"108    # 4. traps are bounded by the per-pattern budget and reported109    trap_urls = [p for p in got if p.startswith("/trap/")]110    assert 0 < len(trap_urls) <= 160, len(trap_urls)111    assert any(b.startswith("pattern:") for b in job["progress"]["budgets_hit"])112    # 5. SSRF redirects were refused and never followed113    for p in ("/r/internal", "/r/metadata"):114        assert got[p]["status"] == "blocked" and "ssrf" in got[p]["reason"], got[p]115    assert got["/r/external"]["status"] in ("blocked", "failed")116    assert got["/loop/a"]["status"] == "failed" and "redirect_loop" in got["/loop/a"]["reason"]117    # 6. coverage report is honest about what it measures118    cov = (await stack.client.get(f"/v1/sites/{job['site_id']}/coverage", params={"job_id": job["job_id"]})).json()119    assert cov["real_coverage"] == "unknown" and cov["blocked"] >= len(forbidden) - 2120    assert cov["discovered"]["by_discovery_method"].get("sitemap", 0) >= 1121    # 7. semantic parameters are kept apart, duplicates are linked with provenance122    assert got["/catalog?category=books"]["status"] == "fetched" and got["/catalog?category=music"]["status"] == "fetched"123    dups = [f for f in front if f["status"] == "duplicate"]124    assert any(f["url"].endswith(("/dup/a", "/dup/b")) for f in dups)125    assert all(f["duplicate_of"] for f in dups)126
Files main
Menu

Theme