Coverage for tests/references/test_politics.py: 100%
202 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
1"""Tests the politics module."""
3from __future__ import annotations
5import pathlib
7import amos
8import pandas as pd
9import pytest
10from conftest import Site
12import courtpy
13from courtpy import politics
15MQ_PAGE = 'https://mqscores.wustl.edu/measures.php'
16MQ_JUSTICES = 'https://mqscores.wustl.edu/media/2024/justices.csv'
17VOTEVIEW = 'https://voteview.com/static/data/out/members/HSall_members.csv'
18# The links of the page of Martin-Quinn scores, which are to a folder named
19# for the year of the release.
20MQ_LINKS = (
21 '<html><body><h3>2024 JUSTICE DATA FILES</h3>'
22 '<a href="media/2024/justices.csv">justices.csv</a>'
23 '<a href="media/2024/justices.dta">justices.dta</a>'
24 '<h3>2024 COURT DATA FILES</h3>'
25 '<a href="media/2024/court.csv">court.csv</a>'
26 '<a href="media/2023/2023_MQscores.zip">2023 MQ Scores Data</a></body></html>')
29@pytest.fixture
30def scores() -> pd.DataFrame:
31 """Returns scores of justices like the Martin-Quinn "justices" file."""
32 return pd.DataFrame({
33 'term': [2020, 2021, 2020, 2020],
34 'justice': [117, 117, 111, 108],
35 'justiceName': ['ACBarrett', 'ACBarrett', 'JGRoberts', 'CThomas'],
36 'post_mn': [0.961, 1.004, 0.3, 3.0],
37 'post_sd': [0.309, 0.259, 0.2, 0.4],
38 'post_med': [0.954, 1.002, 0.3, 3.0],
39 'post_025': [0.394, 0.518, 0.0, 2.2],
40 'post_975': [1.601, 1.514, 0.6, 3.8]})
43@pytest.fixture
44def members() -> pd.DataFrame:
45 """Returns members of Congress like the Voteview file of their ideology."""
46 return pd.DataFrame({
47 'congress': [97, 97, 97, 97, 97, 97, 98, 98, 98],
48 'chamber': ['President', 'Senate', 'Senate', 'Senate', 'House', 'House', 'Senate', 'House', 'House'],
49 'nominate_dim1': [0.9, -0.4, 0.1, 0.3, -0.2, 0.4, 0.2, -0.5, -0.1],
50 'nominate_dim2': [0.0, 0.5, 0.5, 0.5, 0.1, 0.1, 0.3, 0.2, 0.2]})
53@pytest.fixture
54def site(scores: pd.DataFrame, members: pd.DataFrame) -> Site:
55 """Returns a session that serves the sources' pages and files."""
56 return Site({
57 MQ_PAGE: MQ_LINKS,
58 MQ_JUSTICES: scores.to_csv(index = False),
59 VOTEVIEW: members.to_csv(index = False)})
62def test_techniques_are_in_the_library() -> None:
63 for name in ('add_executive', 'add_legislature', 'add_high_court'):
64 assert amos.library.classify(name) == 'merger'
65 assert issubclass(politics.AddExecutive, politics.ByDate)
68def test_presidents() -> None:
69 table = politics.presidents()
70 assert list(table.columns) == ['year', 'president_party']
71 parties = table.set_index('year')['president_party']
72 assert parties.index[0] == 1933
73 # A president who takes office in a year is the president of that year.
74 assert [parties[y] for y in (1980, 1981, 1992, 1993, 2008, 2009, 2020, 2021, 2025)] == [
75 -1, 1, 1, -1, 1, -1, 1, -1, 1]
76 assert list(politics.presidents(2000, 2002)['year']) == [2000, 2001, 2002]
77 with pytest.raises(ValueError, match = 'knows the party'):
78 politics.presidents(1900)
79 with pytest.raises(ValueError, match = 'knows the party'):
80 politics.presidents(end = parties.index[-1] + 1)
83def test_presidents_reads_its_file(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
84 # The terms come from a file, to which a president can be added.
85 terms = pd.read_csv(politics._PRESIDENTS_FILE)
86 added = pd.DataFrame({'president': ['Next'], 'party': [-1], 'start_date': ['2029-01-20'], 'end_date': ['2033-01-20']})
87 path = tmp_path / 'presidents.csv'
88 pd.concat([terms, added]).to_csv(path, index = False)
89 monkeypatch.setattr(politics, '_PRESIDENTS_FILE', path)
90 table = politics.presidents(2028)
91 assert table.to_dict('list') == {'year': [2028, 2029, 2030, 2031, 2032], 'president_party': [1, -1, -1, -1, -1]}
92 assert table['president_party'].dtype == 'Int64'
95def test_executives() -> None:
96 table = politics.executives()
97 assert list(table.columns) == ['executive_name', 'executive_ideology', 'start_date', 'end_date']
98 assert table['start_date'].is_monotonic_increasing
99 # Each term ends when the next begins.
100 assert (table['end_date'].iloc[:-1].to_numpy() == table['start_date'].iloc[1:].to_numpy()).all()
101 assert table.iloc[0]['executive_name'] == 'Franklin D. Roosevelt'
102 assert set(table['executive_ideology']) == {-1, 1}
105def test_legislatures(members: pd.DataFrame) -> None:
106 table = politics.legislatures(members)
107 assert list(table.columns) == ['congress', 'start_date', 'end_date', 'senate_ideology', 'house_ideology']
108 assert list(table['congress']) == [97, 98]
109 assert list(table['start_date'].dt.strftime('%Y-%m-%d')) == ['1981-01-03', '1983-01-03']
110 assert list(table['end_date'].dt.strftime('%Y-%m-%d')) == ['1983-01-03', '1985-01-03']
111 assert list(table['senate_ideology']) == pytest.approx([0.1, 0.2])
112 assert list(table['house_ideology']) == pytest.approx([0.1, -0.3])
113 # Before the Twentieth Amendment, a Congress first met on March 4.
114 assert politics._first_day(73) == '1933-03-04'
117def test_high_courts(scores: pd.DataFrame) -> None:
118 table = politics.high_courts(scores)
119 assert list(table.columns) == ['term', 'start_date', 'end_date', 'high_court_ideology']
120 assert list(table['start_date'].dt.strftime('%Y-%m-%d')) == ['2020-10-01', '2021-10-01']
121 assert list(table['end_date'].dt.strftime('%Y-%m-%d')) == ['2021-09-30', '2022-09-30']
122 assert list(table['high_court_ideology']) == [0.961, 1.004]
125def test_add_executive() -> None:
126 cases = pd.DataFrame({
127 'date_filed': ['2009-01-19', '2009-01-20', '2017-06-01', None, '1900-01-01'],
128 'x': [1, 2, 3, 4, 5]}, index = pd.Index(list('abcde'), name = 'case_id'))
129 dataset = courtpy.code(cases.copy(), 'add_executive')
130 assert isinstance(dataset, courtpy.Cases)
131 data = dataset.data
132 # The day of an inauguration has the new president.
133 assert list(data['executive_name'].iloc[:3]) == ['George W. Bush', 'Barack Obama', 'Donald J. Trump']
134 assert list(data['executive_ideology'].iloc[:3]) == [1, -1, 1]
135 assert data['executive_name'].iloc[3:].isna().all()
136 assert list(data.index) == list('abcde')
137 record = dataset.history[-1]
138 assert (record['rows'], record['matched']) == (5, 3)
139 # Another table of executives, and another column of dates.
140 governors = pd.DataFrame({
141 'executive_name': ['A', 'B'], 'executive_ideology': [1, -1],
142 'start_date': ['2000-01-01', '2004-01-01'], 'end_date': ['2004-01-01', '2008-01-01']})
143 data = politics.AddExecutive().apply(
144 amos.Dataset(pd.DataFrame({'decided': ['2005-05-05']})), source = governors, date = 'decided',
145 prefix = 'state_', indicator = 'known').data
146 assert data.iloc[0].to_dict() == {
147 'decided': '2005-05-05', 'state_executive_name': 'B', 'state_executive_ideology': -1, 'known': True}
148 with pytest.raises(KeyError, match = 'date_filed'):
149 politics.AddExecutive().apply(amos.Dataset(pd.DataFrame({'x': [1]})))
150 with pytest.raises(KeyError, match = 'start_date'):
151 politics.AddExecutive().apply(
152 amos.Dataset(pd.DataFrame({'date_filed': ['2000-01-01']})), source = governors.drop(columns = 'start_date'))
155def test_add_legislature_and_high_court(scores: pd.DataFrame, members: pd.DataFrame) -> None:
156 cases = pd.DataFrame({'date_filed': ['1981-06-01', '1983-01-02', '1983-01-03', '2021-09-30', '2021-10-01']})
157 data = politics.AddLegislature().apply(amos.Dataset(cases.copy()), source = politics.legislatures(members)).data
158 # A Congress sits until the next one first meets.
159 assert list(data['senate_ideology']) == pytest.approx([0.1, 0.1, 0.2, float('nan'), float('nan')], nan_ok = True)
160 assert list(data['house_ideology'].iloc[:3]) == pytest.approx([0.1, 0.1, -0.3])
161 data = politics.AddHighCourt().apply(amos.Dataset(cases.copy()), source = politics.high_courts(scores)).data
162 # A term runs from October to September.
163 assert pd.isna(data['high_court_ideology'].iloc[0])
164 assert list(data['high_court_ideology'].iloc[3:]) == [0.961, 1.004]
167def test_add_legislature_downloads_its_source(site: Site, monkeypatch: pytest.MonkeyPatch) -> None:
168 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
169 cases = pd.DataFrame({'date_filed': ['1984-05-01']})
170 data = courtpy.code(cases, ['add_legislature', 'add_high_court']).data
171 assert data.loc[0, 'house_ideology'] == pytest.approx(-0.3)
172 assert pd.isna(data.loc[0, 'high_court_ideology'])
175def test_martin_quinn(scores: pd.DataFrame) -> None:
176 table = politics.martin_quinn(scores)
177 assert list(table.columns) == [
178 'year', 'supreme_court_median', 'supreme_court_min', 'supreme_court_max']
179 assert list(table['year']) == [2020, 2021]
180 # Each term's scores are summaries of those of its justices.
181 assert list(table['supreme_court_median']) == [0.961, 1.004]
182 assert list(table['supreme_court_min']) == [0.3, 1.004]
183 assert list(table['supreme_court_max']) == [3.0, 1.004]
184 with pytest.raises(KeyError, match = 'Martin-Quinn'):
185 politics.martin_quinn(scores.drop(columns = 'post_mn'))
188def test_justices(scores: pd.DataFrame, tmp_path: pathlib.Path) -> None:
189 path = tmp_path / 'justices.csv'
190 scores.to_csv(path, index = False)
191 table = politics.justices(path)
192 assert list(table.columns) == ['term', 'justice', 'justiceName', 'martin_quinn', 'jcs']
193 assert list(table['martin_quinn']) == [0.961, 1.004, 0.3, 3.0]
194 # judicial-common-space puts the scores on the scale of the Judicial
195 # Common Space, which is from -1 to 1, in the same order.
196 common = table['jcs'].to_numpy()
197 assert (abs(common) < 1).all()
198 assert list(table['jcs'].rank()) == list(table['martin_quinn'].rank())
199 with pytest.raises(KeyError, match = 'Martin-Quinn'):
200 politics.justices(scores.drop(columns = 'post_mn'))
201 # The scores have the Supreme Court Database's numbers for the justices,
202 # so a merger adds them to its votes.
203 votes = pd.DataFrame({'term': [2021, 2020, 2019], 'justice': [117, 111, 117], 'vote': [1, 2, 1]})
204 merged = amos.mergers.MergeKeys().apply(votes, source = table, on = ['term', 'justice'])
205 assert merged.data['martin_quinn'].tolist()[:2] == [1.004, 0.3]
206 assert pd.isna(merged.data['martin_quinn'].iloc[2])
207 assert merged.history[-1]['matched'] == 2
210def test_nominate(members: pd.DataFrame) -> None:
211 table = politics.nominate(members)
212 assert list(table.columns) == ['year', 'senate_median', 'house_median']
213 # The 97th Congress sat in 1981 and 1982, and the 98th in 1983 and 1984.
214 assert list(table['year']) == [1981, 1982, 1983, 1984]
215 assert list(table['senate_median']) == pytest.approx([0.1, 0.1, 0.2, 0.2])
216 assert list(table['house_median']) == pytest.approx([0.1, 0.1, -0.3, -0.3])
217 assert list(politics.nominate(members, score = 'nominate_dim2')['senate_median']) == [0.5, 0.5, 0.3, 0.3]
218 with pytest.raises(KeyError, match = 'members of Congress'):
219 politics.nominate(members, score = 'no_such_score')
222def test_download(site: Site, tmp_path: pathlib.Path) -> None:
223 paths = politics.download(tmp_path / 'scores', session = site)
224 assert list(paths) == ['justices', 'congress']
225 assert [p.name for p in paths.values()] == ['justices.csv', 'HSall_members.csv']
226 assert all(p.is_file() for p in paths.values())
227 # judicial-common-space keeps the files in the "politics" folder of the
228 # folder.
229 assert {p.parent for p in paths.values()} == {tmp_path / 'scores' / 'politics'}
230 # The Martin-Quinn file is found by its link on its page.
231 assert site.urls == [MQ_PAGE, MQ_JUSTICES, VOTEVIEW]
232 # Files that are there are not downloaded again unless asked.
233 politics.download(tmp_path / 'scores', session = site)
234 assert len(site.urls) == 3
235 politics.download(tmp_path / 'scores', kinds = 'congress', overwrite = True, session = site)
236 assert site.urls[3:] == [VOTEVIEW]
237 assert list(politics.download(tmp_path / 'one', kinds = ['justices'], session = site)) == ['justices']
238 # The default folder is outside of any project.
239 assert politics.download(session = site)['congress'].parent == (
240 courtpy.utilities.data_folder() / 'politics')
243def test_download_fails_clearly(site: Site, tmp_path: pathlib.Path) -> None:
244 with pytest.raises(ValueError, match = 'kinds'):
245 politics.download(tmp_path, kinds = 'presidents', session = site)
246 site.pages[MQ_PAGE] = '<a href="media/2024/court.csv">court.csv</a>'
247 with pytest.raises(ValueError, match = "no link to 'justices.csv'"):
248 politics.download(tmp_path, kinds = 'justices', session = site)
249 assert not (tmp_path / 'politics' / 'justices.csv').exists()
250 with pytest.raises(RuntimeError, match = '503'):
251 politics.download(tmp_path, session = Site(site.pages, status = 503))
254def test_build_table(scores: pd.DataFrame, members: pd.DataFrame, tmp_path: pathlib.Path) -> None:
255 assert politics.build_table(False, False).equals(politics.presidents())
256 path = tmp_path / 'justices.csv'
257 scores.to_csv(path, index = False)
258 table = politics.build_table(path, members).set_index('year')
259 assert list(table.columns) == [
260 'president_party', 'supreme_court_median', 'supreme_court_min',
261 'supreme_court_max', 'senate_median', 'house_median']
262 assert table.index.is_monotonic_increasing and table.index.is_unique
263 assert table.loc[2020, 'supreme_court_median'] == 0.961
264 assert table.loc[1981, 'senate_median'] == pytest.approx(0.1)
265 assert pd.isna(table.loc[1981, 'supreme_court_median'])
266 assert table.loc[1981, 'president_party'] == 1
267 assert 'house_median' not in politics.build_table(scores, False).columns
270def test_build_table_downloads_its_sources(site: Site, monkeypatch: pytest.MonkeyPatch) -> None:
271 # With no files, the sources' current files are downloaded, once.
272 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
273 table = politics.build_table().set_index('year')
274 assert table.loc[2020, 'supreme_court_median'] == 0.961
275 assert table.loc[1983, 'house_median'] == pytest.approx(-0.3)
276 assert site.headers == {'User-Agent': courtpy.options._USER_AGENT}
277 folder = courtpy.utilities.data_folder() / 'politics'
278 assert sorted(p.name for p in folder.iterdir()) == ['HSall_members.csv', 'justices.csv']
279 asked = len(site.urls)
280 assert politics.build_table(True, True).set_index('year').equals(table)
281 assert len(site.urls) == asked
282 assert list(politics.justices()['justice']) == [117, 117, 111, 108]
285def test_load_and_download_politics(site: Site, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
286 assert amos.library.classify('load_politics') == 'reference_loader'
287 assert amos.library.classify('download_politics') == 'reference_loader'
288 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
289 dataset = politics.DownloadPolitics().apply(None, source = str(tmp_path))
290 table = dataset.data.set_index('year')
291 assert table.loc[2020, 'supreme_court_median'] == 0.961
292 assert table.loc[1983, 'house_median'] == pytest.approx(-0.3)
293 assert sorted(p.name for p in (tmp_path / 'politics').iterdir()) == [
294 'HSall_members.csv', 'justices.csv']
295 asked = len(site.urls)
296 only = politics.DownloadPolitics().apply(None, source = str(tmp_path), congress = 'false')
297 assert 'house_median' not in only.data.columns
298 assert len(site.urls) == asked
299 politics.DownloadPolitics().apply(
300 None, source = str(tmp_path), supreme_court = False, refresh = True)
301 assert site.urls[asked:] == [VOTEVIEW]
302 # The table is made from the current files, or is a saved one.
303 loaded = politics.LoadPolitics().apply(None, congress = 'false')
304 assert 'supreme_court_median' in loaded.data.columns
305 assert 'house_median' not in loaded.data.columns
306 path = tmp_path / 'years.csv'
307 table.reset_index().to_csv(path, index = False)
308 saved = politics.LoadPolitics().apply(None, source = str(path))
309 assert list(saved.data.columns) == ['year', *table.columns]
310 assert saved.history[-1]['source'] == str(path)