SPB Git

Repository Public

test_diffing.py 11.5 KB 260 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/unit/core/test_diffing.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"""Snapshot comparison units: text, structure signature, fields, classification and pixels."""42import io4344import pytest45from PIL import Image, ImageDraw4647from spider.diffing import (48    classify,49    diff_fields,50    diff_html,51    diff_text,52    diff_visual,53    normalized_text,54    structure_signature,55)5657PAGE = """<html><head><title>Bulletin</title><style>.a{color:red}</style><script>var x = "100.00 CAD";</script></head>58<body><h1>Harbour bulletin</h1><div id="box" class="layout-a"><p id="status">%(text)s</p>59<div id="offer"><p>Price: <span id="price">%(price)s</span></p><p>Availability: <span id="avail">%(avail)s</span></p></div>60<p id="clock">Updated at %(clock)s</p></div></body></html>"""616263def page(text="The harbour is calm.", price="100.00 CAD", avail="In stock", clock="10:00"):64    return PAGE % {"text": text, "price": price, "avail": avail, "clock": clock}656667# --------------------------------------------------------------------------- text68def test_normalized_text_one_line_per_block_and_no_script_or_style():69    lines = normalized_text(page())70    assert lines == ["Bulletin", "Harbour bulletin", "The harbour is calm.", "Price: 100.00 CAD",71                     "Availability: In stock", "Updated at 10:00"]727374@pytest.mark.parametrize("html,expected", [75    ("<p>a</p><p>b</p>", ["a", "b"]),76    ("<div>intro<p>para</p>tail</div>", ["intro", "para", "tail"]),77    ("<p>one<br>two</p>", ["one", "two"]),78    ("<ul><li>x</li><li>y</li></ul>", ["x", "y"]),79    ("<table><tr><td>k</td><td>v</td></tr></table>", ["k", "v"]),80    ("<p>in<b>li</b>ne  <i>text</i></p>", ["inline text"]),81    ("<p>  spaced \n\t out  </p>", ["spaced", "out"]),82    ("", []),83    ("<<<not html", ["<<"]),84])85def test_normalized_text_block_boundaries(html, expected):86    assert normalized_text(html) == expected878889def test_normalized_text_ignore_selectors_work_on_a_copy():90    html = page()91    assert "Updated at 10:00" not in normalized_text(html, ["#clock"])92    assert "Updated at 10:00" in normalized_text(html)                # the input is not altered93    assert normalized_text(html, ["p:::broken(", "#clock"]) == normalized_text(html, ["#clock"])  # bad selector skipped949596@pytest.mark.parametrize("a,b,added,removed,changed", [97    (["x", "y"], ["x", "y"], [], [], False),98    (["x", "y"], ["x", "z"], ["z"], ["y"], True),99    (["x"], ["x", "new"], ["new"], [], True),100    (["x", "old"], ["x"], [], ["old"], True),101    ([], [], [], [], False),102    (["a", "b"], ["b", "a"], ["b"], ["b"], True),   # a moved line is reported on both sides103])104def test_diff_text_table(a, b, added, removed, changed):105    d = diff_text(a, b)106    assert (d["changed"], d["added"], d["removed"]) == (changed, added, removed)107    assert d["added_count"] == len(added) and d["removed_count"] == len(removed)108    assert d["similarity"] == (1.0 if not changed else d["similarity"]) and 0.0 <= d["similarity"] <= 1.0109110111def test_diff_text_caps_the_listing_but_counts_everything():112    d = diff_text([], [f"line {i}" for i in range(500)], max_items=20)113    assert len(d["added"]) == 20 and d["added_count"] == 500 and d["similarity"] == 0.0114115116# --------------------------------------------------------------------------- structure117def test_structure_signature_ignores_text_and_sees_tags_and_classes():118    assert structure_signature(page()) == structure_signature(page(text="Something else", price="1 $", clock="23:59"))119    sig = structure_signature('<div class="b a"><p>x</p></div>')120    assert sig[-2:] == ["div.a.b", "p"]121    assert structure_signature(page()) != structure_signature(page().replace("layout-a", "layout-b"))122123124def test_layout_change_is_detected_without_a_text_change():125    a = page()126    b = a.replace('<div id="offer">', '<aside id="side"><div id="offer">').replace(127        "</span></p></div>\n<p id=\"clock\">", "</span></p></div></aside>\n<p id=\"clock\">")128    d = diff_html(a, b)129    assert d["layout"]["changed"] and d["layout"]["similarity"] < 0.995 and not d["text"]["changed"]130    assert d["kinds"] == ["layout"]131132133def test_identical_pages_have_no_kind():134    d = diff_html(page(), page())135    assert d["kinds"] == [] and d["layout"] == {"changed": False, "similarity": 1.0} and not d["fields"]["changed"]136    assert diff_html("", "")["kinds"] == []137138139# --------------------------------------------------------------------------- fields140@pytest.mark.parametrize("a,b,expected", [141    ({"price": 1}, {"price": 1}, {}),142    ({"price": 1}, {"price": 2}, {"price": {"before": 1, "after": 2}}),143    ({"price": 1}, {}, {"price": {"before": 1, "after": None}}),144    (None, {"sku": "A"}, {"sku": {"before": None, "after": "A"}}),145    (None, None, {}),146    ({"a": 1, "b": 2}, {"a": 1, "b": 3, "c": 4}, {"b": {"before": 2, "after": 3}, "c": {"before": None, "after": 4}}),147])148def test_diff_fields_table(a, b, expected):149    assert diff_fields(a, b) == {"changed": bool(expected), "fields": expected}150151152# --------------------------------------------------------------------------- classification153@pytest.mark.parametrize("change,kinds", [154    ({"text": "A north wind picked up."}, ["content"]),155    ({"price": "120.00 CAD"}, ["content", "price"]),156    ({"price": "$120.00"}, ["content", "price"]),157    ({"price": "74,95 $"}, ["content", "price"]),158    ({"price": "1 250,00 €"}, ["content", "price"]),159    ({"avail": "Out of stock"}, ["content", "availability"]),160    ({"avail": "Rupture de stock"}, ["content", "availability"]),161    ({"price": "90.00 CAD", "avail": "Sold out"}, ["content", "price", "availability"]),162    ({"clock": "10:05"}, ["content"]),163    ({}, []),164])165def test_classify_content_price_availability(change, kinds):166    assert diff_html(page(), page(**change))["kinds"] == kinds167168169def test_classify_uses_extracted_fields_and_noise_selectors():170    d = diff_html(page(), page(clock="10:05"), ["#clock"])171    assert d["kinds"] == []                                             # the only change is in the ignored node172    d = diff_html(page(), page(clock="10:05"), ["#clock"], {"prix": 10, "stock": "yes"}, {"prix": 12, "stock": "no"})173    assert d["kinds"] == ["price", "availability"] and d["fields"]["fields"]["prix"] == {"before": 10, "after": 12}174    d = diff_html(page(), page(), None, {"title": "a"}, {"title": "b"})175    assert d["kinds"] == [] and d["fields"]["changed"]                  # a field that is neither price nor stock176177178def test_classify_direct_table():179    same = {"changed": False, "added": [], "removed": []}180    moved = {"changed": True, "added": ["Price: 10 $", "In stock"], "removed": ["In stock", "Price: 10 $"]}181    assert classify(same, False, {}, None) == []182    assert classify(same, True, {}, None) == ["layout"]183    assert classify(moved, True, {}, None) == ["content", "layout"]    # reordered lines: no price, no availability184    assert classify(same, False, {}, {"changed": True}) == ["visual"]185    assert classify(same, False, {}, {"changed": False}) == []186    assert classify(same, False, {"fields": {"monthly_rent": {}}}, None) == ["price"]187    assert classify(same, False, {"fields": {"disponibilité": {}}}, None) == ["availability"]188189190# --------------------------------------------------------------------------- pixels191def png(size=(480, 360), boxes=(), bg="white") -> bytes:192    im = Image.new("RGB", size, bg)193    d = ImageDraw.Draw(im)194    for box, colour in boxes:195        d.rectangle(box, fill=colour)196    buf = io.BytesIO()197    im.save(buf, "PNG")198    return buf.getvalue()199200201def test_diff_visual_identical_images_are_not_changed():202    a = png(boxes=[((10, 10, 100, 60), "navy")])203    d = diff_visual(a, a)204    assert d["changed"] is False and d["regions"] == [] and d["changed_ratio"] == 0.0205    assert d["size_a"] == d["size_b"] == [480, 360]206207208def test_diff_visual_finds_changed_regions_at_the_right_place():209    base = [((10, 10, 100, 60), "navy")]210    a = png(boxes=base)211    b = png(boxes=[*base, ((240, 120, 311, 191), "red"), ((48, 264, 95, 311), "green")])212    d = diff_visual(a, b)213    assert d["changed"] is True and len(d["regions"]) == 2214    regions = sorted(d["regions"], key=lambda r: r["x"])215    assert regions[0] == {"x": 48, "y": 264, "w": 48, "h": 48}       # aligned on the 24 px grid216    assert regions[1] == {"x": 240, "y": 120, "w": 72, "h": 72}217    assert 0 < d["changed_ratio"] < 0.1218    for key in ("overlay_png", "side_by_side_png", "mask_png"):219        assert Image.open(io.BytesIO(d[key])).format == "PNG"220    assert Image.open(io.BytesIO(d["side_by_side_png"])).size == (480 * 2 + 16, 360)221    mask = Image.open(io.BytesIO(d["mask_png"]))222    assert mask.getpixel((270, 150)) == 255 and mask.getpixel((20, 20)) == 0 and mask.getpixel((400, 30)) == 0223224225def test_diff_visual_region_bounds_cover_an_unaligned_change():226    a, b = png(), png(boxes=[((130, 70, 150, 80), "black")])227    (r,) = diff_visual(a, b)["regions"]228    assert r["x"] <= 130 and r["y"] <= 70 and r["x"] + r["w"] >= 151 and r["y"] + r["h"] >= 81229    assert r["w"] <= 72 and r["h"] <= 72230231232def test_diff_visual_ignores_differences_under_the_threshold():233    a, b = png(bg=(200, 200, 200)), png(bg=(210, 210, 210))234    assert diff_visual(a, b)["changed"] is False235    assert diff_visual(a, png(bg=(120, 120, 120)))["changed"] is True236237238def test_diff_visual_handles_different_sizes():239    a = png(size=(480, 360))240    b = png(size=(480, 600), boxes=[((0, 360, 479, 599), "navy")])   # the page grew by 240 px241    d = diff_visual(a, b)242    assert d["changed"] is True and d["size_a"] == [480, 360] and d["size_b"] == [480, 600]243    (r,) = d["regions"]244    assert r == {"x": 0, "y": 360, "w": 480, "h": 240}245    assert Image.open(io.BytesIO(d["overlay_png"])).size == (480, 600)246    grown_blank = diff_visual(a, png(size=(480, 600)))247    assert grown_blank["changed"] is False                              # white padding is not a change248    assert diff_visual(b, a)["regions"] == [r]                          # symmetric249250251def test_diff_visual_refuses_gigantic_canvases(monkeypatch):252    class Big:253        width, height = 20_000, 20_000254255        def convert(self, _):256            return self257    monkeypatch.setattr(Image, "open", lambda _b: Big())258    d = diff_visual(b"a", b"b")259    assert d["changed"] is None and "too large" in d["error"] and d["regions"] == []260
Files main
Menu

Theme