"""Contract tests for the samorzad.gov.pl contribution.""" from __future__ import annotations import hashlib import json import os import sys from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq import pytest sys.path.insert(0, str(Path(__file__).resolve().parent)) from clean_samorzad_gov_pl import ( DYNAWORD_SCHEMA, _replace_release, normalize_record, publisher_name_from_html, verify_upstream_release, ) def test_publisher_name_comes_from_site_name_metadata(): html = """ Strona główna - inna wartość - Portal gov.pl """ assert publisher_name_from_html(html) == "Szkoła Podstawowa im. Sybiraków w Netcie" def test_publisher_name_falls_back_to_homepage_title(): html = "Strona główna - Gmina Chłopice - Portal gov.pl" assert publisher_name_from_html(html) == "Gmina Chłopice" def test_normalize_record_maps_publisher_to_author_and_preserves_provenance(): source = { "record_id": "abc123", "source_url": "https://samorzad.gov.pl/web/gmina-chlopice/przyklad", "final_url": "https://samorzad.gov.pl/web/gmina-chlopice/przyklad-docelowy", "tenant": "gmina-chlopice", "publisher_type": "municipality", "title": "Przykładowy artykuł", "text": "Zażółć gęślą jaźń. " * 20, "published_date": "2024-05-17", } row, attribution = normalize_record( source, publishers={"gmina-chlopice": "Gmina Chłopice"}, token_count=123, added="2026-08-14", ) assert row == { "id": "samorzad_gov_pl_abc123", "text": source["text"], "source": "samorzad_gov_pl", "added": "2026-08-14", "created": "2024-05-17", "token_count": 123, "license": "CC-BY-SA-4.0", "author": "Gmina Chłopice", } assert attribution["id"] == row["id"] assert attribution["source_url"] == source["source_url"] assert attribution["final_url"] == source["final_url"] assert attribution["attribution_url"] == source["final_url"] assert attribution["publisher"] == "Gmina Chłopice" assert attribution["title"] == source["title"] assert attribution["license_url"] == "https://creativecommons.org/licenses/by-sa/4.0/" assert attribution["modified"] is True def test_verify_upstream_release_rejects_modified_shard(tmp_path): data_dir = tmp_path / "data" data_dir.mkdir() shard = data_dir / "train.parquet" pq.write_table( pa.table({"record_id": ["one"], "text": ["Treść źródłowa"]}), shard, ) text_digest = hashlib.sha256() text_digest.update("one\0Treść źródłowa\n".encode()) manifest = { "schema_version": "fixture-1", "dataset_id": "fixture/dataset", "record_count": 1, "record_fields": ["record_id", "text"], "record_text_sha256": text_digest.hexdigest(), "artifacts": [ { "path": "data/train.parquet", "records": 1, "bytes": shard.stat().st_size, "sha256": hashlib.sha256(shard.read_bytes()).hexdigest(), } ], } manifest_path = tmp_path / "manifest.json" manifest_path.write_text(json.dumps(manifest), encoding="utf-8") expected = { "manifest_sha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(), "dataset_id": "fixture/dataset", "schema_version": "fixture-1", "record_count": 1, "record_text_sha256": text_digest.hexdigest(), } verify_upstream_release(data_dir, manifest_path, expected) shard.write_bytes(shard.read_bytes() + b"corrupt") with pytest.raises(ValueError, match="(size|hash) mismatch"): verify_upstream_release(data_dir, manifest_path, expected) def test_release_replacement_rolls_back_on_failure(tmp_path, monkeypatch): names = ( "samorzad_gov_pl.parquet", "samorzad_gov_pl.attribution.jsonl", "samorzad_gov_pl.stats.json", ) staged = tmp_path / "staged" output = tmp_path / "output" staged.mkdir() output.mkdir() for name in names: (staged / name).write_text(f"new:{name}") (output / name).write_text(f"old:{name}") original_replace = os.replace failed = False def fail_once(source, destination): nonlocal failed if Path(source) == staged / names[1] and not failed: failed = True raise OSError("injected replacement failure") original_replace(source, destination) monkeypatch.setattr(os, "replace", fail_once) with pytest.raises(OSError, match="injected"): _replace_release(staged, output) assert [(output / name).read_text() for name in names] == [ f"old:{name}" for name in names ] def test_canonical_schema_matches_dynaword(): assert DYNAWORD_SCHEMA == pa.schema( [ ("id", pa.string()), ("text", pa.string()), ("source", pa.string()), ("added", pa.string()), ("created", pa.string()), ("token_count", pa.int64()), ("license", pa.string()), ("author", pa.string()), ] ) def test_release_artifact_matches_stats_and_has_institution_authors(): root = Path(__file__).resolve().parents[1] data_dir = root / "data" / "samorzad_gov_pl" parquet_path = data_dir / "samorzad_gov_pl.parquet" stats_path = data_dir / "samorzad_gov_pl.stats.json" sidecar_path = data_dir / "samorzad_gov_pl.attribution.jsonl" table = pq.read_table(parquet_path) stats = json.loads(stats_path.read_text(encoding="utf-8")) attributions = [ json.loads(line) for line in sidecar_path.open(encoding="utf-8") if line.strip() ] ids = table["id"].to_pylist() texts = table["text"].to_pylist() authors = table["author"].to_pylist() assert table.schema == DYNAWORD_SCHEMA assert table.num_rows == stats["kept"] == len(attributions) assert stats["authors_with_value"] == stats["kept"] assert stats["publisher_count"] == 247 assert stats["local_public_tenant_count"] == 246 assert stats["central_tenant_count"] == 1 assert stats["redirected_urls"] == 693 assert stats["upstream_artifact_count"] == 10 assert stats["upstream_manifest_sha256"] == ( "97b5a266b2fd4f043648b7d3c757721cd826c7ca1048301761084b0abdee5c48" ) assert set(table["source"].to_pylist()) == {"samorzad_gov_pl"} assert set(table["license"].to_pylist()) == {"CC-BY-SA-4.0"} assert len(ids) == len(set(ids)) assert ids == sorted(ids) assert len(texts) == len(set(texts)) assert all(value.strip() for value in authors) assert all(value > 0 for value in table["token_count"].to_pylist()) assert stats["chars"] == sum(map(len, texts)) assert stats["tokens"] == sum(table["token_count"].to_pylist()) assert [item["id"] for item in attributions] == ids assert [item["publisher"] for item in attributions] == authors assert all(item["attribution_url"] == item["final_url"] for item in attributions) assert sum( item["source_url"] != item["final_url"] for item in attributions ) == stats["redirected_urls"]