Files
stack/tests/market/test_lda.py

406 lines
14 KiB
Python

"""market.lda: lda.gov filings, amounts, the supersede rule, name matching."""
from __future__ import annotations
import json
import os
import time
from dataclasses import replace
from datetime import datetime
from pathlib import Path
import duckdb
import httpx
import pytest
from market import http
from market import lda as L
from market import tables as T
FX = Path(__file__).parent / "fixtures"
def aafp() -> dict:
return json.loads((FX / "lda_aafp_2024_q1.json").read_text())
@pytest.fixture
def con():
c = duckdb.connect(":memory:")
T.ensure_tables(c)
yield c
c.close()
class Pacer:
def __init__(self):
self.n = 0
def wait(self):
self.n += 1
def row(
uuid,
typ,
posted,
*,
reg=1,
cli=2,
year=2024,
period="first_quarter",
amount=100.0,
entity="AAFP",
superseded=False,
income=None,
expenses=None,
):
return T.LdaFilingRow(
uuid,
typ,
year,
period,
datetime.fromisoformat(posted),
reg,
"REG",
cli,
"CLI",
income,
expenses,
amount,
superseded,
"u",
entity,
"client" if entity else "",
"f.json",
)
def page(results, nxt=None, count=None):
return {
"count": count if count is not None else len(results),
"next": nxt,
"previous": None,
"results": results,
}
# ── transport ────────────────────────────────────────────────────────
def test_lda_requests_go_to_lda_gov():
assert L.LDA_API == "https://lda.gov/api/v1/"
seen = []
def handler(request):
seen.append(request)
return httpx.Response(200, json=page([aafp()]))
cl = httpx.Client(transport=httpx.MockTransport(handler))
out = list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
assert len(out) == 1
assert [r.url.host for r in seen] == ["lda.gov"]
assert "lda.senate.gov" not in str(seen[0].url)
assert seen[0].url.params["page_size"] == "25"
assert seen[0].url.path == "/api/v1/filings/"
def test_lda_pacer_anonymous_and_keyed():
assert L.new_pacer(None).min_interval == 4.2
assert L.new_pacer("k").min_interval == 0.55
anon = http.client("lda", None)
keyed = http.client("lda", "k")
try:
assert "authorization" not in anon.headers
assert keyed.headers["Authorization"] == "Token k"
assert anon.headers["User-Agent"] == http.USER_AGENT
finally:
anon.close()
keyed.close()
def test_query_pages_follows_next():
seen = []
p2 = "https://lda.gov/api/v1/filings/?client_name=X&page=2&page_size=25"
def handler(request):
seen.append(request)
if request.url.params.get("page") == "2":
return httpx.Response(200, json=page([{"filing_uuid": "b"}]))
return httpx.Response(200, json=page([{"filing_uuid": "a"}], nxt=p2))
pacer = Pacer()
cl = httpx.Client(transport=httpx.MockTransport(handler))
out = list(L.query_pages(cl, {"client_name": "X"}, pacer=pacer))
assert [r["filing_uuid"] for r in out] == ["a", "b"]
assert len(seen) == 2 and pacer.n == 2
def test_query_pages_refuses_a_foreign_next_and_non_json():
def foreign(request):
return httpx.Response(
200, json=page([], nxt="https://evil.example/api/v1/filings/?page=2")
)
cl = httpx.Client(transport=httpx.MockTransport(foreign))
with pytest.raises(http.Refused):
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
def bot(request):
return httpx.Response(200, text="<html>Just a moment...</html>")
cl = httpx.Client(transport=httpx.MockTransport(bot))
with pytest.raises(http.Refused) as e:
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
assert "not JSON" in str(e.value)
def listy(request):
return httpx.Response(200, json=[1, 2])
cl = httpx.Client(transport=httpx.MockTransport(listy))
with pytest.raises(http.Refused):
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
def test_query_pages_hoards_and_reuses(tmp_path, monkeypatch):
monkeypatch.setattr(http, "hoard_root", lambda: tmp_path)
calls = []
def handler(request):
calls.append(request)
return httpx.Response(200, json=page([aafp()]))
cl = httpx.Client(transport=httpx.MockTransport(handler))
d = tmp_path / "lda" / "2024"
kw = dict(pacer=Pacer(), cache_dir=d, stem="q")
first = list(L.query_pages(cl, {"client_name": "X"}, **kw))
again = list(L.query_pages(cl, {"client_name": "X"}, **kw))
assert len(calls) == 1 and len(first) == len(again) == 1
assert first[0]["_source_file"].endswith("lda/2024/q.1.json")
manifest = (tmp_path / http.MANIFEST).read_text()
assert "lda/2024/q.1.json" in manifest and "client_name" in manifest
assert "Authorization" not in manifest
def test_query_pages_stale_refetch_never_overwrites(tmp_path, monkeypatch):
monkeypatch.setattr(http, "hoard_root", lambda: tmp_path)
bodies = [
page([{"filing_uuid": "a"}]),
page([{"filing_uuid": "a"}, {"filing_uuid": "b"}]),
]
calls = []
def handler(request):
calls.append(request)
return httpx.Response(200, json=bodies[min(len(calls) - 1, 1)])
cl = httpx.Client(transport=httpx.MockTransport(handler))
d = tmp_path / "lda" / "all"
kw = dict(pacer=Pacer(), cache_dir=d, stem="q", stale_after=3600.0)
list(L.query_pages(cl, {"client_name": "X"}, **kw))
old = d / "q.1.json"
os.utime(old, (time.time() - 7200, time.time() - 7200))
got = list(L.query_pages(cl, {"client_name": "X"}, **kw))
assert len(calls) == 2 and [r["filing_uuid"] for r in got] == ["a", "b"]
assert json.loads(old.read_text())["results"] == [{"filing_uuid": "a"}]
assert len(list(d.glob("q.1.*.json"))) == 1 # the new body landed beside
# a stale page that comes back identical is touched, so it is fresh again
os.utime(old, (time.time() - 7200, time.time() - 7200))
calls.clear()
bodies[:] = [bodies[0], bodies[0]]
list(L.query_pages(cl, {"client_name": "Y"}, **kw))
list(L.query_pages(cl, {"client_name": "Y"}, **kw))
assert len(calls) <= 2
def test_query_pages_stops_at_the_request_budget():
nxt = "https://lda.gov/api/v1/filings/?client_name=X&page=2&page_size=25"
def handler(request):
return httpx.Response(200, json=page([{"filing_uuid": "a"}], nxt=nxt))
cl = httpx.Client(transport=httpx.MockTransport(handler))
budget = L.Budget(1)
out = list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer(), budget=budget))
assert len(out) == 1 and budget.exhausted and budget.used == 1
# a spent budget fetches nothing at all
assert (
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer(), budget=budget))
== []
)
unlimited = L.Budget(0)
assert unlimited.take() and not unlimited.exhausted
# ── rows ─────────────────────────────────────────────────────────────
def test_to_filing_amounts():
f, issues = L.to_filing(
aafp(), entity_key="AAFP", matched_by="client", source_file="s"
)
assert f.filing_uuid == "df5f17c4-62a7-4d7f-8ebe-aeb15147f396"
assert f.filing_type == "Q1" and f.filing_period == "first_quarter"
assert f.filing_year == 2024
assert f.amount == 825016.0 and f.income is None and f.expenses == 825016.0
assert (f.registrant_id, f.client_id) == (1342, 102605)
assert f.client_name == "AMERICAN ACADEMY OF FAMILY PHYSICIANS"
assert f.dt_posted == datetime(2024, 4, 15, 19, 36, 27) # UTC
assert f.superseded is False and (f.entity_key, f.matched_by) == ("AAFP", "client")
assert f.document_url.startswith("https://lda.gov/filings/public/filing/")
assert "BUD" in {i.general_issue_code for i in issues}
assert {i.general_issue_code for i in issues} >= {"HCR", "MMM"}
assert all(i.filing_uuid == f.filing_uuid for i in issues)
# no lobbyist, no contact is carried into any row
assert "QUINN" not in repr((f, issues)) and "TULLY" not in repr((f, issues))
def test_to_filing_income_beats_expenses_and_null_fields():
rec = aafp()
rec.update(income="60000.00", expenses=None, filing_period=None, dt_posted=None)
rec["lobbying_activities"] = None
f, issues = L.to_filing(rec, entity_key="", matched_by="", source_file="s")
assert f.amount == 60000.0 and f.income == 60000.0 and f.expenses is None
assert f.filing_period == "" and issues == []
assert f.dt_posted == datetime(1970, 1, 1)
rec.update(income="10.00", expenses="99.00")
assert (
L.to_filing(rec, entity_key="", matched_by="", source_file="s")[0].amount
== 10.0
)
@pytest.mark.parametrize("kind", ["RR", "RA"])
def test_registration_has_no_amount(kind):
rec = aafp()
rec.update(filing_type=kind, expenses="100.00", income=None)
f, _ = L.to_filing(rec, entity_key="", matched_by="", source_file="s")
assert f.amount is None and f.expenses == 100.0
# ── supersede ────────────────────────────────────────────────────────
def test_amendment_supersedes_original():
q1 = row("q1", "Q1", "2024-04-15T12:00:00")
a1 = row("a1", "1A", "2024-05-01T12:00:00")
assert L.supersede([q1, a1]) == {"q1"}
assert L.supersede([a1, q1]) == {"q1"}
other = row("q2", "Q2", "2024-07-01T00:00:00", period="second_quarter")
third = row("p3", "Q1", "2024-04-20T00:00:00", reg=9)
assert L.supersede([q1, a1, other, third]) == {"q1"}
def test_supersede_ties_and_registrations():
a = row("a", "Q1", "2024-04-15T12:00:00")
b = row("b", "1A", "2024-04-15T12:00:00")
assert L.supersede([a, b]) == {"a"} # equal posting: the later uuid wins
rr = row("r1", "RR", "2024-01-01T00:00:00", amount=None, period="")
ra = row("r2", "RA", "2024-02-01T00:00:00", amount=None, period="")
assert L.supersede([rr, ra]) == set()
assert L.supersede([]) == set()
def test_issue_codes_never_split_amount(con):
f = row("u", "Q1", "2024-04-15T00:00:00", amount=300.0)
issues = [T.LdaIssueRow("u", c, "d") for c in ("HCR", "MMM", "BUD")]
L.write_lda(con, [f], issues)
assert L.spend_by_year(con, "AAFP") == {2024: 300.0}
assert L.spend_by_year(con, "NOPE") == {}
def test_spend_ignores_superseded_and_unamounted(con):
rows = [
row("q1", "Q1", "2024-04-15T00:00:00", amount=100.0),
row("a1", "1A", "2024-05-01T00:00:00", amount=150.0),
row("n", "Q2", "2024-07-01T00:00:00", amount=None, period="second_quarter"),
row("y25", "Q1", "2025-04-01T00:00:00", amount=7.0, year=2025),
]
L.write_lda(con, rows, [])
assert L.spend_by_year(con, "AAFP") == {2024: 150.0, 2025: 7.0}
def test_write_lda_resupersedes_with_stored_rows(con):
q1 = row("q1", "Q1", "2024-04-15T00:00:00")
L.write_lda(con, [q1], [T.LdaIssueRow("q1", "HCR", "x")])
assert not T.read_lda_filings(con)[0].superseded
a1 = row("a1", "1A", "2024-05-01T00:00:00", amount=120.0)
L.write_lda(con, [a1], [T.LdaIssueRow("a1", "MMM", "y")])
got = {r.filing_uuid: r.superseded for r in T.read_lda_filings(con)}
assert got == {"q1": True, "a1": False}
assert {i.filing_uuid for i in T.read_lda_issues(con)} == {"q1", "a1"}
# writing the old one again does not resurrect it
L.write_lda(con, [q1], [T.LdaIssueRow("q1", "HCR", "x")])
got = {r.filing_uuid: r.superseded for r in T.read_lda_filings(con)}
assert got == {"q1": True, "a1": False}
assert L.spend_by_year(con, "AAFP") == {2024: 120.0}
def test_write_lda_keeps_a_stored_entity_and_replaces_issues(con):
f = row("u", "Q1", "2024-04-15T00:00:00")
L.write_lda(
con, [f], [T.LdaIssueRow("u", "HCR", "x"), T.LdaIssueRow("u", "BUD", "z")]
)
blind = replace(f, entity_key="", matched_by="")
n = L.write_lda(con, [blind], [T.LdaIssueRow("u", "MMM", "y")])
got = T.read_lda_filings(con)
assert n == 1 and len(got) == 1 and got[0].entity_key == "AAFP"
assert got[0].matched_by == "client"
assert [i.general_issue_code for i in T.read_lda_issues(con)] == ["MMM"]
assert L.write_lda(con, [], []) == 0
def test_write_lda_registration_is_never_superseded(con):
rr = row("r1", "RR", "2024-01-01T00:00:00", amount=None, period="")
ra = row("r2", "RA", "2024-02-01T00:00:00", amount=None, period="")
L.write_lda(con, [rr, ra], [])
assert [r.superseded for r in T.read_lda_filings(con)] == [False, False]
def test_filings_by_issue(con):
a = row("a", "Q1", "2024-04-15T00:00:00")
b = row("b", "Q2", "2024-07-15T00:00:00", period="second_quarter")
L.write_lda(
con,
[a, b],
[
T.LdaIssueRow("a", "HCR", "x"),
T.LdaIssueRow("a", "HCR", "again"),
T.LdaIssueRow("b", "BUD", "y"),
],
)
assert L.filings_by_issue(con, "AAFP", "HCR") == ["a"]
assert L.filings_by_issue(con, "AAFP", "BUD") == ["b"]
assert L.filings_by_issue(con, "AAFP", "TAX") == []
assert L.filings_by_issue(con, "OTHER", "HCR") == []
# ── name matching ────────────────────────────────────────────────────
def test_name_post_filter_drops_foundation():
index = L.alias_index(
[
(
"AAFP",
[
"American Academy of Family Physicians",
"AMERICAN ACADEMY OF FAMILY PHYSICIANS",
],
)
]
)
assert L.match_client("AMERICAN ACADEMY OF FAMILY PHYSICIANS", index) == "AAFP"
assert (
L.match_client("American Academy of Family Physicians, Inc.", index) == "AAFP"
)
assert (
L.match_client("AMERICAN ACADEMY OF FAMILY PHYSICIANS FOUNDATION", index) == ""
)
assert L.match_client("", index) == ""
def test_alias_index_first_key_wins_and_skips_blank():
index = L.alias_index([("B", ["Same Name", ""]), ("A", ["SAME NAME"])])
assert L.match_client("same name", index) == "A" # keys are taken in sorted order