Files
stack/tests/market/test_fec.py
kert cba6cca08f feat(market): hoard namesake FEC committees and the ACP and AOA PACs
A name-search hit that is not the tracked entity's PAC is kept on a full pull: committee page, cycle totals, and Schedule B, stored with an empty entity key. ACP Services PAC and the AOA affiliate's Osteopathic PAC are curated ids. The AAO communication-cost committee is kept on AAO.
2026-11-14 15:00:39 -05:00

424 lines
13 KiB
Python

"""market.fec: curated committee ids, exact-name fallback, totals, Schedule B."""
from __future__ import annotations
import json
from datetime import date
from pathlib import Path
import httpx
import pytest
from market import fec as F
from market import http
from market import tables as T
FX = Path(__file__).parent / "fixtures"
SECRET = "fec-test-key-do-not-leak"
PAC = "AMERICAN ACADEMY OF FAMILY PHYSICIANS POLITICAL ACTION COMMITTEE (FAMMEDPAC)"
PAC_ALIAS = "AMERICAN ACADEMY OF FAMILY PHYSICIANS POLITICAL ACTION COMMITTEE FAMMEDPAC"
SHORT = "AMERICAN ACADEMY OF FAMILY PHYSICIANS"
def _load(name: str) -> dict:
return json.loads((FX / name).read_text())
@pytest.fixture
def con():
c = __import__("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 entity(key, name, aliases=""):
return T.EntityRow(key, name, "organization", aliases=aliases or name)
def _client(handler, *, key: str | None = None) -> httpx.Client:
headers = {"X-Api-Key": key} if key else {}
return httpx.Client(transport=httpx.MockTransport(handler), headers=headers)
def test_committee_curated_ids_win():
assert F.FEC_API == "https://api.open.fec.gov/v1/"
assert F.new_pacer().min_interval == 3.7
seen = []
body = _load("fec_committees_aafp.json")
def handler(request):
seen.append(request)
return httpx.Response(200, json=body)
cl = _client(handler)
rows, cands = F.resolve(cl, entity("AAFP", SHORT), ["C00411553"], pacer=Pacer())
assert cands == []
assert [(r.committee_id, r.basis, r.entity_key) for r in rows] == [
("C00411553", "curated", "AAFP")
]
assert rows[0].cite_url == "https://www.fec.gov/data/committee/C00411553/"
assert [r.url.host for r in seen] == ["api.open.fec.gov"]
assert seen[0].url.path == "/v1/committee/C00411553/"
assert all("/committees" not in r.url.path for r in seen)
assert "api_key" not in str(seen[0].url)
def test_committee_exact_name_fallback_cited():
body = {"results": _load("fec_committees_aafp.json")["results"]}
def handler(request):
return httpx.Response(200, json=body)
cl = _client(handler)
rows, cands = F.resolve(cl, entity("AAFP", SHORT), [], pacer=Pacer())
assert rows == []
assert cands[0]["name"] == PAC
assert cands[0]["committee_id"] == "C00411553"
rows, cands = F.resolve(cl, entity("AAFP", PAC_ALIAS), [], pacer=Pacer())
assert cands == []
assert rows[0].basis == "exact-name"
assert rows[0].cite_url == "https://www.fec.gov/data/committee/C00411553/"
assert rows[0].name == PAC
def test_hoard_committee_is_kept_unattached():
def handler(request):
assert request.url.path == "/v1/committee/C00765230/"
return httpx.Response(
200,
json={
"results": [
{
"committee_id": "C00765230",
"name": "AMERICAN ANTHEM PAC",
"committee_type": "V",
"designation": "U",
}
]
},
)
rows = F.hoard_committees(_client(handler), ["C00765230"], pacer=Pacer())
assert [(r.committee_id, r.basis, r.entity_key, r.name) for r in rows] == [
("C00765230", "hoarded", "", "AMERICAN ANTHEM PAC")
]
assert rows[0].cite_url == "https://www.fec.gov/data/committee/C00765230/"
def test_short_alias_never_matches_inside_names():
name = "AMALGAMATED TRANSIT UNION PAC"
def handler(request):
assert request.url.params["q"] == "AMA"
return httpx.Response(
200,
json={"results": [{"committee_id": "C00999999", "name": name}]},
)
rows, cands = F.resolve(_client(handler), entity("AMA", "AMA"), [], pacer=Pacer())
assert rows == []
assert [(c["committee_id"], c["name"]) for c in cands] == [("C00999999", name)]
def test_totals_row():
body = _load("fec_totals_C00411553_2024.json")
def handler(request):
assert request.url.path == "/v1/committee/C00411553/totals/"
assert request.url.params["cycle"] == "2024"
return httpx.Response(200, json=body)
row = F.totals(_client(handler), "C00411553", 2024, pacer=Pacer())
assert row is not None
assert row.receipts == 513798.01
assert row.disbursements == 696685.91
assert row.fed_candidate_committee_contributions == 683300.0
assert (row.coverage_start, row.coverage_end) == (
date(2023, 1, 1),
date(2024, 12, 31),
)
def test_schedule_b_keyset_paging():
page1 = _load("fec_schedule_b_page1.json")
page2 = {
"results": [
{
"sub_id": "4010120240004",
"committee_id": "C00411553",
"two_year_transaction_period": 2024,
"disbursement_date": "2024-02-01",
"disbursement_amount": 1.0,
"recipient_name": "SECOND PAGE",
"memo_code": None,
}
],
"pagination": {},
}
seen = []
def handler(request):
seen.append(request)
if "last_index" in request.url.params:
return httpx.Response(200, json=page2)
return httpx.Response(200, json=page1)
rows = F.contributions(_client(handler), "C00411553", 2024, pacer=Pacer())
assert len(seen) == 2
assert seen[0].url.path == "/v1/schedules/schedule_b/"
assert seen[0].url.params["per_page"] == "100"
assert seen[0].url.params["sort"] == "-disbursement_date"
assert seen[0].url.params["two_year_transaction_period"] == "2024"
assert "last_index" not in seen[0].url.params
assert seen[1].url.params["last_index"] == "123"
assert seen[1].url.params["last_disbursement_date"] == "2024-03-01"
assert [r.sub_id for r in rows] == [
"4010120240001",
"4010120240002",
"4010120240003",
"4010120240004",
]
def test_memo_rows_excluded_from_totals(con):
T.write_fec_committees(
con,
[
T.FecCommitteeRow(
"C00411553",
PAC,
"Q",
"U",
"AAFP",
"curated",
"https://www.fec.gov/data/committee/C00411553/",
None,
None,
"",
)
],
)
rows = [
T.FecContributionRow(
"a",
"C00411553",
2024,
date(2024, 6, 1),
100.0,
"C1",
"PAC",
"",
"",
"",
"",
"",
"",
"",
),
T.FecContributionRow(
"b",
"C00411553",
2024,
date(2024, 5, 1),
25.0,
"",
"JANE Q PUBLIC",
"",
"",
"",
"",
"",
"",
"",
),
T.FecContributionRow(
"c",
"C00411553",
2024,
date(2024, 4, 1),
100.0,
"",
"MEMO",
"",
"",
"",
"",
"",
"X",
"",
),
]
T.write_fec_contributions(con, rows)
assert F.contributions_by_cycle(con, "AAFP") == {2024: 125.0}
def test_schedule_b_rows_stored_as_filed(con):
page = _load("fec_schedule_b_page1.json")
def handler(request):
body = dict(page)
body["pagination"] = {}
return httpx.Response(200, json=body)
rows = F.contributions(_client(handler), "C00411553", 2024, pacer=Pacer())
person = next(r for r in rows if r.recipient_name == "JANE Q PUBLIC")
assert person.recipient_committee_id == ""
assert person.amount == 25.0
memo = next(r for r in rows if r.memo_code == "X")
assert memo.recipient_name == "MEMO OF THE 100"
T.write_fec_contributions(con, rows)
stored = T.read_fec_contributions(con)
assert [r.recipient_name for r in stored if r.sub_id == "4010120240002"] == [
"JANE Q PUBLIC"
]
assert any(r.memo_code == "X" for r in stored)
def test_fec_error_message_has_no_key():
seen = []
def handler(request):
seen.append(request)
return httpx.Response(403, text="no")
cl = _client(handler, key=SECRET)
with pytest.raises(http.Refused) as exc:
F.totals(cl, "C00411553", 2024, pacer=Pacer())
assert exc.value.source == "fec"
assert SECRET not in str(exc.value)
assert SECRET not in str(seen[0].url)
assert "api_key" not in str(seen[0].url)
assert seen[0].headers["x-api-key"] == SECRET
def bot(request):
return httpx.Response(200, text="<html>Just a moment...</html>")
with pytest.raises(http.Refused) as exc2:
F.totals(_client(bot, key=SECRET), "C00411553", 2024, pacer=Pacer())
assert "not JSON" in str(exc2.value)
assert SECRET not in str(exc2.value)
def test_budget_edges_and_blank_fields(monkeypatch):
company = type("C", (), {"cik": "0000000001", "fec_committee_ids": ("C1",)})()
org = type(
"O", (), {"key": "AAFP", "fec_committee_ids": ("C2",), "pseudo": False}
)()
pseudo = type(
"O", (), {"key": "SEAT", "fec_committee_ids": ("C9",), "pseudo": True}
)()
monkeypatch.setattr(F, "load_seed", lambda: ([company], [org, pseudo]))
assert F.committee_ids() == {"AAFP": ("C2",), "0000000001": ("C1",)}
limited = F.Budget(1)
assert limited.take() is True
assert limited.take() is False and limited.why == "request limit"
stopped = F.Budget(0, stop=lambda: True)
assert stopped.take() is False and stopped.why == "time limit"
assert F._date(None) is None and F._date("") is None
assert F._money("") == 0.0
row = F.to_contribution(
{
"sub_id": "z",
"amount": "",
"candidate_state": "KS",
"candidate_district": "01",
},
source_file="s",
cycle=2024,
)
assert (row.cycle, row.amount, row.day, row.candidate_state) == (
2024,
0.0,
None,
"KS",
)
seen = []
def handler(request):
seen.append(request.url.path)
return httpx.Response(
200,
json={
"results": [
{"committee_id": "", "name": "NO ID"},
{"committee_id": "C1", "name": PAC},
{"committee_id": "C1", "name": PAC},
]
},
)
cl = _client(handler)
org_row = entity("AAFP", SHORT, aliases=f"{SHORT}|{PAC_ALIAS}")
rows, cands = F.resolve(cl, org_row, [], pacer=Pacer(), budget=F.Budget(1))
assert [r.committee_id for r in rows] == ["C1"]
assert rows[0].basis == "exact-name"
assert cands == []
assert seen == ["/v1/committees/"] # the second alias stops on the budget
def curated(request):
return httpx.Response(200, json=_load("fec_committees_aafp.json"))
one, _ = F.resolve(
_client(curated),
entity("AAFP", SHORT),
["C00411553", "C00000001"],
pacer=Pacer(),
budget=F.Budget(1),
)
assert [r.committee_id for r in one] == ["C00411553"]
spent = F.Budget(1)
spent.take()
def boom(request):
raise AssertionError("budget should have stopped the download")
assert (
F.totals(_client(boom), "C00411553", 2024, pacer=Pacer(), budget=spent) is None
)
assert (
F.contributions(_client(boom), "C00411553", 2024, pacer=Pacer(), budget=spent)
== []
)
def empty(request):
return httpx.Response(200, json={"results": []})
assert F.totals(_client(empty), "C00411553", 2022, pacer=Pacer()) is None
def test_fec_hoard_reuses_and_skips_a_missing_committee(tmp_path, monkeypatch):
monkeypatch.setattr(http, "hoard_root", lambda: tmp_path)
calls = []
body = _load("fec_committees_aafp.json")
def handler(request):
calls.append(request.url.path)
if "C00000000" in request.url.path:
return httpx.Response(404, json={"results": []})
return httpx.Response(200, json=body)
cl = _client(handler)
cache = tmp_path / "fec"
kw = dict(pacer=Pacer(), cache=cache)
first, _ = F.resolve(cl, entity("AAFP", SHORT), ["C00411553"], **kw)
again, _ = F.resolve(cl, entity("AAFP", SHORT), ["C00411553"], **kw)
assert calls == ["/v1/committee/C00411553/"]
assert first[0].source_file.endswith("fec/committee/C00411553.json")
assert again[0].committee_id == "C00411553"
empty, cands = F.resolve(cl, entity("AAFP", SHORT), ["C00000000"], **kw)
assert empty == [] and cands == []