SPB Git

Repository Public

test_extract_structured.py 7.6 KB 154 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/unit/extract/test_extract_structured.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"""JSON-LD, microdata, RDFa Lite, Open Graph and meta extraction."""42from spider.extract.structured import extract_structured, parse_json_ld_text4344BASE = "https://ex.com/p/1"454647def test_json_ld_graph_flattened_and_multiple_scripts():48    html = """<script type="application/ld+json">49    {"@context": "https://schema.org", "@graph": [50      {"@type": "Product", "name": "Vélo", "offers": {"@type": "Offer", "price": "499.99", "priceCurrency": "CAD"}},51      {"@type": "BreadcrumbList", "itemListElement": []}]}</script>52    <script type="application/ld+json">[{"@type": "Organization", "name": "Exemple inc."}]</script>53    <script type="APPLICATION/LD+JSON; charset=utf-8">{"@type": "WebSite", "name": "Site"}</script>"""54    data = extract_structured(html, BASE)55    assert [o["@type"] for o in data["json_ld"]] == ["Product", "BreadcrumbList", "Organization", "WebSite"]56    assert data["json_ld"][0]["@context"] == "https://schema.org"  # inherited from the @graph wrapper57    assert data["json_ld"][0]["offers"]["price"] == "499.99"58    assert data["errors"] == []596061def test_json_ld_tolerates_trailing_commas_comments_and_cdata():62    html = """<script type="application/ld+json"><!--63    {"@type": "Product", "name": "A, }B", "tags": ["x", "y",], }64    --></script>65    <script type="application/ld+json">//<![CDATA[66    {"@type": "Event", "name": "Fête"}67    //]]></script>"""68    data = extract_structured(html, BASE)69    assert data["errors"] == []70    assert data["json_ld"][0] == {"@type": "Product", "name": "A, }B", "tags": ["x", "y"]}71    assert data["json_ld"][1]["name"] == "Fête"727374def test_invalid_json_ld_is_reported_not_raised():75    html = """<script type="application/ld+json">{"@type": "Product", "name": </script>76    <script type="application/ld+json"></script>77    <script type="application/ld+json">{"@type": "Thing", "name": "ok"}</script>"""78    data = extract_structured(html, BASE)79    assert [o["name"] for o in data["json_ld"]] == ["ok"]80    assert [(e["source"], e["index"]) for e in data["errors"]] == [("json_ld", 0), ("json_ld", 1)]81    assert data["errors"][0]["snippet"].startswith('{"@type": "Product"')828384def test_parse_json_ld_text_keeps_comment_like_strings():85    assert parse_json_ld_text('{"a": "<!-- kept -->"}') == {"a": "<!-- kept -->"}868788def test_microdata_nested_and_itemref():89    html = """<div itemscope itemtype="https://schema.org/Product" itemref="extra">90      <h1 itemprop="name">Vélo de route</h1><img itemprop="image" src="/v.jpg">91      <a itemprop="url" href="/velo">voir</a><meta itemprop="sku" content="V-1">92      <div itemprop="offers" itemscope itemtype="https://schema.org/Offer">93        <span itemprop="price" content="499.99">499,99 $</span>94        <time itemprop="validFrom" datetime="2026-12-03">3 déc.</time>95      </div>96    </div>97    <p id="extra"><span itemprop="brand">Marque X</span></p>"""98    (item,) = extract_structured(html, BASE)["microdata"]99    props = item["properties"]100    assert item["type"] == ["https://schema.org/Product"]101    assert props["name"] == ["Vélo de route"] and props["sku"] == ["V-1"]102    assert props["image"] == ["https://ex.com/v.jpg"] and props["url"] == ["https://ex.com/velo"]103    assert props["brand"] == ["Marque X"]  # pulled in through itemref104    offer = props["offers"][0]105    assert offer["type"] == ["https://schema.org/Offer"]106    assert offer["properties"] == {"price": ["499.99"], "validFrom": ["2026-12-03"]}107    assert "price" not in props  # nested properties stay in the nested item108109110def test_microdata_itemref_cycle_terminates():111    html = """<div id="a" itemscope itemref="b"><span itemprop="name">A</span></div>112    <div id="b" itemprop="child" itemscope itemref="a"><span itemprop="name">B</span></div>"""113    data = extract_structured(html, BASE)114    assert data["microdata"][0]["properties"]["name"] == ["A"]115116117def test_rdfa_lite():118    html = """<div vocab="https://schema.org/" typeof="Product" resource="#velo">119      <span property="name">Vélo</span><img property="image" src="/v.jpg">120      <div property="offers" typeof="Offer"><meta property="price" content="499.99">121      <span property="priceCurrency">CAD</span></div></div>"""122    (item,) = extract_structured(html, BASE)["rdfa"]123    assert item["type"] == ["Product"] and item["vocab"] == "https://schema.org/"124    assert item["resource"] == "https://ex.com/p/1#velo"125    assert item["properties"]["name"] == ["Vélo"]126    assert item["properties"]["image"] == ["https://ex.com/v.jpg"]127    offer = item["properties"]["offers"][0]128    assert offer["type"] == ["Offer"] and offer["properties"] == {"price": ["499.99"], "priceCurrency": ["CAD"]}129130131def test_opengraph_and_meta():132    html = """<html lang="fr"><head><title>Titre</title><meta charset="UTF-8">133    <meta property="og:title" content="Titre OG"><meta property="og:image" content="https://ex.com/1.jpg">134    <meta property="og:image" content="https://ex.com/2.jpg"><meta name="twitter:card" content="summary">135    <meta property="article:published_time" content="2026-12-03"><meta property="product:price:amount" content="10.00">136    <meta name="description" content="Une  description"><meta name="robots" content="noindex">137    <link rel="canonical" href="/canon"></head></html>"""138    data = extract_structured(html, BASE)139    assert data["opengraph"] == {140        "og:title": "Titre OG", "og:image": ["https://ex.com/1.jpg", "https://ex.com/2.jpg"],141        "twitter:card": "summary", "article:published_time": "2026-12-03", "product:price:amount": "10.00"}142    meta = data["meta"]143    assert meta["description"] == "Une description" and meta["robots"] == "noindex"144    assert meta["title"] == "Titre" and meta["lang"] == "fr" and meta["charset"] == "utf-8"145    assert meta["canonical"] == "https://ex.com/canon"146    assert "description" not in data["opengraph"]147148149def test_empty_and_garbage_documents():150    for html in ("", "<<<<", "<script type='application/ld+json'>" + "[" * 100_000 + "</script>"):151        data = extract_structured(html, BASE)152        assert set(data) == {"json_ld", "microdata", "rdfa", "opengraph", "meta", "errors"}153        assert data["json_ld"] == []154
Files main
Menu

Theme