polish-dynaword / src /test_sejm_interpellations_contract.py
ppuzio's picture
Add source: sejm_interpellations (10th-term written Q&A)
d69c01f
Raw
History Blame
7.04 kB
"""TDD contract for Sejm interpellations / written-questions ingestion."""
import json
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
ROOT = Path(__file__).resolve().parent.parent
PARQUET = ROOT / "data" / "sejm_interpellations" / "sejm_interpellations.parquet"
STATS = ROOT / "data" / "sejm_interpellations" / "sejm_interpellations.stats.json"
CANON = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
from fetch_sejm_interpellations import (
MIN_CHARS,
_jobs_for_item,
normalize_document,
should_fetch_reply,
)
BODY = (
"Szanowny Panie Ministrze! " + ("Ogrody działkowe wymagają ochrony prawnej. " * 12)
)
Q_HTML = f"""<!DOCTYPE html>
<html lang="pl"><head><title>Interpelacja w sprawie ogrodów</title></head>
<body>
<h1>Interpelacja nr 1</h1>
<p class="int-recipient">do ministra rozwoju i technologii</p>
<p class="int-title">w sprawie sytuacji w rodzinnych ogrodach działkowych</p>
<p class="intAuthor">Zgłaszający: Katarzyna Osos</p>
<p class="intDateTresc">Data wpływu: 15-11-2023</p>
<p>{BODY}</p>
<p>Podstawa: decyzja (znak: BPRM.4820.2.3.2020).</p>
</body></html>
"""
R_HTML = f"""<!DOCTYPE html>
<html lang="pl"><head><title>Odpowiedź na interpelację w sprawie ogrodów</title></head>
<body>
<h1>Odpowiedź na interpelację nr 8</h1>
<p class="int-title">w sprawie tzw. specustawy</p>
<p class="intAuthor">Odpowiadający: minister rodziny Agnieszka Dziemianowicz-Bąk</p>
<p class="intDate">Warszawa, 22-02-2024</p>
<p>Szanowny Panie Marszałku, {"odpowiadając informuję jak poniżej. " * 15}</p>
</body></html>
"""
STUB_HTML = """<!DOCTYPE html>
<html><head><title>Odpowiedź</title></head>
<body>
<h1>Odpowiedź na interpelację nr 806</h1>
<p class="int-title">w sprawie warunków sanitarnych</p>
<p class="intAuthor">Odpowiadający: sekretarz stanu Krzysztof Kukucki</p>
<p class="intDate">Warszawa, 20-02-2024</p>
<p>Treść odpowiedzi znajduje się w załączniku.</p>
<p>Załączniki</p>
<p>LUB-OMK.601.1.2024.3.pdf</p>
</body></html>
"""
ITEM = {
"num": 1,
"term": 10,
"title": "Interpelacja w sprawie sytuacji w rodzinnych ogrodach działkowych",
"receiptDate": "2023-11-15",
"from": ["277"],
"to": ["minister rozwoju i technologii"],
}
class SejmInterpellationsContractTest(unittest.TestCase):
def test_should_fetch_reply_requires_key_and_html(self):
self.assertTrue(should_fetch_reply({"key": "D2QJNB", "onlyAttachment": False}))
self.assertFalse(should_fetch_reply({"key": "X", "onlyAttachment": True}))
self.assertFalse(should_fetch_reply({"onlyAttachment": False}))
self.assertFalse(should_fetch_reply({"key": None, "onlyAttachment": False}))
self.assertFalse(should_fetch_reply({}))
def test_question_strips_header_keeps_body_and_file_number(self):
row = normalize_document("interpellation", ITEM, Q_HTML)
self.assertIsNotNone(row)
self.assertEqual(set(row), {"text", "meta"})
self.assertNotIn("<", row["text"])
self.assertNotIn("Interpelacja nr 1", row["text"])
self.assertNotIn("Zgłaszający:", row["text"])
self.assertNotIn("Data wpływu:", row["text"])
self.assertNotIn("do ministra rozwoju", row["text"])
self.assertIn("Ogrody działkowe", row["text"])
self.assertIn("BPRM.4820.2.3.2020", row["text"]) # not a phone
self.assertGreaterEqual(len(row["text"]), MIN_CHARS)
self.assertEqual(row["meta"]["num"], 1)
self.assertEqual(row["meta"]["term"], 10)
self.assertEqual(row["meta"]["kind"], "interpellation")
self.assertEqual(row["meta"]["author"], "Katarzyna Osos")
self.assertTrue(row["meta"]["url"].endswith("/interpellations/1/body"))
def test_reply_strips_header_and_records_key(self):
reply = {"key": "D2QJNB", "from": "Minister Agnieszka Dziemianowicz-Bąk",
"receiptDate": "2024-02-22", "onlyAttachment": False}
item = {**ITEM, "num": 8}
row = normalize_document("interpellation_reply", item, R_HTML, reply=reply)
self.assertIsNotNone(row)
self.assertNotIn("Odpowiedź na interpelację nr 8", row["text"])
self.assertNotIn("Odpowiadający:", row["text"])
self.assertNotIn("Warszawa, 22-02-2024", row["text"])
self.assertIn("Szanowny Panie Marszałku", row["text"])
self.assertEqual(row["meta"]["kind"], "interpellation_reply")
self.assertEqual(row["meta"]["reply_key"], "D2QJNB")
self.assertIn("Dziemianowicz", row["meta"]["author"])
self.assertTrue(row["meta"]["url"].endswith("/interpellations/8/reply/D2QJNB/body"))
def test_attachment_stub_is_rejected(self):
reply = {"key": "ABC", "from": "X", "receiptDate": "2024-02-20"}
self.assertIsNone(normalize_document(
"interpellation_reply", {**ITEM, "num": 806}, STUB_HTML, reply=reply
))
def test_written_question_url(self):
item = {**ITEM, "title": "Zapytanie w sprawie świadczeń"}
row = normalize_document("written_question", item, Q_HTML)
self.assertTrue(row["meta"]["url"].endswith("/writtenQuestions/1/body"))
self.assertEqual(row["meta"]["kind"], "written_question")
def test_jobs_include_html_replies_only(self):
item = {
**ITEM,
"replies": [
{"key": "KEEP", "onlyAttachment": False},
{"key": "PDF", "onlyAttachment": True},
{"onlyAttachment": False},
],
}
jobs = _jobs_for_item(item)
self.assertEqual(jobs[0], (False, None))
self.assertEqual(len(jobs), 2)
self.assertEqual(jobs[1][1]["key"], "KEEP")
class SejmInterpellationsParquetTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not PARQUET.is_file():
raise unittest.SkipTest("parquet not built yet")
import pyarrow.parquet as pq
cls.tbl = pq.read_table(PARQUET)
cls.stats = json.loads(STATS.read_text(encoding="utf-8"))
def test_canonical_schema_and_uniform_source_license(self):
self.assertEqual(self.tbl.column_names, CANON)
src = set(self.tbl["source"].to_pylist())
lic = set(self.tbl["license"].to_pylist())
self.assertEqual(src, {"sejm_interpellations"})
self.assertEqual(lic, {"public-domain (official documents)"})
def test_nonempty_text_and_positive_tokens(self):
texts = self.tbl["text"].to_pylist()
toks = self.tbl["token_count"].to_pylist()
self.assertTrue(all(t and t.strip() for t in texts))
self.assertTrue(all(n > 0 for n in toks))
def test_stats_match_parquet(self):
self.assertEqual(self.stats["kept"], self.tbl.num_rows)
self.assertEqual(self.stats["tokens"], sum(self.tbl["token_count"].to_pylist()))
self.assertEqual(self.stats["authors_with_value"], self.tbl.num_rows)
if __name__ == "__main__":
unittest.main()