Coverage for tests/references/test_fjc_idb.py: 100%
221 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 fjc_idb module."""
3from __future__ import annotations
5import pathlib
6from typing import Any
8import amos
9import fjc_idb
10import fjc_idb.main
11import pandas as pd
12import pytest
13from conftest import make_cluster, make_opinion
15import courtpy
16from courtpy import fjc_idb as idb
18# Invented appeals, in the layout of fjc-idb's parsed table of appeals. The
19# D.C. Circuit's appeal was remanded by the Supreme Court and ended twice,
20# and the Fifth and Eleventh Circuits each have an appeal 18-11574.
21APPEALS = [
22 ('First Circuit', '0801234', 'No. 08-1234', None, '2008-03-01', '2009-05-01', 'Criminal', 1),
23 ('First Circuit', '1701234', 'No. 17-1234', None, '2017-03-01', '2018-05-01', 'Criminal', 1),
24 ('D.C. Circuit', '1507034', 'No. 15-7034', None, '2015-04-08', '2019-05-14', 'U.S. civil', 1),
25 ('D.C. Circuit', '1507034', 'No. 15-7034', 'Remanded from the Supreme Court', '2020-06-03', '2020-08-18', 'U.S. civil', 0),
26 ('Second Circuit', '1803672', 'No. 18-3672', None, '2018-11-01', '2019-06-03', 'Private civil', 0),
27 ('Second Circuit', '1803701', 'No. 18-3701', None, '2018-11-05', '2019-06-03', 'Private civil', 0),
28 ('Fifth Circuit', '1811574', 'No. 18-11574', None, '2018-10-01', '2019-07-03', 'Criminal', 0),
29 ('Eleventh Circuit', '1811574', 'No. 18-11574', None, '2018-04-11', '2019-05-09', 'Prisoner', 0)]
30COLUMNS = [
31 'circuit', 'docket_num_idb', 'docket_number', 'reopened_or_remanded',
32 'docket_date', 'judgment_date', 'appeal_type', 'published']
35def table() -> pd.DataFrame:
36 """Returns the invented appeals as fjc-idb's table of them."""
37 data = pd.DataFrame(APPEALS, columns = COLUMNS)
38 for column in ('docket_date', 'judgment_date'):
39 data[column] = pd.to_datetime(data[column])
40 return data
43def cases(**columns: list[Any]) -> amos.Dataset:
44 """Returns a dataset of parsed cases with the columns given."""
45 return amos.Dataset(pd.DataFrame(columns))
48def save(folder: pathlib.Path, number: int, court: str, docket: str, date: str) -> None:
49 """Saves a CourtListener case with a docket, as the bulk data does."""
50 cluster = make_cluster(number, date_filed = date)
51 path = courtpy.courtlistener.case_path(folder, court, cluster['id'])
52 courtpy.courtlistener.save_case(path, {
53 'source': 'courtlistener',
54 'court': {'id': court, 'full_name': f'Court of Appeals ({court})'},
55 'cluster': cluster,
56 'docket': {'id': number * 10, 'court_id': court, 'docket_number': docket},
57 'citations': [],
58 'opinions': [courtpy.courtlistener.slim_opinion(make_opinion(number * 10, number))]})
61def test_add_idb_is_a_merger() -> None:
62 assert amos.library.classify('add_idb') == 'merger'
65def test_add_idb() -> None:
66 dataset = cases(
67 court = ['ca1', 'ca5', 'ca11', 'ca2', 'cafc', 'scotus', 'ca1'],
68 docket_number = [
69 '17-1234', '18-11574', 'No. 18-11574', '18-9999-cv, 18-3701-cv',
70 '2018-1234', '17-1234', None],
71 date_filed = [
72 '2018-05-01', '2019-07-03', '2019-05-09', '2019-06-03',
73 '2019-01-01', '2019-01-01', '2018-05-01'])
74 result = idb.AddIdb().apply(dataset, source = table(), indicator = 'found')
75 data = result.data
76 assert list(data['found']) == [True, True, True, True, False, False, False]
77 assert list(data['idb_circuit'].iloc[:4]) == [
78 'First Circuit', 'Fifth Circuit', 'Eleventh Circuit', 'Second Circuit']
79 # The first docket number that the database has is used.
80 assert data['idb_docket_number'].iloc[3] == 'No. 18-3701'
81 assert data['idb_appeal_type'].iloc[2] == 'Prisoner'
82 assert data['idb_judgment_date'].iloc[:5].isna().tolist() == [False] * 4 + [True]
83 assert [c for c in data.columns if c.startswith('idb_')] == [f'idb_{c}' for c in COLUMNS]
84 record = result.history[-1]
85 assert (record['technique'], record['source'], record['rows'], record['matched']) == (
86 'add_idb', 'DataFrame', 7, 4)
89def test_add_idb_to_dockets() -> None:
90 cases = courtpy.Cases.create(pd.DataFrame({
91 'case_id': ['a', 'b'],
92 'court': ['ca2', 'ca1'],
93 'docket_number': ['18-9999-cv, 18-3701-cv', '17-1234'],
94 'date_filed': ['2019-06-03', '2018-05-01']}))
95 dockets = courtpy.code(cases, ['cases_to_dockets'])
96 assert isinstance(dockets, courtpy.Dockets)
97 assert list(dockets.data['docket']) == ['18-9999', '18-3701', '17-1234']
98 result = idb.AddIdb().apply(dockets, source = table(), indicator = 'found')
99 data = result.data
100 # Each docket is matched by its own number only, so the docket that the
101 # database lacks is not given its sibling's record.
102 assert list(data['found']) == [False, True, True]
103 assert data.loc['a-2', 'idb_docket_number'] == 'No. 18-3701'
104 assert pd.isna(data.loc['a-1', 'idb_docket_number'])
105 assert result.history[-1]['matched'] == 2
106 # Made cases again, each case has its first docket's record.
107 back = courtpy.code(result, ['dockets_to_cases'])
108 assert isinstance(back, courtpy.Cases)
109 assert back.data.loc['a', 'docket_numbers'] == '18-9999; 18-3701'
110 assert pd.isna(back.data.loc['a', 'idb_docket_number'])
113def test_reopened_appeals() -> None:
114 dataset = cases(
115 court = ['cadc'] * 4,
116 docket_number = ['15-7034'] * 4,
117 date_filed = ['2016-01-01', '2019-05-14', '2020-08-18', '2021-03-01'])
118 result = idb.AddIdb().apply(dataset, source = table(), columns = 'judgment_date')
119 # The record whose judgment is nearest the decision is used.
120 assert [str(d.date()) for d in result.data['idb_judgment_date']] == [
121 '2019-05-14', '2019-05-14', '2020-08-18', '2020-08-18']
122 # A record of an appeal docketed after the decision is never used.
123 remand = table().drop(index = 2)
124 result = idb.AddIdb().apply(
125 cases(court = ['cadc'], docket_number = ['15-7034'], date_filed = ['2019-05-14']),
126 source = remand, indicator = 'found')
127 assert list(result.data['found']) == [False]
128 # Without dates, the latest record is used.
129 result = idb.AddIdb().apply(
130 cases(court = ['cadc'], docket_number = ['15-7034']),
131 source = table(), columns = 'reopened_or_remanded')
132 assert result.data['idb_reopened_or_remanded'].iloc[0] == 'Remanded from the Supreme Court'
135def test_rules_columns() -> None:
136 # Cases from Lexis-Nexis have the federal rules' numbers for the courts
137 # (12 is the D.C. Circuit and 13 the Federal Circuit) and years.
138 dataset = cases(
139 court_num = [12, 1, 13, None],
140 docket_numbers = [['15-7034'], ['17-1234', '17-1235'], ['18-1234'], ['17-1234']],
141 year = [2019, 2018, 2019, 2018])
142 result = idb.AddIdb().apply(
143 dataset, source = table(), columns = ['judgment_date'], indicator = 'found')
144 assert list(result.data['found']) == [True, True, False, False]
145 assert str(result.data['idb_judgment_date'].iloc[0].date()) == '2019-05-14'
148def test_needed_columns() -> None:
149 with pytest.raises(KeyError, match = 'courts'):
150 idb.AddIdb().apply(cases(docket_number = ['17-1234']), source = table())
151 with pytest.raises(KeyError, match = 'docket numbers'):
152 idb.AddIdb().apply(cases(court = ['ca1']), source = table())
153 with pytest.raises(KeyError, match = 'docket_num_idb'):
154 idb.AddIdb().apply(
155 cases(court = ['ca1'], docket_number = ['17-1234']),
156 source = table().drop(columns = ['docket_number', 'docket_num_idb']))
159def test_a_csv_file(tmp_path: pathlib.Path) -> None:
160 # The CSV file that the fjc-idb command makes keeps the docket numbers
161 # that begin with 0, and its dates are read as dates.
162 path = tmp_path / 'fjc_idb_appellate_data_2008_2026.csv'
163 table().drop(columns = 'docket_number').to_csv(path, index = False)
164 read = idb.AddIdb().read(path)
165 assert read['docket_num_idb'].iloc[0] == '0801234'
166 assert pd.api.types.is_datetime64_any_dtype(read['judgment_date'])
167 result = idb.AddIdb().apply(
168 cases(court = ['ca1'], docket_number = ['08-1234'], date_filed = ['2009-05-01']),
169 source = path, columns = 'appeal_type', indicator = 'found')
170 assert list(result.data['found']) == [True]
171 assert result.history[-1]['source'] == str(path)
174def test_years_of_the_cases(monkeypatch: pytest.MonkeyPatch) -> None:
175 calls: list[tuple[Any, ...]] = []
177 def appeals(start: int, stop: int, folder: Any, **kwargs: Any) -> pd.DataFrame:
178 calls.append((start, stop, folder, kwargs))
179 return table()
181 monkeypatch.setattr(idb, 'appeals', appeals)
182 dataset = cases(
183 court = ['ca1', 'cadc', 'scotus'],
184 docket_number = ['17-1234', '15-7034', '1'],
185 date_filed = ['2018-05-01', '2019-05-14', '1950-01-01'])
186 result = idb.AddIdb().apply(dataset, district = 'false', download = 'no')
187 # The years begin with the database's first and end with the year after
188 # the latest decision.
189 assert calls[-1] == (2008, 2020, None, {'district': False, 'download': False})
190 assert result.history[-1]['source'] == 'FJC IDB appeals, 2008-2020'
191 idb.AddIdb().apply(
192 cases(court = ['ca1'], docket_number = ['17-1234'], date_filed = ['2018-05-01']),
193 district = True, folder = '~/idb')
194 assert calls[-1][:3] == (2018, 2019, pathlib.Path('~/idb').expanduser())
195 assert calls[-1][3]['district'] is True
196 with pytest.raises(ValueError, match = 'begin in 2008'):
197 idb.AddIdb().apply(
198 cases(court = ['ca1'], docket_number = ['05-1234'], date_filed = ['2005-06-01']))
201def test_download(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
202 calls: list[tuple[Any, ...]] = []
204 def download(kind: str, start: int, stop: int, root: pathlib.Path, **kwargs: Any) -> list[pathlib.Path]:
205 calls.append((kind, start, stop, root, kwargs))
206 return [root / f'{kind}{start}']
208 monkeypatch.setattr(fjc_idb, 'download', download)
209 appellate = tmp_path / 'appellate'
210 appellate.mkdir()
211 (appellate / 'ap17.sas7bdat').touch()
212 (appellate / 'ap18_0.sas7bdat').touch()
213 # Only the years that are missing are asked for.
214 assert idb.download(2017, 2020, tmp_path) == [tmp_path / 'appellate2019']
215 assert calls == [('appellate', 2019, 2020, tmp_path, {'overwrite': False})]
216 calls.clear()
217 idb.download(2017, 2018, tmp_path)
218 assert calls == []
219 idb.download(2017, 2018, tmp_path, district = True, overwrite = True)
220 assert [call[:3] for call in calls] == [
221 ('appellate', 2017, 2018), ('civil', 2017, 2018), ('criminal', 2017, 2018)]
222 # The years begin with the database's first.
223 calls.clear()
224 idb.download(2000, 2008, tmp_path)
225 assert calls[0][:3] == ('appellate', 2008, 2008)
226 with pytest.raises(ValueError, match = 'begin in 2008'):
227 idb.download(2000, 2005, tmp_path)
230def test_default_folder(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
231 calls: list[pathlib.Path] = []
232 monkeypatch.setenv('COURTPY_DATA_DIR', str(tmp_path))
233 monkeypatch.setattr(
234 fjc_idb, 'download',
235 lambda kind, start, stop, root, **kwargs: calls.append(root) or [])
236 idb.download(2019, 2019)
237 assert calls == [tmp_path / 'fjc_idb']
240def test_appeals(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
241 calls: list[tuple[Any, ...]] = []
242 monkeypatch.setattr(
243 fjc_idb.main, 'import_data',
244 lambda *args: calls.append(('import', *args)) or 'imported')
245 monkeypatch.setattr(
246 fjc_idb.main, 'parse_data',
247 lambda data, kind, **kwargs: calls.append(('parse', data, kind, kwargs)) or table())
248 monkeypatch.setattr(
249 fjc_idb, 'merge_district',
250 lambda *args, **kwargs: calls.append(('merge', *args, kwargs)) or table())
251 monkeypatch.setattr(
252 fjc_idb, 'download',
253 lambda *args, **kwargs: calls.append(('download', *args[:3])) or [])
254 assert idb.appeals(2017, 2018, tmp_path, download = False).equals(table())
255 assert calls == [
256 ('import', 'appellate', 2017, 2018, tmp_path / 'appellate'),
257 ('parse', 'imported', 'appellate', {'fix_city_spellings': True})]
258 calls.clear()
259 idb.appeals(2017, 2018, tmp_path, district = True)
260 assert calls == [
261 ('download', 'appellate', 2017, 2018),
262 ('download', 'civil', 2017, 2018),
263 ('download', 'criminal', 2017, 2018),
264 ('merge', 2017, 2018, tmp_path, {'fix_city_spellings': True, 'export': False})]
267def test_add_idb_in_a_wrangler(tmp_path: pathlib.Path) -> None:
268 # A file of the database that the settings name is found as the clerk
269 # finds files: in the input folder.
270 folder = tmp_path / 'data' / 'courtlistener'
271 save(folder, 1, 'ca2', '18-3672-cv, 18-3701-cv', '2019-06-03')
272 save(folder, 2, 'cadc', '15-7034', '2020-08-18')
273 save(folder, 3, 'cafc', '2019-1234', '2019-06-03')
274 table().to_csv(tmp_path / 'data' / 'appeals.csv', index = False)
275 settings = tmp_path / 'study.ini'
276 settings.write_text(
277 '[files]\n'
278 'input_folder = data\n'
279 '[court_project]\n'
280 'court_workers = wrangler\n'
281 '[wrangler]\n'
282 'techniques = load_courtlistener, add_idb\n'
283 '[add_idb_parameters]\n'
284 'source = appeals.csv\n'
285 'columns = appeal_type, judgment_date\n'
286 'indicator = in_idb\n', encoding = 'utf-8')
287 result = courtpy.Project.create(settings, clerk = tmp_path).result
288 assert list(result.data['in_idb']) == [True, True, False]
289 assert list(result.data['idb_appeal_type'].iloc[:2]) == ['Private civil', 'U.S. civil']
290 assert str(result.data['idb_judgment_date'].iloc[1].date()) == '2020-08-18'
291 assert result.history[-1]['source'] == 'appeals.csv'
294def test_load_and_download_idb(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None:
295 assert amos.library.classify('load_idb') == 'reference_loader'
296 assert amos.library.classify('download_idb') == 'reference_loader'
297 calls: list[tuple[Any, ...]] = []
298 monkeypatch.setattr(
299 idb, 'appeals',
300 lambda start, stop, folder, **kwargs: calls.append(('appeals', start, stop, folder, kwargs)) or table())
301 monkeypatch.setattr(
302 idb, 'download',
303 lambda start, stop, folder, **kwargs: calls.append(('download', start, stop, folder, kwargs)) or [])
304 # Settings are text, and with no source the current files are used.
305 dataset = idb.LoadIdb().apply(None, start_year = '2017', stop_year = 2018, district = 'no')
306 assert dataset.data.equals(table())
307 assert calls == [('appeals', 2017, 2018, None, {
308 'district': False, 'download': True, 'fix_city_spellings': True})]
309 calls.clear()
310 idb.DownloadIdb().apply(None, source = str(tmp_path), start_year = 2017, refresh = 'true')
311 assert calls == [
312 ('download', 2017, None, tmp_path, {'district': False, 'overwrite': True}),
313 ('appeals', 2017, None, tmp_path, {
314 'district': False, 'download': False, 'fix_city_spellings': True})]
317# Invented merits appeals for `compare_with_idb`: the First Circuit's 17-1237
318# and the Second Circuit's 18-0001 are missing from the cases below, 18-0004
319# was not decided on the merits, and 18-0005 was judged after every case.
320COMPARED = pd.DataFrame({
321 'circuit': ['First Circuit'] * 4 + ['Second Circuit'] * 5,
322 'docket_number': [
323 'No. 17-1234', 'No. 17-1235', 'No. 17-1236', 'No. 17-1237',
324 'No. 18-1', 'No. 18-2', 'No. 18-3', 'No. 18-4', 'No. 18-5'],
325 'docket_date': pd.to_datetime(['2017-01-01'] * 9),
326 'judgment_date': pd.to_datetime([
327 '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01', '2018-05-01',
328 '2018-06-01', '2018-12-01', '2018-06-01', '2019-02-01']),
329 'appeal_type': ['19', '4', '19', '3', '21', '4', '4', '4', '4'],
330 'disposition': ['1', '2', '1', '6', '1', '2', '3', None, '2'],
331 'published': [1, 0, 0, 1, 0, 1, 1, 0, 0],
332 'dissents': [0, 1, 0, 0, 0, 0, 0, 0, 0],
333 'district_of_origin': ['D. Mass.'] * 4 + ['S.D.N.Y.'] * 5})
336def compared_cases() -> courtpy.Cases:
337 """Returns cases to compare with `COMPARED`."""
338 return courtpy.Cases.create(pd.DataFrame({
339 'case_id': ['a', 'b', 'c'],
340 'court': ['ca1', 'ca1', 'ca2'],
341 'docket_number': ['17-1234, 17-1235', '17-1236', '18-2, 18-3'],
342 'date_filed': ['2018-05-01', '2018-07-01', '2018-12-01'],
343 'type_criminal': [True, True, False],
344 'type_civil': [False, False, True],
345 'outcome_reversal': [False, True, True],
346 'published': ['True', 'False', None]}))
349def test_compare_with_idb_is_a_describer() -> None:
350 assert amos.library.classify('compare_with_idb') == 'describer'
353def test_compare_with_idb_agreement() -> None:
354 cases = compared_cases()
355 result = idb.CompareWithIdb().apply(cases, source = COMPARED)
356 # The cases stay cases, though they are compared as dockets.
357 assert result is cases and isinstance(result, courtpy.Cases)
358 table = result.tables['compare_with_idb']
359 # The data lacks "dissents" and the parties' columns, so those are left out.
360 assert list(table.index) == ['criminal', 'civil', 'reversal', 'published']
361 criminal = table.loc['criminal']
362 # 17-1235 is criminal in the data and civil in the database.
363 assert (criminal['dockets'], criminal['compared'], criminal['matches']) == (5, 5, 4)
364 assert (criminal['data_only'], criminal['idb_only']) == (1, 0)
365 reversal = table.loc['reversal']
366 # 17-1234 (affirmed) is no reversal in either, and 17-1235 (reversed) is
367 # no reversal in the data; 17-1236 is affirmed but a reversal in the
368 # data; 18-2 (reversed) and 18-3 (affirmed and reversed in part) are both.
369 assert (reversal['both_true'], reversal['both_false']) == (2, 1)
370 assert (reversal['data_only'], reversal['idb_only']) == (1, 1)
371 assert reversal['match_share'] == pytest.approx(0.6)
372 published = table.loc['published']
373 # Case c's two dockets have no value, so they are not compared.
374 assert (published['compared'], published['data_missing']) == (3, 2)
375 assert published['kappa'] == pytest.approx(0.4)
376 # Cohen's kappa of criminal: 0.8 agree, and 0.48 would by chance.
377 assert criminal['kappa'] == pytest.approx((0.8 - 0.48) / 0.52)
378 record = result.history[-1]
379 assert (record['dockets'], record['matched'], record['idb_appeals'], record['in_data']) == (
380 5, 5, 7, 5)
383def test_compare_with_idb_missing() -> None:
384 result = idb.CompareWithIdb().apply(
385 compared_cases(), source = COMPARED, report = ['reversal', 'published'])
386 table = result.tables['compare_with_idb_missing']
387 assert list(table['group'].unique()) == ['All', 'First Circuit', 'Second Circuit']
388 row = table.set_index(['group', 'variable']).loc['All', 'reversal']
389 # Seven merits appeals are in the cases' circuits and dates, and the cases
390 # have five of them.
391 assert (row['appeals'], row['in_data']) == (7, 5)
392 assert row['coverage'] == pytest.approx(5 / 7)
393 # The missing appeals (17-1237, remanded, and 18-1, affirmed) are half
394 # reversals, and three of the five that the data has are.
395 assert row['share_in_data'] == pytest.approx(0.6)
396 assert row['share_missing'] == pytest.approx(0.5)
397 assert row['difference'] == pytest.approx(0.1)
398 assert 0 < row['p_value'] <= 1
399 # Every appeal the database has, decided on the merits or not.
400 every = idb.CompareWithIdb().apply(
401 compared_cases(), source = COMPARED, merits_only = False, by = 'district')
402 table = every.tables['compare_with_idb_missing']
403 assert list(table['group'].unique()) == ['All', 'D. Mass.', 'S.D.N.Y.']
404 assert table.set_index(['group', 'variable']).loc[('All', 'criminal'), 'appeals'] == 8
407def test_compare_with_idb_variables() -> None:
408 cases = compared_cases()
409 table = idb.CompareWithIdb().describe(
410 cases, source = COMPARED, variables = {'criminal_code': 'type_criminal, appeal_type'})
411 assert list(table.index) == ['criminal_code']
412 with pytest.raises(KeyError, match = 'dissent'):
413 idb.CompareWithIdb().describe(cases, source = COMPARED, variables = 'dissent')
414 with pytest.raises(KeyError, match = 'unknown'):
415 idb.CompareWithIdb().describe(cases, source = COMPARED, variables = 'nope')
416 with pytest.raises(KeyError, match = 'merits_only'):
417 idb.CompareWithIdb().describe(cases, source = COMPARED.drop(columns = 'disposition'))
420def test_compare_with_idb_figures() -> None:
421 pytest.importorskip('matplotlib')
422 result = idb.CompareWithIdb().apply(compared_cases(), source = COMPARED, visualize = True)
423 record = result.history[-1]
424 assert (record['figure'], record['missing_figure']) == (
425 'compare_with_idb', 'compare_with_idb_missing')
426 matrices = result.figures['compare_with_idb']
427 assert [a.get_title() for a in matrices.axes if a.get_visible()][0] == 'criminal (κ = 0.62)'
428 differences = result.figures['compare_with_idb_missing']
429 labels = [t.get_text() for t in differences.axes[0].get_yticklabels()]
430 assert labels[0] == 'All (71% in data)'