Coverage for tests/references/test_scdb.py: 100%
168 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 scdb module."""
3from __future__ import annotations
5import io
6import pathlib
7import zipfile
9import amos
10import pandas as pd
11import pytest
12from conftest import Site, make_cluster, make_opinion, write_case
14import courtpy
15from courtpy import scdb
17PAGE = 'https://scdb.la.psu.edu/data/'
18RELEASE = 'https://scdb.la.psu.edu/data/2026-release-01/'
19CASES = 'https://scdb.la.psu.edu/?jet_download=aaa'
20VOTES = 'https://scdb.la.psu.edu/?jet_download=ccc'
21# The database's page lists its releases, the latest first, and the page of
22# a release links to its files with the same words for both kinds of data.
23RELEASES = (
24 '<h2>Latest Releases</h2>'
25 f'<a href="{RELEASE}">2026 Release 01</a>'
26 '<a href="https://scdb.la.psu.edu/data/scdb-legacy-07/">SCDB Legacy 07</a>'
27 '<a href="https://scdb.la.psu.edu/data/2025-release-01/">2025 Release 01</a>')
28FILES = (
29 '<h3>Case Centered Data</h3>'
30 f'<a href="{CASES}"><span>Download CSV Organized by Supreme Court Citation</span>'
31 '<span>File size: 698 KB</span></a>'
32 '<a href="https://scdb.la.psu.edu/?jet_download=bbb">Download DTA Organized by Supreme Court Citation</a>'
33 '<a href="https://scdb.la.psu.edu/?jet_download=ddd">Download CSV Organized by Docket</a>'
34 '<h3>Justice Centered Data</h3>'
35 f'<a href="{VOTES}">Download CSV Organized by Supreme Court Citation</a>')
36# Invented cases, in the layout of the database's case centered file. The
37# last two are short orders on one page of each reporter.
38ROWS = [
39 ('1953-069', '347 U.S. 483', '74 S. Ct. 686', '98 L. Ed. 873', 1953, 'BROWN v. BOARD', 2, 2, 9, 0),
40 ('2007-059', '554 U.S. 570', '128 S. Ct. 2783', '171 L. Ed. 2d 637', 2007, 'D.C. v. HELLER', 2, 1, 5, 4),
41 ('2025-068', None, '146 S. Ct. 1873', '225 L. Ed. 2d 342', 2025, 'MCCARTHY v. HERNANDEZ', 1, 1, 6, 3),
42 ('1960-101', '365 U.S. 1', '81 S. Ct. 1', '5 L. Ed. 2d 1', 1960, 'ROE v. ONE', 9, 2, 9, 0),
43 ('1960-102', '365 U.S. 1', '81 S. Ct. 1', '5 L. Ed. 2d 1', 1960, 'ROE v. TWO', 9, 1, 9, 0)]
44COLUMNS = [
45 'caseId', 'usCite', 'sctCite', 'ledCite', 'term', 'caseName', 'issueArea',
46 'decisionDirection', 'majVotes', 'minVotes']
49def table() -> pd.DataFrame:
50 """Returns the invented cases as the database's table of them."""
51 return pd.DataFrame(ROWS, columns = COLUMNS)
54def justices() -> pd.DataFrame:
55 """Returns two invented votes in each of the invented cases."""
56 votes = table().loc[table().index.repeat(2)].reset_index(drop = True)
57 return votes.assign(
58 justice = [111, 117] * len(ROWS),
59 justiceName = ['JGRoberts', 'ACBarrett'] * len(ROWS),
60 vote = [1, 2] * len(ROWS))
63def archive(data: pd.DataFrame, name: str, encoding: str = 'utf-8') -> bytes:
64 """Returns a zip archive of a table, as the database's files are."""
65 buffer = io.BytesIO()
66 with zipfile.ZipFile(buffer, 'w') as file:
67 file.writestr(name, data.to_csv(index = False).encode(encoding))
68 return buffer.getvalue()
71@pytest.fixture
72def site() -> Site:
73 """Returns a session that serves the database's pages and files."""
74 return Site({
75 PAGE: RELEASES,
76 RELEASE: FILES,
77 CASES: archive(table(), 'SCDB_2026_01_caseCentered_Citation.csv'),
78 VOTES: archive(justices(), 'SCDB_2026_01_justiceCentered_Citation.csv')})
81def test_technique_is_in_the_library() -> None:
82 assert amos.library.classify('add_scdb') == 'merger'
85def test_download(site: Site, tmp_path: pathlib.Path) -> None:
86 paths = scdb.download(tmp_path / 'files', session = site)
87 assert list(paths) == ['cases', 'votes']
88 # A file is named for its release.
89 assert [p.name for p in paths.values()] == [
90 'SCDB_2026_01_caseCentered_Citation.csv.zip',
91 'SCDB_2026_01_justiceCentered_Citation.csv.zip']
92 # The latest release is found once, and each file by its link.
93 assert site.urls == [PAGE, RELEASE, CASES, VOTES]
94 # Files that are there are not looked for again unless asked.
95 assert scdb.download(tmp_path / 'files', session = site) == paths
96 assert len(site.urls) == 4
97 scdb.download(tmp_path / 'files', kinds = 'votes', overwrite = True, session = site)
98 assert site.urls[4:] == [PAGE, RELEASE, VOTES]
99 assert list(scdb.download(tmp_path / 'one', kinds = ['cases'], session = site)) == ['cases']
100 # The default folder is outside of any project.
101 assert scdb.download(session = site)['cases'].parent == courtpy.utilities.data_folder() / 'scdb'
104def test_download_uses_the_latest_release(site: Site, tmp_path: pathlib.Path) -> None:
105 earlier = tmp_path / 'SCDB_2025_01_caseCentered_Citation.csv.zip'
106 earlier.write_bytes(archive(table().iloc[:1], 'SCDB_2025_01_caseCentered_Citation.csv'))
107 assert scdb.download(tmp_path, kinds = 'cases', session = site)['cases'] == earlier
108 assert site.urls == []
109 latest = scdb.download(tmp_path, kinds = 'cases', overwrite = True, session = site)['cases']
110 assert latest.name == 'SCDB_2026_01_caseCentered_Citation.csv.zip'
111 assert earlier.is_file()
112 assert scdb.download(tmp_path, kinds = 'cases', session = site)['cases'] == latest
115def test_download_fails_clearly(site: Site, tmp_path: pathlib.Path) -> None:
116 with pytest.raises(ValueError, match = 'kinds'):
117 scdb.download(tmp_path, kinds = 'dockets', session = site)
118 # A page whose first link is not to the case centered data.
119 site.pages[CASES] = site.pages[VOTES]
120 with pytest.raises(ValueError, match = 'caseCentered_Citation'):
121 scdb.download(tmp_path, kinds = 'cases', session = site)
122 site.pages[CASES] = b'not a zip archive'
123 with pytest.raises(ValueError, match = 'caseCentered_Citation'):
124 scdb.download(tmp_path, kinds = 'cases', session = site)
125 assert list(tmp_path.iterdir()) == []
126 site.pages[RELEASE] = '<a href="x">Download CSV Organized by Docket</a>'
127 with pytest.raises(ValueError, match = 'does not link'):
128 scdb.download(tmp_path, session = site)
129 site.pages[PAGE] = '<a href="https://scdb.la.psu.edu/data/scdb-legacy-07/">SCDB Legacy 07</a>'
130 with pytest.raises(ValueError, match = 'no release'):
131 scdb.download(tmp_path, session = site)
132 with pytest.raises(RuntimeError, match = '503'):
133 scdb.download(tmp_path, session = Site(site.pages, status = 503))
136def test_cases_and_votes(site: Site, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None:
137 paths = scdb.download(tmp_path, session = site)
138 cases = scdb.cases(paths['cases'])
139 assert list(cases.columns) == COLUMNS
140 assert list(cases['caseId']) == [row[0] for row in ROWS]
141 assert cases.loc[1, 'decisionDirection'] == 1
142 votes = scdb.votes(paths['votes'])
143 assert len(votes) == 2 * len(ROWS)
144 assert {'justice', 'justiceName', 'vote'} <= set(votes.columns)
145 assert scdb.cases(cases) is not cases and scdb.cases(cases).equals(cases)
146 # Earlier releases were not in UTF-8.
147 named = table().assign(caseName = 'PEÑA v. BOARD')
148 old = tmp_path / 'old.zip'
149 old.write_bytes(archive(named, 'old.csv', encoding = 'cp1252'))
150 assert scdb.cases(old)['caseName'].iloc[0] == 'PEÑA v. BOARD'
151 # With no file, the latest release is used, and downloaded once.
152 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
153 asked = len(site.urls)
154 assert scdb.cases().equals(cases)
155 assert site.urls[asked:] == [PAGE, RELEASE, CASES]
156 assert scdb.cases().equals(cases)
157 assert len(site.urls) == asked + 3
160def test_add_scdb() -> None:
161 data = pd.DataFrame({
162 'scdb_id': ['2007-059', None, None, '1953-069', '9999-001', None],
163 'citation': [
164 'ignored', '74 S.Ct. 686; 98 L.Ed. 873', ['146 S. Ct. 1873'], None,
165 '554 U.S. 570', '365 U.S. 1'],
166 'year': [2008, 1954, 2026, 1954, 2008, 1961]}, index = list('abcdef'))
167 dataset = scdb.AddScdb().apply(
168 amos.Dataset(data.copy()), source = table(), indicator = 'in_scdb',
169 columns = 'caseId, issueArea, decisionDirection')
170 result = dataset.data
171 assert list(result.index) == list(data.index)
172 assert list(result.columns) == [
173 'scdb_id', 'citation', 'year', 'scdb_caseId', 'scdb_issueArea',
174 'scdb_decisionDirection', 'in_scdb']
175 # A case is matched by its id, or else by a citation. An id that is not
176 # in the database leaves the citation to match by, and a citation that
177 # two cases share matches neither.
178 assert list(result['scdb_caseId'].iloc[:5]) == [
179 '2007-059', '1953-069', '2025-068', '1953-069', '2007-059']
180 assert list(result['in_scdb']) == [True, True, True, True, True, False]
181 assert pd.isna(result.loc['f', 'scdb_issueArea'])
182 assert result.loc['a', 'scdb_decisionDirection'] == 1
183 record = dataset.history[0]
184 assert (record['technique'], record['rows'], record['matched']) == ('add_scdb', 6, 5)
185 # By default, every column of the database is added.
186 everything = scdb.AddScdb().apply(amos.Dataset(data.copy()), source = table()).data
187 assert [c for c in everything.columns if c.startswith('scdb_') and c != 'scdb_id'] == [
188 f'scdb_{c}' for c in COLUMNS]
191def test_add_scdb_keys() -> None:
192 # Either the ids or the citations are enough, under any names.
193 ids = pd.DataFrame({'spaeth': ['1953-069', None]})
194 result = scdb.AddScdb().apply(
195 amos.Dataset(ids), source = table(), on = 'spaeth', columns = 'term').data
196 assert result['scdb_term'].tolist()[0] == 1953 and pd.isna(result['scdb_term'].iloc[1])
197 cites = pd.DataFrame({'cites': [['1 F.2d 3', '347 U. S. 483'], [], None]})
198 result = scdb.AddScdb().apply(
199 amos.Dataset(cites), source = table(), citations = 'cites', columns = 'term',
200 prefix = None).data
201 assert result['term'].tolist()[0] == 1953 and result['term'].iloc[1:].isna().all()
202 with pytest.raises(KeyError, match = 'scdb_id'):
203 scdb.AddScdb().apply(amos.Dataset(pd.DataFrame({'year': [2000]})), source = table())
204 with pytest.raises(KeyError, match = 'caseId'):
205 scdb.AddScdb().apply(amos.Dataset(ids.rename(columns = {'spaeth': 'scdb_id'})), source = table()[['term']])
206 with pytest.raises(KeyError, match = 'no_such'):
207 scdb.AddScdb().apply(amos.Dataset(ids), source = table(), on = 'spaeth', columns = 'no_such')
210def test_add_scdb_with_court_listener(
211 site: Site,
212 tmp_path: pathlib.Path,
213 monkeypatch: pytest.MonkeyPatch) -> None:
214 # CourtListener records the database's id of a case of the Supreme Court,
215 # which becomes a column of the parsed cases.
216 folder = tmp_path / 'data' / 'courtlistener'
217 write_case(
218 folder,
219 make_cluster(
220 7, scdb_id = '2007-059', case_name = 'District of Columbia v. Heller',
221 citations = [{'volume': 554, 'reporter': 'U.S.', 'page': '570', 'type': 1}]),
222 [make_opinion(71, 7)], court = 'scotus')
223 write_case(
224 folder,
225 make_cluster(
226 8, scdb_id = '', case_name = 'McCarthy v. Hernandez',
227 citations = [{'volume': 146, 'reporter': 'S. Ct.', 'page': '1873', 'type': 1}]),
228 [make_opinion(81, 8)], court = 'scotus')
229 parsed = courtpy.parse(folder)
230 assert list(parsed['scdb_id'].fillna('')) == ['2007-059', '']
231 # As one of a loader's coders, it uses the latest release, which it
232 # downloads, and the history records the release.
233 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
234 dataset = courtpy.loaders.LoadCourtlistener().apply(
235 None, source = folder, coders = 'code_outcome, add_scdb', label = 'outcome_reversal')
236 assert list(dataset.data['scdb_caseName']) == ['D.C. v. HELLER', 'MCCARTHY v. HERNANDEZ']
237 assert list(dataset.data['scdb_majVotes']) == [5, 6]
238 record = dataset.history[-1]
239 assert record['source'].endswith('SCDB_2026_01_caseCentered_Citation.csv.zip')
240 assert (record['rows'], record['matched']) == (2, 2)
243def test_other_cases_have_no_id(court_listener_folder: pathlib.Path) -> None:
244 assert 'scdb_id' not in courtpy.parse(court_listener_folder).columns
247def test_add_scdb_in_a_wrangler(
248 court_listener_folder: pathlib.Path,
249 tmp_path: pathlib.Path) -> None:
250 # A file of the database that the settings name is found as the clerk
251 # finds files: in the input folder.
252 folder = tmp_path / 'data' / 'courtlistener'
253 folder.parent.mkdir()
254 court_listener_folder.rename(folder)
255 cited = table().assign(usCite = ['950 F.3d 12', *table()['usCite'].iloc[1:]])
256 (tmp_path / 'data' / 'mine.zip').write_bytes(archive(cited, 'mine.csv'))
257 settings = tmp_path / 'study.ini'
258 settings.write_text(
259 '[general]\n'
260 'label = outcome_reversal\n'
261 '[files]\n'
262 'input_folder = data\n'
263 '[court_project]\n'
264 'court_workers = wrangler\n'
265 '[wrangler]\n'
266 'techniques = load_courtlistener, add_scdb\n'
267 '[add_scdb_parameters]\n'
268 'source = mine.zip\n'
269 'columns = issueArea, majVotes\n'
270 'indicator = found\n', encoding = 'utf-8')
271 result = courtpy.Project.create(settings, clerk = tmp_path).result
272 # All three cases have the citation that was given to the table's first
273 # row.
274 assert list(result.data['found']) == [True, True, True]
275 assert list(result.data['scdb_issueArea']) == [2, 2, 2]
276 assert result.history[-1]['source'] == 'mine.zip'
279def test_load_and_download_scdb(site: Site, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None:
280 assert amos.library.classify('load_scdb') == 'reference_loader'
281 assert amos.library.classify('download_scdb') == 'reference_loader'
282 monkeypatch.setattr(courtpy.utilities.requests, 'Session', lambda: site)
283 folder = str(tmp_path / 'files')
284 dataset = scdb.DownloadScdb().apply(None, source = folder, kind = 'votes')
285 assert len(dataset.data) == 2 * len(ROWS)
286 assert site.urls == [PAGE, RELEASE, VOTES]
287 # A file that is there is not looked for again unless asked.
288 scdb.DownloadScdb().apply(None, source = folder, kind = 'votes')
289 assert len(site.urls) == 3
290 scdb.DownloadScdb().apply(None, source = folder, kind = 'votes', refresh = 'true')
291 assert site.urls[3:] == [PAGE, RELEASE, VOTES]
292 # A file of the database, or the latest release that was downloaded.
293 path = scdb.download(folder, kinds = 'cases', session = site)['cases']
294 loaded = scdb.LoadScdb().apply(None, source = str(path))
295 assert list(loaded.data['caseId']) == [row[0] for row in ROWS]
296 assert loaded.history[-1]['source'] == str(path)
297 current = scdb.LoadScdb().apply(None)
298 assert current.data.equals(loaded.data)
299 assert current.history[-1]['source'] == 'current'
300 with pytest.raises(ValueError, match = 'kind'):
301 scdb.LoadScdb().apply(None, kind = 'dockets')
302 with pytest.raises(ValueError, match = 'kind'):
303 scdb.DownloadScdb().apply(None, kind = 'dockets')