Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/e2e/devstack.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"""Boot the whole SPIDER stack outside pytest: gateway + dashboard, local fixture site, one worker.4243Used to develop the dashboard against real data and by ``capture_screenshots.py``. Nothing here is44simulated: jobs are executed by a real worker against the fixture website of ``tests/fixtures/site``.4546 SPIDER_ENV=test .venv/bin/python tests/e2e/devstack.py --port 8911 --seed4748The database named by SPIDER_TEST_DATABASE_URL (default postgresql://localhost/spider_dash) is49WIPED at start. The admin key is written to ``<data-dir>/admin.key``.50"""51from __future__ import annotations5253import argparse54import asyncio55import importlib.util56import os57import sys58import tempfile59from pathlib import Path6061ROOT = Path(__file__).resolve().parents[2]6263PRODUCT_SCHEMA = {64 "type": "object",65 "properties": {66 "name": {"type": "string"},67 "price": {"type": "number"},68 "currency": {"type": "string"},69 "sku": {"type": "string"},70 },71 "required": ["name", "price"],72}737475def integration_conftest():76 """The integration conftest module (Stack class and `stack` fixture), loaded by path."""77 name = "spider_integration_conftest"78 if name in sys.modules:79 return sys.modules[name]80 spec = importlib.util.spec_from_file_location(name, ROOT / "tests" / "integration" / "conftest.py")81 mod = importlib.util.module_from_spec(spec)82 sys.modules[name] = mod83 spec.loader.exec_module(mod)84 return mod858687def browser_available() -> bool:88 try:89 import spider.browser.pool # noqa: F40190 return True91 except Exception: # noqa: BLE00192 return False939495async def boot(*, port: int | None = None, db: str | None = None, data_dir: Path | None = None,96 caps: tuple[str, ...] | None = None):97 """Start fixture site, gateway and one worker. Returns (stack, stop_coroutine_function)."""98 import asyncpg99 import uvicorn100 ic = integration_conftest()101 from server import start_fixture # tests/fixtures/site (path added by the integration conftest)102 site = await start_fixture(port=ic.free_port())103 port = port or ic.free_port()104 db = db or os.environ.get("SPIDER_TEST_DATABASE_URL", "postgresql://localhost/spider_dash")105 data_dir = data_dir or Path(tempfile.mkdtemp(prefix="spider-dash-"))106 os.environ.update({107 "SPIDER_ENV": "test", "SPIDER_DATABASE_URL": db, "SPIDER_DATA_DIR": str(data_dir / "data"),108 "SPIDER_SECRET_FILE": str(data_dir / "secret.key"), "SPIDER_TEST_ALLOW_HOSTS": f"127.0.0.1:{site.port}",109 "SPIDER_TEST_DELAY_MS": os.environ.get("SPIDER_TEST_DELAY_MS", "0"), "SPIDER_LEASE_SECONDS": "30",110 "SPIDER_COOKIE_SECURE": "0",111 })112 conn = await asyncpg.connect(db)113 await conn.execute("drop schema public cascade; create schema public")114 await conn.close()115 from spider import auth116 from spider.api.app import create_app117 from spider.config import Settings118 st = ic.Stack()119 st.site = site120 st.settings = Settings()121 st.app = create_app(st.settings)122 server = uvicorn.Server(uvicorn.Config(st.app, host="127.0.0.1", port=port, log_level="warning", lifespan="on"))123 srv_task = asyncio.create_task(server.serve())124 while not server.started:125 await asyncio.sleep(0.02)126 st.base = f"http://127.0.0.1:{port}"127 async with st.orch.pool.acquire() as c:128 tid = await c.fetchval("insert into tenants(name) values('test') returning id")129 st.tenant_id = str(tid)130 _, st.admin_key = await auth.create_key(c, tid, "admin", ["read", "write", "admin", "metrics"])131 _, st.reader_key = await auth.create_key(c, tid, "reader", ["read"])132 _, st.worker_key = await auth.create_key(c, tid, "worker", ["worker"], kind="worker")133 import httpx134 st.client = httpx.AsyncClient(base_url=st.base, headers={"Authorization": f"Bearer {st.admin_key}"}, timeout=120)135 (data_dir / "admin.key").write_text(st.admin_key)136 if caps is None:137 caps = ("http", "browser") if browser_available() else ("http",)138 try:139 from spider.ocr.client import available as ocr_available140 if "browser" in caps and ocr_available():141 caps = (*caps, "ocr")142 except Exception: # noqa: BLE001143 pass144 st.caps = caps145 await st.start_worker(caps=caps)146147 async def stop() -> None:148 for w, task in list(st.workers):149 await st.stop_worker(w, task, hard=True)150 await w.close()151 await st.client.aclose()152 server.should_exit = True153 await asyncio.gather(srv_task, return_exceptions=True)154 await site.close()155 return st, stop156157158async def _post(st, path: str, body: dict) -> dict:159 r = await st.client.post(path, json=body)160 if r.status_code >= 300:161 raise RuntimeError(f"{path} -> {r.status_code} {r.text[:300]}")162 return r.json()163164165async def seed(st, *, log=print, walls: bool = True) -> dict:166 """Create a realistic set of jobs on the fixture site. Returns the ids the screenshots need."""167 out: dict = {}168 browser = "browser" in st.caps169 crawl = await _post(st, "/v1/crawl", {"url": st.url("/"), "budgets": {"max_pages": 60, "max_depth": 3},170 "render": "http",171 "policy": {"min_delay_ms": 250, "exclude_paths": ["^/wall/"]},172 "metadata": {"purpose": "dashboard seed"}})173 out["crawl"] = crawl["job_id"]174 j = await st.wait(crawl["job_id"], timeout=240)175 log(f"crawl {j['status']} {j['progress']['urls']}")176 ext = await _post(st, "/v1/extract", {"url": st.url("/product/1"), "render": "browser" if browser else "http",177 "extract": {"schema": PRODUCT_SCHEMA, "ocr": browser,178 "formats": ["markdown", "json", "text"]}})179 out["extract"] = ext["job_id"]180 j = await st.wait(ext["job_id"], timeout=240)181 log(f"extract {j['status']}")182 if browser:183 deep = await _post(st, "/v1/deep-capture", {184 "url": st.url("/product/1"),185 "capture": {"tiles": True, "tile_height": 700, "tile_overlap": 80, "interactive_states": True,186 "profiles": ["desktop", "mobile", "tablet"]},187 "extract": {"ocr": True, "schema": PRODUCT_SCHEMA, "formats": ["markdown", "json", "text"]}})188 out["deep"] = deep["job_id"]189 j = await st.wait(deep["job_id"], timeout=400)190 log(f"deep-capture {j['status']}")191 ui = await _post(st, "/v1/deep-capture", {"url": st.url("/ui/tabs"),192 "capture": {"tiles": True, "interactive_states": True}})193 out["states"] = ui["job_id"]194 j = await st.wait(ui["job_id"], timeout=400)195 log(f"deep-capture (states) {j['status']}")196 # two snapshots of a page that changes between fetches -> a real diff197 a = await _post(st, "/v1/scrape", {"url": st.url("/cond/changing"), "render": "browser" if browser else "http",198 "extract": {"formats": ["markdown", "json", "text"]}})199 await st.wait(a["job_id"], timeout=200)200 st.site.state.bump() # the fixture serves the next variant of /cond/changing201 b = await _post(st, "/v1/scrape", {"url": st.url("/cond/changing"), "render": "browser" if browser else "http",202 "extract": {"formats": ["markdown", "json", "text"]},203 "metadata": {"run": "second"}})204 await st.wait(b["job_id"], timeout=200)205 out["diff_url"] = st.url("/cond/changing")206 mon = await _post(st, "/v1/monitor", {"name": "Changing page", "interval_s": 300, "cooldown_s": 0,207 "watch": ["content", "fields"],208 "request": {"url": st.url("/cond/changing"), "render": "http"}})209 out["monitor"] = mon.get("id") or mon.get("schedule_id")210 # two monitor runs so that the maintenance loop records a real change event211 changes = []212 for attempt in range(60):213 await asyncio.sleep(1)214 changes = (await st.client.get("/v1/changes")).json()["items"]215 if changes:216 break217 mons = (await st.client.get("/v1/monitors")).json()["items"]218 if attempt % 6 == 5 and mons and mons[0]["last_snapshot_id"]:219 st.site.state.bump()220 await st.client.post(f"/v1/monitors/{out['monitor']}/run-now")221 log(f"monitor changes: {len(changes)}")222 sch = await _post(st, "/v1/schemas", {"name": "product", "json_schema": PRODUCT_SCHEMA})223 out["schema"] = sch["schema_id"]224 await st.client.put("/v1/policies", json={"domain": "slow.example", "min_delay_ms": 5000,225 "notes": "publisher asked for a slow crawl"})226 if walls:227 # last on purpose: the simulated CAPTCHA wall suspends the fixture host (mandatory policy)228 w = await _post(st, "/v1/scrape", {"url": st.url("/wall/captcha"), "render": "http"})229 out["wall"] = w["job_id"]230 j = await st.wait(w["job_id"], timeout=120)231 log(f"wall scrape {j['status']}")232 return out233234235async def _main() -> None:236 ap = argparse.ArgumentParser(description=__doc__)237 ap.add_argument("--port", type=int, default=8911)238 ap.add_argument("--seed", action="store_true", help="create a set of real jobs on the fixture site")239 ap.add_argument("--http-only", action="store_true")240 args = ap.parse_args()241 st, stop = await boot(port=args.port, caps=("http",) if args.http_only else None)242 print(f"dashboard: {st.base}/dashboard/\nfixture: {st.site.base_url}\nadmin key: {st.admin_key}\n"243 f"read key: {st.reader_key}\nworker: {st.caps}", flush=True)244 try:245 if args.seed:246 print("seeded:", await seed(st), flush=True)247 await asyncio.Event().wait()248 finally:249 await stop()250251252if __name__ == "__main__":253 asyncio.run(_main())254