SPB Git

Repository Public

test_browser_render.py 11.3 KB 207 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/unit/browser/test_browser_render.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"""Whole renders on real browsers: snapshot, links, signals, dynamic content, bounded scrolling."""42from __future__ import annotations4344import json45from pathlib import Path4647import pytest4849from spider.browser.snapshot import serialize_dom5051pytestmark = [pytest.mark.browser, pytest.mark.asyncio(loop_scope="session")]525354def link_map(result):55    return {(link.kind, link.url.split("/", 3)[3]) for link in result.links}565758@pytest.mark.parametrize("engine", ["chromium", "webkit"])59async def test_basic_render(pool, make_request, server, engine, open_page):60    server.clear()61    res = await pool.render(make_request("/p/basic.html", engine=engine, full_page=True))62    assert res.ok and res.status == 200 and res.error_class is None and res.refusal is None63    assert res.engine == engine and res.engine_version and res.title == "Basic page"64    assert res.final_url == server.url("/p/basic.html") and res.bytes > 100065    assert "Basic page heading" in res.text and "CARD-THREE" in res.text and "FIGURE-CAPTION" in res.text66    kinds = link_map(res)67    assert {("nav", "p/about.html"), ("nav", "p/contact.html"), ("anchor", "p/inline-target.html"),68            ("pagination", "p/basic.html?page=2"), ("pagination", "p/basic.html?page=3"),69            ("anchor", "p/legal.html"), ("canonical", "p/basic.html"), ("hreflang", "p/basic-fr.html")} <= kinds70    assert not any("mailto" in link.url or "javascript" in link.url or "#intro" in link.url for link in res.links)71    assert {c.kind for c in res.captures} == {"viewport", "full_page"}72    # stored artifacts73    html = Path(res.html_path).read_text()74    assert "<script>" in html and "Basic page heading" in html            # scripts are kept in the evidence75    aria = Path(res.aria_path).read_text()76    assert "heading" in aria and "Basic page heading" in aria and "link" in aria77    blocks = json.loads(Path(res.metrics["blocks"]["path"]).read_text())78    price = next(b for b in blocks["blocks"] if b["text"] == "PRICE 1 234 $")79    page = await open_page("/p/basic.html", engine)80    m = await page.evaluate("""() => { const r = document.querySelector('#price').getBoundingClientRect();81        return {x: r.left + scrollX, y: r.top + scrollY, w: r.width, h: r.height}; }""")82    assert price["selector"] == "#price" and price["tag"] == "div" and price["font_size"] == 1683    assert all(abs(price["rect"][k] - m[k]) < 0.02 for k in "xywh")84    intro = next(b for b in blocks["blocks"] if b["selector"] == "#intro")85    assert intro["text"] == "Intro paragraph with bold words and a inline link." and intro["role"] == "paragraph"86    heading = next(b for b in blocks["blocks"] if b["tag"] == "h1")87    assert heading["role"] == "heading" and heading["font_size"] == 3288    replay = Path(res.metrics["replay_path"]).read_text()89    assert "<script" not in replay and "Content-Security-Policy" in replay and "Basic page heading" in replay90    # metrics and signals91    assert res.metrics["stability"]["stable"] is True and res.metrics["load"]["navigation"]["dom_content_loaded_ms"] > 092    assert res.signals["spa"] is False and res.signals["shadow_dom"] is False and res.signals["iframes"] == []93    assert res.metrics["network"]["requests"] >= 1 and res.metrics["timings_ms"]["total"] > 094    assert server.non_get() == []959697async def test_console_and_network_logs_are_redacted(pool, make_request):98    res = await pool.render(make_request("/p/basic.html"))99    text = json.dumps(res.console)100    assert "basic ready" in text and "REDACTED" in text101    assert "abc123secret" not in text and "SHOULDNOTAPPEAR" not in text and "q=ok" in text102    res = await pool.render(make_request("/p/post-on-load.html"))103    errors = json.dumps(res.network_errors)104    assert "token=REDACTED" in errors and "SECRET123" not in errors and "x=1" in errors105    assert any(e.get("reason") == "http_404" for e in res.network_errors)106    assert all(len(v) <= 500 for e in res.network_errors + res.console for v in e.values() if isinstance(v, str))107108109async def test_neutralised_serialisation(open_page):110    page = await open_page("/p/danger.html")111    raw = await serialize_dom(page)112    clean = await serialize_dom(page, neutralised=True)113    assert "<script>" in raw["html"] and "onclick=" in raw["html"]114    assert "<script" not in clean["html"] and "onclick" not in clean["html"] and "Buy now" in clean["html"]115    assert raw["title"] == "Danger" and raw["truncated"] is False116117118async def test_lazy_loading_is_triggered_by_the_scroll_pass(pool, make_request, server):119    server.clear()120    res = await pool.render(make_request("/p/lazy.html"))121    assert res.ok and res.signals["lazy_loading"] is True122    assert "LAZY-TEXT-ONE" in res.text and "LAZY-TEXT-TWO" in res.text123    for name in ("10-20-30", "40-50-60", "70-80-90", "100-110-120"):124        assert len(server.hits(f"/img/{name}.png")) == 1, name125    scroll = res.metrics["scroll"]126    assert scroll["images_loaded_after"] == 4 > scroll["images_loaded_before"] and scroll["intersection_hits"] >= 4127    assert scroll["steps"] >= 9 and res.signals["infinite_scroll"] is False128    html = Path(res.html_path).read_text()129    assert 'src="/img/70-80-90.png"' in html and "LAZY-TEXT-TWO" in html130131132async def test_infinite_scroll_is_bounded(pool, make_request, server):133    server.clear()134    res = await pool.render(make_request("/p/infinite.html"))135    assert res.ok and "infinite_scroll" in res.budgets_hit and res.signals["infinite_scroll"] is True136    assert res.metrics["scroll"]["bottom_growths"] == 8 and res.metrics["scroll"]["stopped"] == "infinite_scroll"137    pages = len(server.hits("/api/items"))138    assert 9 <= pages <= 11, pages                       # first load + 8 growths (+ at most a pending one)139    assert "ITEM-1-0" in res.text and "ITEM-9-9" in res.text and "ITEM-13-0" not in res.text140    assert res.doc_height >= 9 * 1200141142143async def test_hydration_is_waited_for(pool, make_request):144    res = await pool.render(make_request("/p/hydrate.html"))145    assert res.ok and res.signals["hydration"] is True and res.signals["stable"] is True146    assert "HYDRATED-TITLE" in res.text and "ROW-C" in res.text and "FINAL-TEXT-AFTER-HYDRATION" in res.text147    assert "Loading" not in res.text148    assert "FINAL-TEXT-AFTER-HYDRATION" in Path(res.html_path).read_text()149    assert res.metrics["stability"]["mutations"] > 0 and res.metrics["stability"]["waited_ms"] >= 800150    assert res.signals["spa"] is True                      # client-rendered root container151152153async def test_shadow_dom_and_same_origin_iframe(pool, make_request, server):154    res = await pool.render(make_request("/p/shadow.html"))155    assert res.ok and res.signals["shadow_dom"] is True and res.metrics["page"]["shadow_roots"] == 2156    for text in ("LIGHT-TEXT", "SHADOW-TEXT", "NESTED-SHADOW-TEXT", "IFRAME-TEXT"):157        assert text in res.text, text158    kinds = link_map(res)159    assert {("anchor", "p/shadow-target.html"), ("anchor", "p/nested-shadow-target.html"),160            ("anchor", "p/frame-target.html"), ("iframe", "p/frame-inner.html")} <= kinds161    assert res.signals["iframes"] == [{"src": server.url("/p/frame-inner.html"), "same_origin": True, "w": 404,162                                       "h": 154, "visible": True}]163    html = Path(res.html_path).read_text()164    assert html.count('<template shadowrootmode="open">') == 2 and "NESTED-SHADOW-TEXT" in html165    assert 'data-spider-frame="0"' in html and "IFRAME-TEXT" not in html166    (frame,) = res.metrics["frames"]167    assert frame["url"] == server.url("/p/frame-inner.html") and "IFRAME-TEXT" in Path(frame["path"]).read_text()168    blocks = json.loads(Path(res.metrics["blocks"]["path"]).read_text())["blocks"]169    shadow = next(b for b in blocks if b["text"] == "SHADOW-TEXT")170    assert shadow["selector"] == "#host >> p" and shadow["rect"]["w"] > 0171    inner = next(b for b in blocks if b["text"] == "IFRAME-TEXT")172    assert "|frame|" in inner["selector"] and inner["rect"]["y"] > shadow["rect"]["y"]173174175async def test_spa_routes_are_observed(pool, make_request, server):176    res = await pool.render(make_request("/p/spa.html"))177    assert res.ok and res.signals["spa"] is True and res.metrics["page"]["history_calls"] == 2178    assert res.final_url == server.url("/p/spa/dashboard?tab=1")179    routes = {r.split("/", 3)[3] for r in res.observed_routes}180    assert {"p/spa/home", "p/spa/dashboard?tab=1", "p/spa/about", "p/spa/products/42",181            "p/spa/dashboard?tab=1#/settings"} <= routes182    kinds = link_map(res)183    assert ("observed_route", "p/spa/about") in kinds and ("observed_route", "p/spa/home") in kinds184    assert ("nav", "p/spa/real-link") in kinds185    assert "SPA-VIEW /p/spa/dashboard" in res.text186187188async def test_virtualised_list_windows_and_row_union(pool, make_request):189    res = await pool.render(make_request("/p/virtual.html"))190    assert res.ok and res.signals["virtualized"] is True191    (report,) = res.metrics["virtualized"]192    assert report["selector"] == "#box" and report["complete"] is True and report["dom_rows"] == 16193    assert report["row_count"] == 200 and report["rows"][0] == "VROW-0" and report["rows"][-1] == "VROW-199"194    windows = [c for c in res.captures if c.kind == "element" and c.selector == "#box"]195    assert len(windows) == report["windows"] >= 15196    assert [w.row for w in windows] == list(range(len(windows)))197    assert all(w.width == 502 and w.height in (402, 403) and (w.css.w, w.css.h) == (w.width, w.height) for w in windows)198    assert "VROW-199" not in res.text                       # the DOM never holds every row at once199200201async def test_cookie_banner_is_evidence_not_clicked(pool, make_request, server):202    server.clear()203    res = await pool.render(make_request("/p/danger.html", interactive_states=False))204    assert res.ok and "We use cookies" in res.text205    assert server.non_get() == [] and server.hits("/api/side-effect") == []206    assert res.states == [] and res.skipped_actions == []207
Files main
Menu

Theme