Coverage for tests/references/test_jcs.py: 100%
89 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 jcs module."""
3from __future__ import annotations
5import io
6import pathlib
7import zipfile
9import amos
10import pandas as pd
11import pytest
12from conftest import Site
14import courtpy
15from courtpy import jcs, politics
17PAGE = 'https://epstein.wustl.edu/jcs'
18ARCHIVE = 'https://epstein.wustl.edu/s/JCS2024.zip'
19JUDGES = pd.DataFrame({
20 '': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
21 'name': [
22 'Lynch, Mary Ann', 'Smith, Milton D., Jr.', 'Smith, N. Roy',
23 'Fiélds, Ray Lanier, III', 'Fields, Ray Lanier, III', 'Woods, Dana',
24 'Kerner, Otto, Jr.', 'Kerner, Otto', 'Lynhc, Mary', 'Nobody, Ann'],
25 'circuit': [1, 9, 9, 5, 11, 1, 7, 7, 1, 1],
26 'jcs': [-0.4, 0.5, 0.6, -0.1, -0.1, 0.2, -0.3, -0.3, -0.4, 0.0]})
27JUSTICES = pd.DataFrame({
28 '': [1, 2, 3],
29 'term': [2020, 2021, 2022],
30 'justiceName': ['ACBarrett', 'ACBarrett', 'ACBarrett'],
31 'jcs': [0.43, 0.44, 0.39]})
32MEDIANS = pd.DataFrame({
33 '': [1, 2, 3],
34 'year': [1924, 1924, 1925],
35 'term': [None, None, None],
36 'congress': [68, 68, 69],
37 'president': [0.4, 0.44, 0.4],
38 'house_median': [0.2, 0.2, 0.26],
39 'senate_median': [0.22, 0.22, 0.22],
40 'sc_median': [None, None, 0.1],
41 'circuit_median3': [0.43, 0.43, 0.43],
42 'circuit_sd3': [None, None, 0.1]})
45def archive(skipped: str | None = None) -> bytes:
46 """Returns an archive of scores in the layout of the 2024 release."""
47 contents = {
48 'coa_judges_2024': JUDGES,
49 'jcs medians': MEDIANS,
50 'jcs_supreme_court_2024_long': JUSTICES,
51 'jcs_supreme_court_2024_wide': pd.DataFrame({'justiceName': ['ACBarrett']})}
52 buffer = io.BytesIO()
53 with zipfile.ZipFile(buffer, 'w') as packed:
54 for name, table in contents.items():
55 if name == skipped:
56 continue
57 csv = table.to_csv(index = False).encode('utf-8')
58 packed.writestr(f'jcs 2024/csv/{name}.csv', csv)
59 packed.writestr(f'jcs 2024/stata/{name}.dta', b'not a csv')
60 # The hidden files that a Mac adds have the same names.
61 packed.writestr(f'__MACOSX/jcs 2024/csv/._{name}.csv', b'\x00\x05')
62 return buffer.getvalue()
65@pytest.fixture
66def site() -> Site:
67 """Returns a session that serves the page and archive of scores."""
68 return Site({
69 PAGE: (
70 '<html><body><a href="/s/JCS.pdf">here</a> for the article. '
71 '<a href="/s/JCS2024.zip">here</a> for the data.</body></html>'),
72 ARCHIVE: archive()})
75def test_download(site: Site, tmp_path: pathlib.Path) -> None:
76 # judicial-common-space keeps the files in the "jcs" folder of the folder.
77 paths = jcs.download(tmp_path, session = site)
78 assert list(paths) == ['judges', 'justices', 'medians']
79 assert [p.name for p in paths.values()] == ['judges.csv', 'justices.csv', 'medians.csv']
80 assert {p.parent for p in paths.values()} == {tmp_path / 'jcs'}
81 assert (tmp_path / 'jcs' / 'JCS2024.zip').is_file()
82 # The archive is found by its link on the page.
83 assert site.urls == [PAGE, ARCHIVE]
84 assert pd.read_csv(paths['justices'])['justiceName'].tolist() == ['ACBarrett'] * 3
85 # Files that are there are not downloaded again unless asked.
86 jcs.download(tmp_path, session = site)
87 assert len(site.urls) == 2
88 jcs.download(tmp_path, kinds = 'judges', overwrite = True, session = site)
89 assert site.urls[2:] == [PAGE, ARCHIVE]
90 assert list(jcs.download(tmp_path, kinds = ['medians'], session = site)) == ['medians']
91 # The default folder is outside of any project.
92 assert jcs.download(session = site)['judges'].parent == courtpy.utilities.data_folder() / 'jcs'
95def test_download_identifies_courtpy(site: Site, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
96 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
97 jcs.download(tmp_path)
98 assert site.headers == {'User-Agent': courtpy.options._USER_AGENT}
101def test_download_fails_clearly(site: Site, tmp_path: pathlib.Path) -> None:
102 with pytest.raises(ValueError, match = 'kinds'):
103 jcs.download(tmp_path, kinds = 'presidents', session = site)
104 site.pages[ARCHIVE] = archive(skipped = 'jcs medians')
105 with pytest.raises(ValueError, match = 'no CSV file of medians'):
106 jcs.download(tmp_path, session = site)
107 site.pages[PAGE] = '<a href="/s/JCS.pdf">here</a>'
108 with pytest.raises(ValueError, match = 'no link to an archive'):
109 jcs.download(tmp_path / 'other', session = site)
110 with pytest.raises(RuntimeError, match = '503'):
111 jcs.download(tmp_path / 'third', session = Site(site.pages, status = 503))
114def test_medians(site: Site, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
115 path = tmp_path / 'medians.csv'
116 MEDIANS.to_csv(path, index = False)
117 table = jcs.medians(path).set_index('year')
118 assert list(table.columns) == [
119 'jcs_president', 'jcs_house_median', 'jcs_senate_median',
120 'jcs_supreme_court_median', 'jcs_circuit3_median', 'jcs_circuit3_sd']
121 # A year with two rows has their means.
122 assert table.loc[1924, 'jcs_president'] == pytest.approx(0.42)
123 assert pd.isna(table.loc[1924, 'jcs_supreme_court_median'])
124 assert table.loc[1925, 'jcs_circuit3_sd'] == 0.1
125 with pytest.raises(KeyError, match = 'year'):
126 jcs.medians(MEDIANS.drop(columns = 'year'))
127 # Without a file, the current one is downloaded.
128 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
129 assert jcs.medians().equals(jcs.medians(path))
130 assert site.urls == [PAGE, ARCHIVE]
133def test_build_table_adds_medians() -> None:
134 table = politics.build_table(False, False, common_space = MEDIANS).set_index('year')
135 assert 'jcs_house_median' in table.columns and 'president_party' in table.columns
136 assert table.loc[1933, 'president_party'] == -1
137 assert table.loc[1925, 'jcs_house_median'] == 0.26
140def test_download_jcs(site: Site, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
141 assert amos.library.classify('download_jcs') == 'reference_loader'
142 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
143 medians = jcs.DownloadJcs().apply(None, source = str(tmp_path))
144 assert medians.data.equals(jcs.medians(tmp_path / 'jcs' / 'medians.csv'))
145 justices = jcs.DownloadJcs().apply(None, source = str(tmp_path), kind = 'justices')
146 assert justices.data['justiceName'].tolist() == ['ACBarrett'] * 3
147 assert site.urls == [PAGE, ARCHIVE]
148 jcs.DownloadJcs().apply(None, source = str(tmp_path), refresh = 'true')
149 assert site.urls[2:] == [PAGE, ARCHIVE]
150 with pytest.raises(ValueError, match = 'kinds'):
151 jcs.DownloadJcs().apply(None, source = str(tmp_path), kind = 'presidents')