SPB Git

Repository Public

test_watch_monitor.py 12.1 KB 247 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/integration/test_watch_monitor.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"""Watch: monitors, conditional requests, change classification, cooldown, noise selectors, diff, time machine.4243The fixture page /cond/changing has five variants (initial, text, price, availability, layout) cycled44with `stack.site.state.bump()`. The background maintenance loop is stopped so that every run is45driven by the test (`run-now` + `maint.tick()`); two tests then run ticks concurrently on purpose.46"""47import asyncio4849import pytest5051pytestmark = pytest.mark.pg52TERMINAL = ("partial", "succeeded", "failed", "cancelled", "blocked")535455async def db(stack, sql, *args):56    async with stack.orch.pool.acquire() as c:57        return await c.fetch(sql, *args)585960async def create_monitor(stack, path="/cond/changing", **kw) -> str:61    req = {"url": stack.url(path), "render": "http"} | kw.pop("request", {})62    body = {"name": "watch", "request": req, "interval_s": 3600, "watch": ["content", "layout"], "cooldown_s": 0} | kw63    r = await stack.client.post("/v1/monitor", json=body)64    assert r.status_code == 201, r.text65    return r.json()["id"]666768async def run_monitor(stack, sid, tick=None) -> dict:69    """Force one run and drive maintenance until that run is finished and compared. Returns the job row."""70    n0 = len(await db(stack, "select 1 from jobs where schedule_id=$1", sid))71    r = await stack.client.post(f"/v1/monitors/{sid}/run-now")72    assert r.status_code == 200, r.text73    for _ in range(400):74        await (tick or stack.maint.tick)()75        rows = await db(stack, "select * from jobs where schedule_id=$1 order by created_at", sid)76        assert len(rows) <= n0 + 1, "one run-now started more than one job"77        if len(rows) == n0 + 1 and all(j["status"] in TERMINAL and "compared" in j["stats"] for j in rows):78            return dict(rows[-1])79        await asyncio.sleep(0.05)80    raise AssertionError("monitor run did not finish")818283async def events(stack, sid) -> list[dict]:84    r = await stack.client.get("/v1/changes", params={"schedule_id": sid})85    return list(reversed(r.json()["items"]))  # oldest first868788@pytest.fixture89async def quiet(stack):90    await stack.maint.stop()  # no background tick: the test drives maintenance91    await stack.start_worker(concurrency=2)92    return stack939495async def test_each_variant_produces_the_right_change_kinds(quiet):96    stack = quiet97    sid = await create_monitor(stack)98    j = await run_monitor(stack, sid)99    assert j["status"] == "succeeded" and await events(stack, sid) == []  # first capture: nothing to compare100    # nothing changed: conditional request, 304, no event101    j = await run_monitor(stack, sid)102    last = [q for q in stack.site.state.requests if q.path == "/cond/changing"][-1]103    assert last.headers.get("If-None-Match") == '"changing-v0"' and last.status == 304104    assert (await db(stack, "select status from urls where job_id=$1", j["id"]))[0]["status"] == "not_modified"105    assert await events(stack, sid) == []106    expected = [("text", {"content"}), ("price", {"content", "price"}), ("availability", {"content", "availability"})]107    for i, (variant, kinds) in enumerate(expected, start=1):108        stack.site.state.bump()109        await run_monitor(stack, sid)110        ev = await events(stack, sid)111        assert len(ev) == i, f"variant {variant}: {len(ev)} events"112        assert set(ev[-1]["kinds"]) == kinds, (variant, ev[-1]["kinds"])113        assert ev[-1]["alerted"] is True and ev[-1]["url"] == stack.url("/cond/changing")114    ev = await events(stack, sid)115    assert ev[0]["summary"]["text"]["removed"] == ["The harbour is calm this morning."]116    assert ev[0]["summary"]["text"]["added"] == ["A north wind picked up before noon."]117    assert ev[0]["summary"]["layout"]["changed"] is False118    assert "120.00 CAD" in " ".join(ev[1]["summary"]["text"]["added"])119    assert "Out of stock" in " ".join(ev[2]["summary"]["text"]["added"])120    stack.site.state.bump()  # layout B: same sentences, another structure121    await run_monitor(stack, sid)122    ev = await events(stack, sid)123    assert len(ev) == 4 and "layout" in ev[3]["kinds"], ev[3]["kinds"]124    assert not {"price", "availability"} & set(ev[3]["kinds"]), ev[3]["kinds"]125    assert ev[3]["summary"]["layout"]["changed"] is True126    # each event links the two snapshots it compared, in order127    chain = [(e["snapshot_a"], e["snapshot_b"]) for e in ev]128    assert all(chain[i][1] == chain[i + 1][0] for i in range(3))129    # unchanged again: still no event130    await run_monitor(stack, sid)131    assert len(await events(stack, sid)) == 4132    assert stack.site.state.side_effects == []133134    # ---- time machine: history newest first, one snapshot per variant (the 304 runs stored nothing)135    hist = (await stack.client.get("/v1/snapshots", params={"url": stack.url("/cond/changing")})).json()["items"]136    assert len(hist) == 5137    times = [h["captured_at"] for h in hist]138    assert times == sorted(times, reverse=True)139    assert hist[0]["snapshot_id"] == chain[-1][1] and hist[-1]["snapshot_id"] == chain[0][0]140    assert len({h["content_hash"] for h in hist}) == 5141142    # ---- diff between the first and the last capture143    r = await stack.client.post("/v1/diff", json={"snapshot_a": hist[-1]["snapshot_id"],144                                                  "snapshot_b": hist[0]["snapshot_id"]})145    assert r.status_code == 200, r.text146    d = r.json()147    assert {"text", "layout", "fields", "visual", "kinds"} <= set(d)148    assert d["text"]["changed"] and "The harbour is calm this morning." in d["text"]["removed"]149    assert d["layout"]["changed"] and d["layout"]["similarity"] < 0.995150    assert {"content", "layout", "price", "availability"} <= set(d["kinds"])151    assert d["same_content_hash"] is False and d["captured_a"] < d["captured_b"]152    same = (await stack.client.post("/v1/diff", json={"snapshot_a": hist[0]["snapshot_id"],153                                                      "snapshot_b": hist[0]["snapshot_id"]})).json()154    assert same["kinds"] == [] and same["text"]["similarity"] == 1.0 and same["same_content_hash"] is True155    # noise selectors apply to the comparison, not to the stored evidence156    r = await stack.client.post("/v1/diff", json={"snapshot_a": hist[-1]["snapshot_id"], "snapshot_b": hist[-2]["snapshot_id"],157                                                  "ignore_selectors": ["#status-text"]})158    assert r.json()["kinds"] == []159    r = await stack.client.post("/v1/diff", json={"snapshot_a": hist[0]["snapshot_id"],160                                                  "snapshot_b": "00000000-0000-0000-0000-000000000000"})161    assert r.status_code == 404162163164async def test_fields_watch_reports_price_from_the_extracted_record(quiet):165    stack = quiet166    schema = {"type": "object", "properties": {"price": {"type": ["number", "null"]},167                                               "availability": {"type": ["string", "null"]}}}168    rules = {"price": {"css": "#price"}, "availability": {"css": "#availability"}}169    sid = await create_monitor(stack, watch=["fields"],170                               request={"extract": {"schema": schema, "rules": rules, "formats": ["markdown"]}})171    await run_monitor(stack, sid)172    stack.site.state.bump()  # text only: no field moved, nothing for a fields watch173    await run_monitor(stack, sid)174    assert await events(stack, sid) == []175    stack.site.state.bump()  # price 100 -> 120176    await run_monitor(stack, sid)177    (ev,) = await events(stack, sid)178    assert "price" in ev["kinds"] and ev["summary"]["fields"] == {"price": {"before": 100.0, "after": 120.0}}, ev179180181async def test_cooldown_suppresses_the_alert_but_records_the_event(quiet):182    stack = quiet183    sid = await create_monitor(stack, cooldown_s=3600)184    await run_monitor(stack, sid)185    for _ in range(3):186        stack.site.state.bump()187        await run_monitor(stack, sid)188    ev = await events(stack, sid)189    assert [e["alerted"] for e in ev] == [True, False, False], ev190    assert [set(e["kinds"]) for e in ev] == [{"content"}, {"content", "price"}, {"content", "availability"}]191    # once the cooldown is over the next change alerts again192    await db(stack, "update schedules set last_alert_at = now() - interval '2 hours' where id=$1", sid)193    stack.site.state.bump()194    await run_monitor(stack, sid)195    assert (await events(stack, sid))[-1]["alerted"] is True196197198async def test_ignore_selectors_suppress_a_noisy_node(quiet):199    stack = quiet200    sid = await create_monitor(stack, ignore_selectors=["#status-text"])201    await run_monitor(stack, sid)202    stack.site.state.bump()  # only #status-text changes203    j = await run_monitor(stack, sid)204    assert await events(stack, sid) == []205    assert len(await db(stack, "select 1 from snapshots where job_id=$1", j["id"])) == 1  # captured all the same206    stack.site.state.bump()  # the price is outside the ignored node207    await run_monitor(stack, sid)208    (ev,) = await events(stack, sid)209    assert set(ev["kinds"]) == {"content", "price"}210211212@pytest.mark.parametrize("path,header,value", [213    ("/cond/etag", "If-None-Match", '"fixture-etag-v1"'),214    ("/cond/lastmod", "If-Modified-Since", "Wed, 02 Dec 2026 12:00:00 GMT"),215])216async def test_second_monitor_run_is_conditional_and_recorded_not_modified(quiet, path, header, value):217    stack = quiet218    sid = await create_monitor(stack, path)219    j1 = await run_monitor(stack, sid)220    assert (await db(stack, "select status from urls where job_id=$1", j1["id"]))[0]["status"] == "fetched"221    for _ in range(2):  # the validator survives a 304 run222        j = await run_monitor(stack, sid)223        u = (await db(stack, "select status, http_status from urls where job_id=$1", j["id"]))[0]224        assert (u["status"], u["http_status"]) == ("not_modified", 304)225        assert j["status"] == "succeeded"226    reqs = [q for q in stack.site.state.requests if q.path == path]227    assert [q.status for q in reqs] == [200, 304, 304]228    assert header not in reqs[0].headers and reqs[1].headers[header] == value == reqs[2].headers[header]229    assert len(await db(stack, "select 1 from snapshots where url=$1", stack.url(path))) == 1230    assert await events(stack, sid) == []231232233async def test_concurrent_maintenance_ticks_start_one_run_and_record_one_event(quiet):234    """Two gateway processes tick at the same time: one job per due schedule, one event per change."""235    stack = quiet236237    async def both():238        await asyncio.gather(stack.maint.tick(), stack.maint.tick(), stack.maint.tick())239240    sid = await create_monitor(stack)241    await run_monitor(stack, sid, tick=both)242    for n in (1, 2):243        stack.site.state.bump()244        await run_monitor(stack, sid, tick=both)245        assert len(await events(stack, sid)) == n246    assert len(await db(stack, "select 1 from jobs where schedule_id=$1", sid)) == 3247
Files main
Menu

Theme