SPB Git

Repository Public

test_browser_helpers.py 11.4 KB 228 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_helpers.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"""Pure helpers: refusal detection, redaction, tile geometry, mosaic planning, perceptual hash."""42from __future__ import annotations4344import itertools4546import pytest47from PIL import Image4849from spider.browser import imaging50from spider.browser.capture import axis_positions51from spider.browser.redact import CappedLog, redact_text, redact_url52from spider.browser.refusal import detect_refusal53from spider.browser.render import classify_error, status_error_class54from spider.browser.states import new_text5556LONG = "Lorem ipsum dolor sit amet. " * 80575859@pytest.mark.parametrize(("facts", "kind"), [60    ({"status": 403, "text": "Forbidden"}, "access_denied"),61    ({"status": 401, "text": LONG}, "access_denied"),62    ({"status": 407, "text": ""}, "access_denied"),63    ({"status": 451, "text": LONG}, "access_denied"),64    ({"status": 200, "title": "Just a moment...", "text": "Checking your browser before accessing"}, "captcha"),65    ({"status": 200, "text": "Vérifiez que vous êtes humain"}, "captcha"),66    ({"status": 403, "text": "Please verify you are human"}, "captcha"),67    ({"status": 200, "text": "Access denied. You don't have permission."}, "access_denied"),68    ({"status": 200, "text": "Accès refusé"}, "access_denied"),69    ({"status": 200, "text": "short", "frames": [{"src": "https://www.google.com/recaptcha/api2/bframe?k=1",70                                                  "visible": True, "w": 400, "h": 580}]}, "captcha"),71    ({"status": 200, "text": LONG, "frames": [{"src": "https://geo.captcha-delivery.com/captcha/?x=1",72                                               "visible": True, "w": 1280, "h": 800}]}, "captcha"),73    ({"status": 200, "text": "x", "frames": [{"src": "https://challenges.cloudflare.com/turnstile/v0/x",74                                              "visible": True, "w": 300, "h": 65}]}, "captcha"),75    ({"status": 200, "text": LONG, "requested_url": "https://s.example/account/orders",76      "final_url": "https://s.example/login?next=%2Faccount"}, "login_wall"),77    ({"status": 200, "text": LONG, "requested_url": "https://s.example/a", "final_url": "https://s.example/connexion"},78     "login_wall"),79    ({"status": 200, "text": "Members only. Please sign in.", "password_fields": 1}, "login_wall"),80    ({"status": 200, "text": "", "password_fields": 1}, "login_wall"),81    ({"status": 200, "text": LONG + " Subscribe to continue reading", "overlay": True}, "paywall"),82    ({"status": 200, "text": "Abonnez-vous pour lire la suite " + LONG, "paywall_hint": True}, "paywall"),83    ({"status": 200, "text": LONG + " Cet article est réservé aux abonnés", "overlay": True}, "paywall"),84])85def test_refusals(facts, kind):86    got = detect_refusal(facts)87    assert got is not None and got[0] == kind, got88    assert got[1]899091@pytest.mark.parametrize("facts", [92    {"status": 200, "text": LONG},93    # reCAPTCHA widget on a contact form94    {"status": 200, "text": "Contact us", "form_fields": 3,95     "frames": [{"src": "https://www.google.com/recaptcha/api2/anchor?k=1", "visible": True, "w": 304, "h": 78}]},96    {"status": 200, "text": LONG, "frames": [{"src": "https://www.google.com/recaptcha/api2/anchor", "visible": True,97                                              "w": 304, "h": 78}]},98    # invisible badge / hidden frame99    {"status": 200, "text": "Hi", "frames": [{"src": "https://www.google.com/recaptcha/api2/bframe", "visible": False}]},100    # the login page itself was requested101    {"status": 200, "text": "Sign in", "password_fields": 1, "requested_url": "https://s.example/login",102     "final_url": "https://s.example/login"},103    # paywall words without any overlay: an article about paywalls104    {"status": 200, "text": LONG + " Subscribe to continue reading"},105    # a long page with a login box in the header106    {"status": 200, "text": LONG, "password_fields": 1},107    {"status": 404, "text": "Not found"},108    {"status": 200, "text": "Contact form protected by captcha", "form_fields": 3},109])110def test_not_refusals(facts):111    assert detect_refusal(facts) is None112113114def test_redact_url():115    u = redact_url("https://user:pw77@h.example/p?token=abc&q=hello%20x&api_key=K1&SessionId=9&sig=zz&page=2#access_token=tk55&x=1")116    assert "abc" not in u and "K1" not in u and "pw77" not in u and "zz" not in u and "tk55" not in u and "=9" not in u117    assert "q=hello%20x" in u and "page=2" in u and u.startswith("https://REDACTED@h.example/p?")118    assert redact_url("data:text/html;base64," + "A" * 5000) == "data:[5022 chars]"119    assert len(redact_url("https://h.example/" + "a" * 2000)) <= 500120121122def test_redact_text():123    s = redact_text("fail Authorization: Bearer abc.def.ghi and\nCookie: sid=1234; other=5\nat "124                    "https://h.example/x?password=hunter2&ok=1 token=xyz987 {\"apiKey\": \"sk-12345\"} "125                    "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcDEF123456")126    for secret in ("abc.def.ghi", "1234;", "hunter2", "xyz987", "sk-12345", "eyJhbGci"):127        assert secret not in s, s128    assert "ok=1" in s and "REDACTED" in s129    assert len(redact_text("x" * 5000)) == 500130131132def test_capped_log():133    log = CappedLog(max_entries=3)134    for i in range(5):135        log.add(url=f"https://h.example/?token=t{i}", text="y" * 900, n=i, skip=None)136    assert len(log.entries) == 3 and log.dropped == 2137    assert all("token=REDACTED" in e["url"] and len(e["text"]) == 500 and "skip" not in e for e in log.entries)138139140@pytest.mark.parametrize(("total", "size", "overlap", "expected"), [141    (800, 800, 120, [0.0]),142    (500, 800, 120, [0.0]),143    (1600, 800, 0, [0.0, 800.0]),144    (2000, 800, 0, [0.0, 800.0, 1200.0]),145    (2000, 800, 120, [0.0, 680.0, 1200.0]),146    (20000, 800, 0, [float(i * 800) for i in range(25)]),147])148def test_axis_positions(total, size, overlap, expected):149    got = axis_positions(total, size, overlap)150    assert got == expected151    assert got[0] == 0 and got[-1] + size >= total152    assert all(b - a <= size - overlap + 1e-6 for a, b in itertools.pairwise(got))153154155def test_axis_positions_cover_everything():156    for total in (801, 1234, 5000, 19999, 20000):157        for overlap in (0, 50, 120, 400):158            pos = axis_positions(total, 800, overlap)159            covered = 0.0160            for p in pos:161                assert p <= covered + 1e-6            # no gap162                covered = max(covered, p + 800)163            assert covered >= total164165166def test_error_classes():167    assert classify_error("net::ERR_NAME_NOT_RESOLVED at https://x") == "dns"168    assert classify_error("getaddrinfo ENOTFOUND nope.invalid") == "dns"169    assert classify_error("net::ERR_CERT_AUTHORITY_INVALID") == "tls"170    assert classify_error("self-signed certificate in certificate chain") == "tls"171    assert classify_error("net::ERR_CONNECTION_REFUSED") == "connect"172    assert classify_error("connect ECONNREFUSED 127.0.0.1:9") == "connect"173    assert classify_error("Timeout 30000ms exceeded.") == "timeout"174    assert classify_error("net::ERR_TOO_MANY_REDIRECTS") == "redirect_loop"175    assert classify_error("Target page, context or browser has been closed") == "browser_crash"176    assert classify_error("something odd") == "internal"177    assert [status_error_class(s) for s in (200, 301, 403, 404, 429, 410, 500, 503)] == \178        [None, None, "http_403", "http_404", "http_429", "http_4xx", "http_5xx", "http_5xx"]179180181def test_new_text():182    assert new_text("a\nb\n", "a\nb\nc\n  d \nc") == "c\nd"183    assert new_text("x", "x") == ""184185186def _png(tmp_path, name, size, colour, boxes=()):187    im = Image.new("RGB", size, colour)188    for box, c in boxes:189        im.paste(c, box)190    p = tmp_path / name191    im.save(p)192    return str(p)193194195def test_dhash_and_diff(tmp_path):196    a = _png(tmp_path, "a.png", (400, 300), (255, 255, 255), [((0, 0, 400, 40), (0, 0, 0))])197    b = _png(tmp_path, "b.png", (400, 300), (255, 255, 255), [((0, 0, 400, 40), (0, 0, 0))])198    c = _png(tmp_path, "c.png", (400, 300), (255, 255, 255), [((0, 0, 400, 40), (0, 0, 0)), ((100, 100, 300, 250), (200, 0, 0))])199    assert len(imaging.dhash(a)) == 64 and imaging.dhash(a) == imaging.dhash(b)200    assert imaging.hamming(imaging.dhash(a), imaging.dhash(c)) > 6201    assert imaging.diff_bbox(a, b) is None202    assert imaging.diff_bbox(a, c) == (100, 100, 300, 250)203    assert imaging.sha256_file(a) == imaging.sha256_file(b) != imaging.sha256_file(c)204205206def test_mosaic_crops_overlap_and_deduplicates_layers(tmp_path):207    red, green, white = (200, 0, 0), (0, 120, 0), (255, 255, 255)208    tiles = []209    for i, y in enumerate((0, 80, 160)):                      # 100 px tiles, 20 px overlap, document 260 px210        body = (10 * (i + 1), 10 * (i + 1), 10 * (i + 1))211        raw = _png(tmp_path, f"t{i}.png", (50, 100), body, [((0, 0, 50, 10), red), ((0, 90, 50, 100), green)])212        hid = _png(tmp_path, f"h{i}.png", (50, 100), body)213        layers = [{"selector": "#top", "position": "fixed", "anchor": "top", "rect": {"x": 0, "y": 0, "w": 50, "h": 10}},214                  {"selector": "#bottom", "position": "fixed", "anchor": "bottom", "rect": {"x": 0, "y": 90, "w": 50, "h": 10}}]215        tiles.append(imaging.MosaicTile(path=raw, hidden_path=hid, x=0, y=y, w=50, h=100, row=i, col=0, layers=layers))216    out = tmp_path / "m.png"217    report = imaging.build_mosaic(tiles, 50, 260, 1.0, out)218    im = Image.open(out).convert("RGB")219    assert im.size == (50, 260) and report["tiles"] == 3 and report["hidden_pass_tiles"] == 3220    assert im.getpixel((5, 5)) == red and im.getpixel((5, 255)) == green221    assert im.getpixel((5, 50)) == (10, 10, 10) and im.getpixel((5, 99)) == (10, 10, 10)   # first tile owns its overlap222    assert im.getpixel((5, 100)) == (20, 20, 20) and im.getpixel((5, 185)) == (30, 30, 30)223    for y in (85, 95, 165, 175):                                                           # no repeated layer224        assert im.getpixel((5, y)) not in (red, green)225    kept = {p["selector"]: p["kept_tile"] for p in report["deduplicated"]}226    assert kept == {"#top": {"row": 0, "col": 0}, "#bottom": {"row": 2, "col": 0}}227    assert white not in (im.getpixel((5, 130)),)228
Files main
Menu

Theme