Coverage for tests/sources/test_bulk.py: 96%
98 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 downloading cases from the bulk data with `CourtListener`."""
3from __future__ import annotations
5import bz2
6import csv
7import io
8import json
9import pathlib
10from typing import Any
12import pytest
13from conftest import FakeResponse
15import courtpy
16from courtpy import courtlistener
18DATE = '2026-09-30'
19OPINION_HTML = (
20 '<p>The defendant said "I did not" before trial.\nWe reverse.</p>'
21 '<p>See 18 U.S.C. \\u00a7 922.</p>')
24def write_bulk(folder: pathlib.Path, kind: str, header: list[str], rows: list[list[Any]]) -> None:
25 """Writes a bulk file the way PostgreSQL does, with backslash escapes."""
26 text = io.StringIO()
27 writer = csv.writer(text, escapechar = '\\', doublequote = False, lineterminator = '\n')
28 writer.writerow(header)
29 writer.writerows(rows)
30 folder.mkdir(parents = True, exist_ok = True)
31 (folder / f'{kind}-{DATE}.csv.bz2').write_bytes(bz2.compress(text.getvalue().encode('utf-8')))
34class LocalBucket:
35 """A session that serves the bulk files in a folder and lists them."""
37 def __init__(self, folder: pathlib.Path) -> None:
38 self.folder = folder
39 self.headers: dict[str, str] = {}
41 def head(self, url: str, **kwargs: Any) -> Any:
42 path = self.folder / url.rsplit('/', 1)[-1]
43 response = FakeResponse({}, 200, {'Content-Length': str(path.stat().st_size)})
44 response.raise_for_status = lambda: None
45 return response
47 def get(self, url: str, params: dict[str, Any] | None = None, **kwargs: Any) -> Any:
48 keys = ''.join(
49 f'<Contents><Key>bulk-data/{p.name}</Key></Contents>'
50 for p in sorted(self.folder.glob('*.bz2'))
51 if p.name.startswith((params or {}).get('prefix', '').removeprefix('bulk-data/')))
52 response = FakeResponse({}, 200)
53 response.content = (
54 '<?xml version="1.0" encoding="UTF-8"?>'
55 '<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
56 f'{keys}<IsTruncated>false</IsTruncated></ListBucketResult>').encode()
57 response.raise_for_status = lambda: None
58 return response
61@pytest.fixture
62def bucket(tmp_path: pathlib.Path) -> pathlib.Path:
63 folder = tmp_path / 'bulk'
64 write_bulk(folder, 'courts', ['id', 'full_name', 'short_name', 'citation_string', 'jurisdiction', 'notes'], [
65 ['ca1', 'Court of Appeals for the First Circuit', 'First Circuit', '1st Cir.', 'F', ''],
66 ['ca2', 'Court of Appeals for the Second Circuit', 'Second Circuit', '2d Cir.', 'F', '']])
67 write_bulk(folder, 'dockets', [
68 'id', 'date_modified', 'court_id', 'docket_number', 'docket_number_core', 'case_name_full',
69 'date_argued', 'cause', 'blocked', 'idb_data_id', 'appeal_from_id', 'view_count'], [
70 [10, '2026-01-01 10:00:00+00', 'ca1', '19-1234', '1901234', 'United States v. Doe',
71 '2020-01-15', '', 'f', 77, 'mad', 5],
72 [20, '', 'ca2', '19-9999', '1909999', 'Other v. Case', '', '', 'f', '', '', 0],
73 [30, '', 'ca1', '18-0001', '1800001', 'Old v. Case', '', '', 'f', '', '', 0]])
74 write_bulk(folder, 'opinion-clusters', [
75 'id', 'judges', 'date_filed', 'case_name', 'case_name_full', 'attorneys', 'disposition',
76 'precedential_status', 'docket_id', 'citation_count', 'blocked', 'date_created'], [
77 [1, 'Lynch, Howard, Thompson', '2020-03-04', 'United States v. Doe',
78 'UNITED STATES, Appellee, v. John DOE, Appellant', 'Assistant United States Attorney',
79 '', 'Published', 10, 3, 'f', '2020-03-05 10:00:00+00'],
80 [2, 'Pooler', '2020-05-05', 'Other v. Case', '', '', '', 'Published', 20, 0, 'f', ''],
81 [3, 'Selya', '2018-02-02', 'Old v. Case', '', '', '', 'Published', 30, 0, 'f', '']])
82 write_bulk(folder, 'citations', ['id', 'volume', 'reporter', 'page', 'type', 'cluster_id'], [
83 [1, 950, 'F.3d', 12, 1, 1], [2, 1, 'F.4th', 2, 1, 2]])
84 write_bulk(folder, 'opinions', [
85 'id', 'author_str', 'per_curiam', 'type', 'plain_text', 'html_with_citations', 'cluster_id'], [
86 [11, 'Lynch', 'f', '010combined', '', OPINION_HTML, 1],
87 [12, 'Howard', 'f', '040dissent', 'I dissent.', '', 1],
88 [21, 'Pooler', 't', '010combined', 'Other text.', '', 2]])
89 return folder
92def test_rows_read_postgres_csv(bucket: pathlib.Path) -> None:
93 data = courtlistener.CourtListener(bulk_folder = bucket, bulk_date = DATE, session = LocalBucket(bucket))
94 opinions = list(data.read_bulk_rows('opinions'))
95 assert opinions[0]['html_with_citations'] == OPINION_HTML
96 assert opinions[2]['per_curiam'] == 't'
97 chosen = list(data.read_bulk_rows('dockets', columns = ['id'], keep = {'court_id': ['ca1']}))
98 assert chosen == [{'id': '10'}, {'id': '30'}]
101def test_available_and_latest(bucket: pathlib.Path) -> None:
102 data = courtlistener.CourtListener(bulk_folder = bucket, session = LocalBucket(bucket))
103 assert data.bulk_dates('opinions') == [DATE]
104 assert data.bulk_dates('opinion-clusters') == [DATE]
105 assert data.resolve_bulk_date() == DATE
108def test_download_from_bulk_data(bucket: pathlib.Path, tmp_path: pathlib.Path) -> None:
109 data = courtlistener.CourtListener(bulk_folder = bucket, bulk_date = DATE, session = LocalBucket(bucket))
110 output = tmp_path / 'cases'
111 saved = data.download('ca1', '2019-01-01', '2020-12-31', output)
112 assert saved == [output / 'ca1' / '1.json']
113 record = json.loads(saved[0].read_text(encoding = 'utf-8'))
114 assert record['bulk_date'] == DATE
115 assert record['court']['citation_string'] == '1st Cir.'
116 assert record['docket'] == {
117 'id': 10, 'court_id': 'ca1', 'docket_number': '19-1234', 'docket_number_core': '1901234',
118 'case_name_full': 'United States v. Doe', 'date_argued': '2020-01-15', 'cause': None,
119 'blocked': False, 'idb_data_id': 77, 'appeal_from_id': 'mad'}
120 assert record['citations'] == ['950 F.3d 12']
121 assert record['cluster']['citation_count'] == 3
122 assert record['cluster']['blocked'] is False
123 assert 'date_created' not in record['cluster']
124 assert [o['id'] for o in record['opinions']] == [11, 12]
125 assert record['opinions'][1] == {
126 'id': 12, 'cluster_id': 1, 'type': '040dissent', 'author_str': 'Howard',
127 'per_curiam': False, 'plain_text': 'I dissent.'}
128 # Cases that were saved with their opinions are skipped the next time.
129 assert data.download('ca1', '2019-01-01', '2020-12-31', output) == []
130 table = courtpy.parse(output)
131 assert table.loc['1', 'docket_number'] == '19-1234'
132 assert table.loc['1', 'date_argued'] == '2020-01-15'
133 assert table.loc['1', 'dissenting'] == 'HOWARD'
134 assert table.loc['1', 'opinion_reverse']
137def test_fetch_resumes_partial_download(bucket: pathlib.Path, tmp_path: pathlib.Path) -> None:
138 source = bucket / f'courts-{DATE}.csv.bz2'
139 content = source.read_bytes()
141 class Remote(LocalBucket):
142 def get(self, url: str, headers: dict[str, str] | None = None, **kwargs: Any) -> Any:
143 start = int((headers or {}).get('Range', 'bytes=0-')[6:-1])
144 response = FakeResponse({}, 206 if start else 200)
145 response.raise_for_status = lambda: None
146 response.iter_content = lambda chunk_size: [content[start:]]
147 return response
149 local = tmp_path / 'downloads'
150 local.mkdir()
151 (local / f'courts-{DATE}.csv.bz2.part').write_bytes(content[:10])
152 data = courtlistener.CourtListener(bulk_folder = local, bulk_date = DATE, session = Remote(bucket))
153 path = data.fetch_bulk_file('courts')
154 assert path.read_bytes() == content
155 assert not (local / f'courts-{DATE}.csv.bz2.part').exists()
158def test_unknown_kind(bucket: pathlib.Path) -> None:
159 data = courtlistener.CourtListener(bulk_folder = bucket, bulk_date = DATE, session = LocalBucket(bucket))
160 with pytest.raises(ValueError, match = 'kind must be one of'):
161 list(data.read_bulk_rows('people'))