Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/integration/conftest.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"""Integration stack: PostgreSQL (spider_test), gateway, one worker and the local fixture site.4243The fixture site is reachable only because SPIDER_ENV=test and its exact host:port is listed in44SPIDER_TEST_ALLOW_HOSTS; every other loopback or private destination stays blocked.45"""46import asyncio47import os48import socket49import sys50from pathlib import Path5152import asyncpg53import httpx54import pytest55import pytest_asyncio56import uvicorn5758ROOT = Path(__file__).resolve().parents[2]59sys.path.insert(0, str(ROOT / "tests" / "fixtures" / "site"))60DB = os.environ.get("SPIDER_TEST_DATABASE_URL", "postgresql://localhost/spider_test")616263def free_port() -> int:64 s = socket.socket()65 s.bind(("127.0.0.1", 0))66 p = s.getsockname()[1]67 s.close()68 return p697071class Stack:72 def __init__(self):73 self.base = ""74 self.site = None75 self.admin_key = ""76 self.worker_key = ""77 self.settings = None78 self.app = None79 self.workers = []80 self.client: httpx.AsyncClient | None = None81 self.port = 082 self.hook_port = 0 # reserved loopback port a test may bind a webhook listener on (SSRF allowlist)83 self._server = None84 self._srv_task = None8586 async def start_gateway(self):87 """Start a gateway app (new process-equivalent) on the same database, data directory and port."""88 from spider.api.app import create_app89 self.app = create_app(self.settings)90 self._server = uvicorn.Server(uvicorn.Config(self.app, host="127.0.0.1", port=self.port,91 log_level="warning", lifespan="on"))92 self._srv_task = asyncio.create_task(self._server.serve())93 while not self._server.started:94 if self._srv_task.done():95 await self._srv_task96 await asyncio.sleep(0.02)97 self.base = f"http://127.0.0.1:{self.port}"98 if self.client is not None: # connections of the previous gateway are gone99 await self.client.aclose()100 self.client = httpx.AsyncClient(base_url=self.base, timeout=60,101 headers={"Authorization": f"Bearer {self.admin_key}"})102103 async def stop_gateway(self):104 """Stop the gateway (coordinator down): workers keep running and see connection errors."""105 if self._server is None:106 return107 self._server.should_exit = True108 await asyncio.gather(self._srv_task, return_exceptions=True)109 self._server = self._srv_task = None110111 async def fake_worker(self, name="fake", caps=("http",)) -> "FakeWorker":112 """A hand-driven worker speaking the internal API: lets a test hold, expire and replay leases."""113 fw = FakeWorker(self, name, list(caps))114 await fw.register()115 return fw116117 @property118 def orch(self):119 return self.app.state.spider.orch120121 @property122 def maint(self):123 return self.app.state.spider.maint124125 def url(self, path: str) -> str:126 return self.site.base_url + path127128 async def start_worker(self, caps=("http",), concurrency=4, name=None):129 from spider.worker import Worker130 w = Worker(self.settings, self.base, self.worker_key, list(caps), name=name or f"w{len(self.workers)}",131 concurrency=concurrency)132 task = asyncio.create_task(w.run())133 self.workers.append((w, task))134 return w, task135136 async def stop_worker(self, w, task, hard=False):137 if hard:138 task.cancel() # simulates a crash: no abandon, leases are left to expire139 else:140 w.stopping.set()141 await asyncio.gather(task, return_exceptions=True)142 self.workers = [x for x in self.workers if x[0] is not w]143144 async def wait(self, job_id: str, timeout: float = 90) -> dict:145 t0 = asyncio.get_running_loop().time()146 while True:147 j = (await self.client.get(f"/v1/jobs/{job_id}")).json()148 if j["status"] not in ("queued", "running"):149 return j150 if asyncio.get_running_loop().time() - t0 > timeout:151 raise AssertionError(f"job still {j['status']}: {j['progress']}")152 await asyncio.sleep(0.2)153154 async def results(self, job_id: str) -> list[dict]:155 items, cur = [], None156 while True:157 r = (await self.client.get(f"/v1/jobs/{job_id}/results", params={"limit": 100} | ({"cursor": cur} if cur else {}))).json()158 items += r["items"]159 cur = r["next_cursor"]160 if not cur:161 return items162163164class FakeWorker:165 def __init__(self, stack: Stack, name: str, caps: list[str]):166 self.http = httpx.AsyncClient(base_url=stack.base + "/internal/v1", timeout=30,167 headers={"Authorization": f"Bearer {stack.worker_key}"})168 self.name, self.caps, self.worker_id = name, caps, ""169170 async def register(self):171 r = await self.http.post("/workers/register", json={"name": self.name, "capabilities": self.caps,172 "concurrency": 4})173 r.raise_for_status()174 self.worker_id = r.json()["worker_id"]175176 async def lease(self, n=1, wait: float = 10.0) -> list[dict]:177 t0 = asyncio.get_running_loop().time()178 while True:179 r = await self.http.post(f"/workers/{self.worker_id}/lease", json={"max_tasks": n})180 r.raise_for_status()181 if r.json()["tasks"] or asyncio.get_running_loop().time() - t0 > wait:182 return r.json()["tasks"]183 await asyncio.sleep(0.1)184185 async def complete(self, task: dict, result: dict, token: int | None = None) -> httpx.Response:186 return await self.http.post(f"/tasks/{task['task_id']}/complete", json={187 "worker_id": self.worker_id, "fencing_token": task["fencing_token"] if token is None else token,188 "result": result, "kind": task["kind"]})189190 @staticmethod191 def page(url: str, text: str = "fake page", links=(), nbytes: int = 100) -> dict:192 """A minimal successful page result, as a real worker would send it (no artifact)."""193 import hashlib194 return {"ok": True, "status": 200, "final_url": url, "bytes": nbytes, "pages": [{195 "engine": "http", "profile": "none", "url": url, "final_url": url, "status": 200, "title": "fake",196 "content_hash": hashlib.sha256(text.encode()).hexdigest(), "artifacts": [], "states": [], "text": text,197 "links": [{"url": u, "kind": "anchor", "text": ""} for u in links]}]}198199 async def heartbeat(self, task_ids=()) -> dict:200 r = await self.http.post(f"/workers/{self.worker_id}/heartbeat", json={"task_ids": list(task_ids)})201 r.raise_for_status()202 return r.json()203204 async def close(self):205 await self.http.aclose()206207208@pytest_asyncio.fixture209async def stack(tmp_path, monkeypatch):210 from server import start_fixture # tests/fixtures/site211 site = await start_fixture(port=free_port())212 port, hook_port = free_port(), free_port()213 monkeypatch.setenv("SPIDER_ENV", "test")214 monkeypatch.setenv("SPIDER_DATABASE_URL", DB)215 monkeypatch.setenv("SPIDER_DATA_DIR", str(tmp_path / "data"))216 monkeypatch.setenv("SPIDER_SECRET_FILE", str(tmp_path / "secret.key"))217 monkeypatch.setenv("SPIDER_TEST_ALLOW_HOSTS", f"127.0.0.1:{site.port},127.0.0.1:{hook_port}")218 monkeypatch.setenv("SPIDER_TEST_DELAY_MS", os.environ.get("SPIDER_TEST_DELAY_MS", "0"))219 monkeypatch.setenv("SPIDER_LEASE_SECONDS", "6")220 monkeypatch.setenv("SPIDER_COOKIE_SECURE", "0")221 try:222 conn = await asyncpg.connect(DB)223 except Exception as e: # noqa: BLE001224 pytest.skip(f"PostgreSQL test database not available: {e}")225 await conn.execute("drop schema public cascade; create schema public")226 await conn.close()227 from spider import auth228 from spider.config import Settings229 st = Stack()230 st.site = site231 st.settings = Settings()232 st.port, st.hook_port = port, hook_port233 await st.start_gateway()234 async with st.orch.pool.acquire() as c:235 tid = await c.fetchval("insert into tenants(name) values('test') returning id")236 st.tenant_id = str(tid)237 _, st.admin_key = await auth.create_key(c, tid, "admin", ["read", "write", "admin", "metrics"])238 _, st.worker_key = await auth.create_key(c, tid, "worker", ["worker"], kind="worker")239 st.client = httpx.AsyncClient(base_url=st.base, headers={"Authorization": f"Bearer {st.admin_key}"}, timeout=60)240 try:241 yield st242 finally:243 for w, task in list(st.workers):244 await st.stop_worker(w, task, hard=True)245 await w.close()246 await st.client.aclose()247 await st.stop_gateway()248 await site.close()249