SPB Git

Repository Public

test_browser_capture.py 20.1 KB 381 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_capture.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"""Spatial capture engine on real browsers: geometry, tiles, mosaic, elements, sections, profiles."""42from __future__ import annotations4344import hashlib45import json46from pathlib import Path4748import pytest49import pytest_asyncio50from browser_testlib import UA_SUFFIX, pageserver, rgb51from PIL import Image5253from spider.browser import capture as capture_mod54from spider.contracts import CaptureOptions, RenderRequest5556pytestmark = [pytest.mark.browser, pytest.mark.asyncio(loop_scope="session")]5758HEADER, FOOTER, STICKY = pageserver.HEADER_RGB, pageserver.FOOTER_RGB, pageserver.STICKY_RGB596061def by_kind(result, kind):62    return [c for c in result.captures if c.kind == kind]636465def file_sha(path) -> str:66    return hashlib.sha256(Path(path).read_bytes()).hexdigest()676869def assert_tiles_cover(tiles, doc_w, doc_h):70    """Union of the tile rectangles = the document, without gaps."""71    rows = sorted({t.row for t in tiles})72    cols = sorted({t.col for t in tiles})73    assert len(tiles) == len(rows) * len(cols)74    grid = {(t.row, t.col): t for t in tiles}75    for r in rows:76        covered = 0.077        for c in cols:78            t = grid[(r, c)]79            assert t.css.x <= covered + 0.0180            covered = max(covered, t.css.x + t.css.w)81        assert covered >= doc_w - 0.0182    for c in cols:83        covered = 0.084        for r in rows:85            t = grid[(r, c)]86            assert t.css.y <= covered + 0.0187            covered = max(covered, t.css.y + t.css.h)88        assert covered >= doc_h - 0.0189    assert min(t.css.x for t in tiles) == 0 and min(t.css.y for t in tiles) == 0909192# ----------------------------------------------------------------------------------------- tall page93@pytest_asyncio.fixture(scope="module", loop_scope="session")94async def tall(pool, server, tmp_path_factory):95    req = RenderRequest(url=server.url("/gen/tall?h=20000"), out_dir=str(tmp_path_factory.mktemp("tall")),96                        capture=CaptureOptions(tiles=True, tile_overlap=0, full_page=True, webp_derivatives=True),97                        user_agent_suffix=UA_SUFFIX, timeout_s=90)98    return await pool.render(req)99100101async def test_tall_page_result(tall):102    assert tall.ok and tall.status == 200 and tall.error_class is None103    assert (tall.doc_width, tall.doc_height) == (1280, 20000) and tall.dpr == 1104    assert tall.engine == "chromium" and tall.engine_version105    assert "full_page_limit" not in tall.budgets_hit106    print("timings_ms", tall.metrics["timings_ms"], "tiles", tall.metrics["tiles"]["capture_ms"],107          "mosaic", tall.metrics["mosaic"]["build_ms"])108109110async def test_tall_tiles_geometry(tall):111    tiles = by_kind(tall, "tile")112    assert len(tiles) == 25113    assert_tiles_cover(tiles, 1280, 20000)114    for i, t in enumerate(tiles):115        assert (t.row, t.col) == (i, 0)116        assert (t.css.x, t.css.y, t.css.w, t.css.h) == (0, i * 800, 1280, 800)117        assert (t.width, t.height) == (1280, 800) and t.dpr == 1          # physical = css × dpr118        assert (t.scroll_x, t.scroll_y) == (0, i * 800)                    # captured by real scrolling119        assert (t.doc_width, t.doc_height) == (1280, 20000)120        assert t.mime == "image/png" and t.profile == "desktop" and t.engine.startswith("chromium/")121        assert t.captured_at.endswith("Z")122    info = tall.metrics["tiles"]123    assert info["rows"] == 25 and info["cols"] == 1 and info["tile_css"] == [1280, 800]124    assert info["clamped_to_viewport"] is True          # 1600 px requested, viewport is 800 px high125126127async def test_tall_raw_tiles_keep_fixed_layers(tall):128    """Raw evidence is never altered: the fixed header and footer are in every raw tile."""129    for t in by_kind(tall, "tile"):130        assert rgb(t.path, 640, 30) == HEADER, t.path131        assert rgb(t.path, 640, 780) == FOOTER, t.path132    # marker bands at their known document offsets, read through the tile rectangles133    for i in range(20):134        y = 1000 * i + 350135        t = next(t for t in by_kind(tall, "tile") if t.css.y + 60 <= y < t.css.y + t.css.h - 40)136        assert rgb(t.path, 640, y - t.css.y) == pageserver.band_rgb(i)137138139async def test_tall_mosaic_alignment_and_deduplication(tall):140    (mosaic,) = by_kind(tall, "mosaic")141    assert (mosaic.width, mosaic.height) == (1280, 20000)142    assert (mosaic.css.x, mosaic.css.y, mosaic.css.w, mosaic.css.h) == (0, 0, 1280, 20000)143    with Image.open(mosaic.path) as im:144        im = im.convert("RGB")145        px = im.getpixel146        assert im.size == (1280, 20000)147        for i in range(20):                                   # every marker band at its document offset148            top = 1000 * i + 300149            assert px((640, top + 50)) == pageserver.band_rgb(i)150            assert px((640, top + 1)) == pageserver.band_rgb(i) and px((640, top + 98)) == pageserver.band_rgb(i)151            if top - 2 > 60:152                assert px((640, top - 2)) == (255, 255, 255) and px((640, top + 102)) == (255, 255, 255)153        assert px((640, 30)) == HEADER                         # fixed header: once, at the top154        assert px((640, 19980)) == FOOTER                      # fixed footer: once, at the bottom155        for k in range(1, 25):156            assert px((640, k * 800 + 30)) != HEADER, k157            assert px((640, k * 800 - 20)) != FOOTER, k158        header_rows = sum(1 for y in range(0, 20000, 10) if px((900, y)) == HEADER)159        footer_rows = sum(1 for y in range(0, 20000, 10) if px((900, y)) == FOOTER)160        assert header_rows == 6 and footer_rows == 4           # 60 px and 40 px, sampled every 10 px161        assert px((150, 5015)) == STICKY                       # sticky block in its in-flow position only162        sticky_rows = sum(1 for y in range(0, 20000, 5) if px((150, y)) == STICKY)163        assert sticky_rows == 6164    report = tall.metrics["mosaic"]165    dedup = {d["selector"]: d for d in report["deduplicated"]}166    assert dedup["#fixed-header"]["kept_tile"] == {"row": 0, "col": 0} and dedup["#fixed-header"]["seen_in_tiles"] == 25167    assert dedup["#fixed-footer"]["kept_tile"] == {"row": 24, "col": 0}168    assert dedup["#sticky"]["kept"] == "in_flow_position" and dedup["#sticky"]["kept_tile"] is None169    assert report["hidden_pass_tiles"] == 25 and mosaic.selector is None170171172async def test_tall_full_page_and_viewport(tall):173    (full,) = by_kind(tall, "full_page")174    assert (full.width, full.height) == (1280, 20000) and (full.css.w, full.css.h) == (1280, 20000)175    assert rgb(full.path, 640, 30) == HEADER and rgb(full.path, 640, 9350) == pageserver.band_rgb(9)176    (view,) = by_kind(tall, "viewport")177    assert (view.width, view.height) == (1280, 800) and (view.css.x, view.css.y, view.css.w, view.css.h) == (0, 0, 1280, 800)178    assert rgb(view.path, 640, 350) == pageserver.band_rgb(0)179180181async def test_sha256_matches_files_and_derivatives(tall):182    assert tall.captures183    pngs = {}184    for c in tall.captures:185        assert Path(c.path).is_file()186        assert c.sha256 == file_sha(c.path), c.path187        with Image.open(c.path) as im:188            assert im.size == (c.width, c.height)189            assert im.format == ("WEBP" if c.kind == "derivative" else "PNG")190        if c.kind != "derivative":191            pngs.setdefault(c.sha256, []).append(c)     # the viewport and the first tile are the same pixels192    derived = by_kind(tall, "derivative")193    assert len(derived) == 26                               # viewport + 25 tiles194    for dv in derived:195        sources = pngs[dv.derived_from]196        assert dv.mime == "image/webp" and (dv.width, dv.height) == (sources[0].width, sources[0].height)197        assert any(dv.css == src.css and dv.row == src.row for src in sources)198    skipped = {s["path"] for s in tall.metrics["derivatives"]["skipped"]}199    assert skipped == {"full_page.png", "mosaic.png"}       # taller than the WebP limit: reported, not hidden200201202async def test_manifest_lists_every_file(tall):203    out = Path(tall.captures[0].path).parent204    manifest = json.loads((out / "manifest.json").read_text())205    assert manifest["spider_engine"] == "spider-browser/0.1" and manifest["engine"] == "chromium"206    assert manifest["browser_version"] == tall.engine_version207    listed = {a["path"]: a for a in manifest["artifacts"]}208    on_disk = {str(p.relative_to(out)) for p in out.rglob("*") if p.is_file() and p.name != "manifest.json"}209    assert on_disk == set(listed)210    for rel, a in listed.items():211        assert a["sha256"] == file_sha(out / rel) and a["bytes"] == (out / rel).stat().st_size and a["mime"]212    for c in tall.captures:213        a = listed[str(Path(c.path).relative_to(out))]214        assert a["kind"] == c.kind and a["width"] == c.width and a["css"] == c.css.model_dump() and a["dpr"] == c.dpr215        assert a["captured_at"] and a["spider_engine"] == "spider-browser/0.1"216    sources = [a for a in manifest["artifacts"] if a.get("role") == "mosaic_source_layers_hidden"]217    assert len(sources) == 25218    assert {"html", "aria", "blocks", "text", "replay"} <= {a["kind"] for a in manifest["artifacts"]}219220221# ------------------------------------------------------------------------------ overlap, both engines222@pytest.mark.parametrize("engine", ["chromium", "webkit"])223async def test_tiles_with_overlap_viewport_and_full_page(pool, make_request, engine):224    res = await pool.render(make_request("/gen/tall?h=3000", engine=engine, tiles=True, tile_overlap=120, full_page=True))225    assert res.ok, res.error_detail226    assert res.engine == engine and (res.doc_width, res.doc_height) == (1280, 3000)227    tiles = by_kind(res, "tile")228    assert [t.css.y for t in tiles] == [0, 680, 1360, 2040, 2200]           # step = height - overlap, last flush229    assert_tiles_cover(tiles, 1280, 3000)230    for t in tiles:231        assert (t.width, t.height) == (1280, 800) and t.scroll_y == t.css.y232        assert rgb(t.path, 640, 30) == HEADER and rgb(t.path, 640, 780) == FOOTER233    (view,) = by_kind(res, "viewport")234    (full,) = by_kind(res, "full_page")235    (mosaic,) = by_kind(res, "mosaic")236    assert (view.width, view.height) == (1280, 800)237    assert (full.width, full.height) == (1280, 3000) == (mosaic.width, mosaic.height)238    for path in (full.path, mosaic.path):239        for i in range(3):240            assert rgb(path, 640, 1000 * i + 350) == pageserver.band_rgb(i), (engine, path, i)241        assert rgb(path, 640, 30) == HEADER242    for y in (680 + 30, 1360 + 30, 2040 + 30, 2200 + 30):243        assert rgb(mosaic.path, 640, y) != HEADER244    assert rgb(mosaic.path, 640, 2980) == FOOTER245    for c in res.captures:246        assert c.sha256 == file_sha(c.path) and c.engine.startswith(engine + "/")247248249async def test_full_page_limit_falls_back_to_mosaic(pool, make_request, monkeypatch):250    """Above the engine's safe size the native full page is skipped — never silently truncated."""251    monkeypatch.setitem(capture_mod.FULL_PAGE_LIMITS, "chromium", {"max_dim": 2000, "max_pixels": 10**9})252    res = await pool.render(make_request("/gen/tall?h=3000&fixed=0", full_page=True))253    assert res.ok and "full_page_limit" in res.budgets_hit254    assert by_kind(res, "full_page") == []255    (mosaic,) = by_kind(res, "mosaic")256    assert (mosaic.width, mosaic.height) == (1280, 3000) and len(by_kind(res, "tile")) == 5257    assert rgb(mosaic.path, 640, 2350) == pageserver.band_rgb(2)258    assert res.metrics["full_page"]["physical_px"] == [1280, 3000]259260261async def test_engine_limits_are_declared():262    for engine in ("chromium", "webkit"):263        assert capture_mod.FULL_PAGE_LIMITS[engine]["max_dim"] >= 16_384264265266# ---------------------------------------------------------------------------------------- wide page267async def test_horizontal_tiles_on_a_wide_page(pool, make_request):268    res = await pool.render(make_request("/gen/wide?w=3000&h=1200", tiles=True, tile_overlap=0))269    assert res.ok and (res.doc_width, res.doc_height) == (3000, 1200)270    tiles = by_kind(res, "tile")271    assert res.metrics["tiles"]["horizontal"] is True and res.metrics["tiles"]["cols"] == 3272    assert sorted({t.css.x for t in tiles}) == [0, 1280, 1720] and sorted({t.css.y for t in tiles}) == [0, 400]273    assert_tiles_cover(tiles, 3000, 1200)274    for t in tiles:275        assert (t.width, t.height) == (1280, 800) and (t.scroll_x, t.scroll_y) == (t.css.x, t.css.y)276    (mosaic,) = by_kind(res, "mosaic")277    assert (mosaic.width, mosaic.height) == (3000, 1200)278    for i in range(6):279        assert rgb(mosaic.path, 500 * i + 150, 250) == pageserver.band_rgb(i)280        assert rgb(mosaic.path, 500 * i + 50, 250) == (255, 255, 255)281        t = next(t for t in tiles if t.css.x <= 500 * i + 150 < t.css.x + 1280 and t.css.y == 0)282        assert rgb(t.path, 500 * i + 150 - t.css.x, 250) == pageserver.band_rgb(i)283284285async def test_configured_tile_size_and_device_scale_factor(pool, make_request):286    res = await pool.render(make_request("/gen/tall?h=2000&fixed=0", tiles=True, tile_width=640, tile_height=400,287                                         tile_overlap=40, device_scale_factor=2))288    assert res.ok and res.dpr == 2289    tiles = by_kind(res, "tile")290    assert res.metrics["tiles"]["tile_css"] == [640, 400] and res.metrics["tiles"]["clamped_to_viewport"] is False291    assert sorted({t.css.x for t in tiles}) == [0, 600, 640] and tiles[1].css.y - tiles[0].css.y in (0, 360)292    assert sorted({t.css.y for t in tiles}) == [0, 360, 720, 1080, 1440, 1600]293    assert_tiles_cover(tiles, 1280, 2000)294    for t in tiles:295        assert (t.css.w, t.css.h) == (640, 400) and (t.width, t.height) == (1280, 800) and t.dpr == 2296    (mosaic,) = by_kind(res, "mosaic")297    assert (mosaic.width, mosaic.height) == (2560, 4000)298    assert rgb(mosaic.path, 1280, 2 * 1350) == pageserver.band_rgb(1)299    assert rgb(mosaic.path, 2500, 2 * 399) == pageserver.band_rgb(0) and rgb(mosaic.path, 2500, 2 * 401) == (255, 255, 255)300301302async def test_pdf_on_chromium_and_reported_unsupported_on_webkit(pool, make_request):303    res = await pool.render(make_request("/p/basic.html", pdf=True))304    (pdf,) = by_kind(res, "pdf")305    assert pdf.mime == "application/pdf" and Path(pdf.path).read_bytes().startswith(b"%PDF-")306    assert pdf.sha256 == file_sha(pdf.path) and "pdf_unsupported" not in res.budgets_hit307    res = await pool.render(make_request("/p/basic.html", engine="webkit", pdf=True))308    assert res.ok and by_kind(res, "pdf") == [] and "pdf_unsupported" in res.budgets_hit309310311# ----------------------------------------------------------------------------------------- profiles312@pytest.mark.parametrize(("profile", "css", "dpr"), [("desktop", (1280, 800), 1), ("mobile", (390, 844), 3),313                                                      ("tablet", (820, 1180), 2)])314async def test_profiles_give_their_viewport_and_pixel_ratio(pool, make_request, server, profile, css, dpr):315    server.clear()316    res = await pool.render(make_request("/gen/tall?h=3000&fixed=0", profile=profile, tiles=True, tile_overlap=0))317    assert res.ok and res.profile == profile and res.dpr == dpr318    (view,) = by_kind(res, "viewport")319    assert (view.css.w, view.css.h) == css and (view.width, view.height) == (css[0] * dpr, css[1] * dpr)320    assert view.dpr == dpr and view.profile == profile and res.doc_width == css[0]321    for t in by_kind(res, "tile"):322        assert (t.width, t.height) == (round(t.css.w * dpr), round(t.css.h * dpr))323    assert rgb(view.path, 10 * dpr, 350 * dpr) == pageserver.band_rgb(0)324    assert res.metrics["viewport"] == {"width": css[0], "height": css[1]}325    # transparent identity: the browser's own user agent plus the declared suffix, nothing else326    ua = res.metrics["user_agent"]327    assert ua.endswith(" " + UA_SUFFIX) and ua.startswith("Mozilla/5.0")328    assert {h["ua"] for h in server.hits("/gen/tall")} == {ua}329330331@pytest.mark.parametrize("engine", ["chromium", "webkit"])332async def test_user_agent_is_the_real_one_plus_suffix(pool, make_request, open_page, engine):333    page = await open_page("/p/basic.html", engine)334    real = await page.evaluate("navigator.userAgent")           # default context: untouched browser UA335    res = await pool.render(make_request("/p/basic.html", engine=engine))336    assert res.metrics["user_agent"] == f"{real} {UA_SUFFIX}"337    assert await page.evaluate("navigator.webdriver") is True    # automation is not hidden338339340# ----------------------------------------------------------------------------- elements and sections341async def test_element_and_section_captures_match_dom_rects(pool, make_request, open_page):342    res = await pool.render(make_request("/p/basic.html", elements=["#price", ".card", "#specs", "#missing", "p >"],343                                         sections=True))344    assert res.ok345    page = await open_page("/p/basic.html")346    measure = """(sel) => [...document.querySelectorAll(sel)].map((el) => { const r = el.getBoundingClientRect();347        return {x: r.left + scrollX, y: r.top + scrollY, w: r.width, h: r.height}; })"""348349    def close(rect, m):350        """The capture covers the DOM box, enlarged to whole CSS pixels at most."""351        return (m["x"] - 1 < rect.x <= m["x"] + 0.01 and m["y"] - 1 < rect.y <= m["y"] + 0.01352                and m["x"] + m["w"] - 0.01 <= rect.x + rect.w < m["x"] + m["w"] + 1353                and m["y"] + m["h"] - 0.01 <= rect.y + rect.h < m["y"] + m["h"] + 1)354355    elements = by_kind(res, "element")356    assert [e.selector for e in elements] == ["#price", ".card", ".card", ".card", "#specs"]357    for sel in ("#price", ".card", "#specs"):358        expected = await page.evaluate(measure, sel)359        got = [e for e in elements if e.selector == sel]360        assert len(got) == len(expected)361        for e, m in zip(got, expected, strict=True):362            assert close(e.css, m), (sel, e.css, m)363            assert (e.width, e.height) == (e.css.w, e.css.h)                # physical = css × dpr (dpr 1)364            assert e.sha256 == file_sha(e.path)365    price = next(e for e in elements if e.selector == "#price")366    assert price.width == 200 and price.height in (50, 51) and rgb(price.path, 100, 25) == (10, 200, 10)367    assert [c.row for c in elements if c.selector == ".card"] == [0, 1, 2]368    info = res.metrics["elements"]369    assert info["matches"]["#missing"] == 0 and any("invalid_selector" in s["reason"] for s in info["skipped"])370371    sections = by_kind(res, "section")372    tags = [s.selector for s in sections]373    for expected_sel in ("header", "nav", "main", "footer", "#cards", "#specs", "figure"):374        hits = [s for s in sections if s.selector == expected_sel or s.selector.endswith(" > " + expected_sel)375                or s.selector.split(" > ")[-1].startswith(expected_sel)]376        assert hits, (expected_sel, tags)377        m = (await page.evaluate(measure, hits[0].selector))[0]378        assert close(hits[0].css, m), (expected_sel, hits[0].css, m)379        assert (hits[0].width, hits[0].height) == (hits[0].css.w, hits[0].css.h)380    assert res.metrics["sections"]["captured"] == len(sections) >= 7381
Files main
Menu

Theme