Coverage for tests/wrangler/test_rules.py: 100%
194 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 rules module: courtpy's rulebooks."""
3from __future__ import annotations
5import csv
6import pathlib
7import re
8from typing import Any
10import amos
11import pandas as pd
12import pytest
14from courtpy import parsers, rules
17def apply(name: str, **sections: str) -> dict[str, Any]:
18 """Applies a rulebook to the sections of one case.
20 Args:
21 name: the name of the rulebook.
22 **sections: the sections of text, by name.
24 Returns:
25 The columns that the rules made, with `None` for missing values.
27 """
28 table = pd.DataFrame({k: [v] for k, v in sections.items()}, dtype = 'str')
29 _, made = parsers._apply(amos.parsers.Rulebook.create(name), table)
30 return {
31 k: None if pd.isna(v) else v for k, v in made.iloc[0].to_dict().items()}
34def test_rulebooks_are_named() -> None:
35 assert amos.library.classify('parse_federal') == 'parser'
36 federal = amos.parsers.Rulebook.create('federal')
37 assert len(federal) == len(amos.parsers.Rulebook.create(rules.RULEBOOKS['federal']))
38 assert len(amos.parsers.Rulebook.create('lexis_nexis')) > 10
39 with pytest.raises(FileNotFoundError, match = 'federal'):
40 amos.parsers.Rulebook.create('no_such_rules')
43def test_rule_files_are_general_then_federal() -> None:
44 general, federal = rules._GENERAL, rules._INSTRUCTIONS / 'federal'
45 assert rules.find_rule_files('criminal') == [
46 general / 'criminal.csv', federal / 'criminal.csv']
47 assert rules.find_rule_files('citations') == [general / 'citations.csv']
48 assert rules.find_rule_files('agencies') == [federal / 'agencies.csv']
49 assert rules.find_rule_files('criminal', None) == [general / 'criminal.csv']
50 with pytest.raises(FileNotFoundError, match = 'no_such_topic'):
51 rules.find_rule_files('no_such_topic')
52 names = amos.parsers.Rulebook.create('criminal').names
53 assert 'criminal_firearm' in names and 'criminal_acca' in names
56def test_register_rulebooks(tmp_path: pathlib.Path) -> None:
57 # A study's folders make a rulebook of each topic, applied in the order
58 # of the folders, and one that combines them.
59 general, texas = tmp_path / 'general', tmp_path / 'texas'
60 general.mkdir()
61 texas.mkdir()
62 header = 'column,name,kind,pattern\n'
63 (general / 'oil.csv').write_text(header + 'opinion,oil_well,flags,well\n', encoding = 'utf-8')
64 (texas / 'oil.csv').write_text(header + 'opinion,oil_rrc,flags,Railroad Commission\n', encoding = 'utf-8')
65 (texas / 'cattle.csv').write_text(header + 'opinion,cattle_brand,flags,brand\n', encoding = 'utf-8')
66 books = rules.register_rulebooks(general, texas, combined = 'texas_all', prefix = 'texas')
67 assert list(books) == ['texas_cattle', 'texas_oil', 'texas_all']
68 assert books['texas_oil'].__name__ == 'ParseTexasOil'
69 assert amos.parsers.Rulebook.create('texas_oil').names == ['oil_well', 'oil_rrc']
70 assert amos.parsers.Rulebook.create('parse_texas_all').names == [
71 'cattle_brand', 'oil_well', 'oil_rrc']
72 assert amos.library.classify('parse_texas_cattle') == 'parser'
73 assert list(rules.register_rulebooks(texas, topics = ['oil'])) == ['oil']
74 with pytest.raises(FileNotFoundError, match = 'sheep'):
75 rules.register_rulebooks(general, topics = ['sheep'])
76 with pytest.raises(FileNotFoundError, match = 'no files of rules'):
77 rules.register_rulebooks(tmp_path / 'empty')
80def test_review_rules() -> None:
81 found = apply(
82 'review',
83 opening_lines = (
84 'Appeal from the United States District Court for the District of '
85 'Massachusetts\n[Hon. William G. Young, U.S. District Judge]'),
86 history = '', party = 'UNITED STATES, Appellee')
87 assert found['review_district'] and not found['review_agency']
88 assert found['district_judges'] == 'WILLIAM G YOUNG'
89 found = apply(
90 'review',
91 opening_lines = 'On Petition for Review of an Order of the Board of Immigration Appeals',
92 history = '', party = 'JOHN DOE, Petitioner')
93 assert found['review_agency'] and found['review_immigration']
94 assert not found['review_district'] and found['district_judges'] is None
95 standards = apply('general', opinion = 'We review for plain error. Substantial evidence supports it.')
96 assert standards['standard_plain_error'] and standards['standard_named']
97 assert standards['standard_substantial_evidence'] and not standards['standard_de_novo']
100def test_structure_files_are_by_source_and_courts() -> None:
101 path = rules.find_structure_file('lexis_nexis', 'federal_appellate')
102 assert path == rules._INSTRUCTIONS / 'sources' / 'lexis_nexis' / 'federal_appellate.csv'
103 with pytest.raises(FileNotFoundError, match = 'state_trial'):
104 rules.find_structure_file('lexis_nexis', 'state_trial')
107def read_rows(path: Any) -> list[dict[str, str]]:
108 """Returns the rows of a CSV file of rules.
110 Args:
111 path: the path of the file.
113 Returns:
114 The rows, as `dict`s by the names of the columns.
116 """
117 with path.open(encoding = 'utf-8-sig', newline = '') as file:
118 return list(csv.DictReader(file))
121def test_federal_files_do_not_repeat_general_rules() -> None:
122 for path in sorted((rules._INSTRUCTIONS / 'federal').glob('*.csv')):
123 general = rules._GENERAL / path.name
124 if general.exists():
125 names = {row['name'] for row in read_rows(general)}
126 repeated = {row['name'] for row in read_rows(path)} & names
127 assert not repeated, (path.name, repeated)
130def test_rules_that_ignore_case_do_not_list_both_cases() -> None:
131 both = re.compile(r'\[([A-Za-z])([A-Za-z])\]')
132 for path in sorted(rules._INSTRUCTIONS.rglob('*.csv')):
133 for row in read_rows(path):
134 # The tables of courts and presidents are not rules.
135 if 'flags' not in row or 'ignorecase' not in row['flags']:
136 continue
137 for first, second in both.findall(row['pattern']):
138 assert first.lower() != second.lower(), (path, row['name'])
141def test_files_named_twice_are_read_once() -> None:
142 both = amos.parsers.Rulebook.create('civil', 'federal')
143 assert len(both) == len(amos.parsers.Rulebook.create('federal'))
146def test_built_in_rulebooks_are_valid() -> None:
147 federal = amos.parsers.Rulebook.create('federal')
148 lexis = amos.parsers.Rulebook.create('lexis_nexis')
149 general_header = amos.parsers.Rulebook.create('header')
150 lexis_header = amos.parsers.Rulebook.create('lexis_nexis_header')
151 courtlistener_header = amos.parsers.Rulebook.create('courtlistener_header')
152 assert len(federal) > 300
153 for variable in (
154 'opinion_reverse', 'criminal_firearm',
155 'civil_titlevii', 'constitutional_amend4', 'citations_case',
156 'citations_statute', 'agencies', 'review_district'):
157 assert variable in federal.names
158 # The header rules are applied by source, not with the federal rules.
159 assert 'party1' not in federal.names and 'panel_judges' not in federal.names
160 shared = (
161 'party1', 'party2', 'panel_judges', 'authors', 'concurring',
162 'dissenting', 'disposition_reverse', 'cite_federal_reporter', 'party1_appellant',
163 'party2_united_states', 'counsel_us_attorney', 'docket_criminal',
164 'party1_agencies', 'party2_agencies', 'history_agencies',
165 'lower_court_num', 'lower_court_name')
166 for book in (general_header, lexis_header, courtlistener_header):
167 for variable in shared:
168 assert variable in book.names
169 for variable in ('court_num', 'court_name', 'notice_unpublished', 'future_grant', 'cite_lexis'):
170 assert variable in lexis_header.names
171 assert variable not in courtlistener_header.names
172 assert 'caption' in courtlistener_header.names and 'caption' not in lexis_header.names
173 assert 'agency' not in lexis_header.names
174 assert lexis.names == [
175 'header', 'opinion', 'party', 'court', 'docket_number', 'history',
176 'future', 'counsel', 'notice', 'dates', 'disposition', 'citation',
177 'judges', 'opinion_by', 'concurring_lines', 'dissenting_lines']
178 # Several values in a cell are separated by "; ", with no line breaks in
179 # the files (which a checkout on Windows would make "\r\n").
180 for rule in [*federal, *lexis, *lexis_header, *courtlistener_header]:
181 if rule.kind in ('names', 'matches'):
182 assert rule.separator == '; '
185def test_lexis_dates_are_lines() -> None:
186 found = apply(
187 'lexis_nexis',
188 text = (
189 '\nA v. B\n\nMarch 3, 2009, Argued\nJune 1, 2009, Decided\n'
190 'JUDGES: Smith.\nOPINION\n\nWe affirm.\n'))
191 assert found['dates'] == 'March 3, 2009, Argued; June 1, 2009, Decided'
194@pytest.mark.parametrize(('judges', 'expected'), [
195 # A middle initial "J." is not "Justice".
196 ('PRESENT: DENNIS JACOBS, SARAH A. L. MERRIAM, Circuit Judges, LAWRENCE '
197 'J. VILARDO, District Judge.',
198 ['DENNIS JACOBS', 'SARAH A L MERRIAM', 'LAWRENCE J VILARDO']),
199 # "JR." after a name is a suffix, and "S.R." before one is initials.
200 ('Present: JOHN M. WALKER, JR., PIERRE N. LEVAL, MICHAEL H. PARK, Circuit '
201 'Judges.', ['JOHN M WALKER', 'PIERRE N LEVAL', 'MICHAEL H PARK']),
202 ('Before: S.R. THOMAS, BRESS, and DE ALBA, Circuit Judges.',
203 ['SR THOMAS', 'BRESS', 'DE ALBA']),
204 # "J." and "JJ." after names are still titles.
205 ('ROBERTS, C. J., delivered the opinion of the Court, in which SCALIA, '
206 'KENNEDY, and THOMAS, JJ., joined. GINSBURG, J., filed a dissenting '
207 'opinion.', ['ROBERTS', 'SCALIA', 'KENNEDY', 'THOMAS', 'GINSBURG']),
208 # CourtListener's list of judges can have words that are not names.
209 ('Agee, Dismissed, King, Per Curiam, Thacker', ['AGEE', 'KING', 'THACKER']),
210 ('Gregory, Keenan, Eastern, Curium', ['GREGORY', 'KEENAN'])])
211def test_header_rules_split_judges(judges: str, expected: list[str]) -> None:
212 found = apply('header', judges = judges)
213 assert found['panel_judges'] == '; '.join(expected)
216@pytest.mark.parametrize(('opening', 'expected'), [
217 ('Before JORDAN, ROSENBAUM, and ABUDU, Circuit Judges. PER CURIAM: Doe '
218 'appeals.', ['JORDAN', 'ROSENBAUM', 'ABUDU']),
219 # A chief judge in the middle, an accent, and a judge by designation.
220 ('Before Barron, Chief Judge, Gelpí and Montecalvo, Circuit Judges. Jane '
221 'Roe, Assistant Federal Public Defender, for appellant.',
222 ['BARRON', 'GELPÍ', 'MONTECALVO']),
223 ('Before: PAEZ and OWENS, Circuit Judges, and SEEBORG,* Chief District '
224 'Judge. Following a trial', ['PAEZ', 'OWENS', 'SEEBORG']),
225 ('Before SYKES, Chief Judge, and BRENNAN and ST. EVE, Cir- cuit Judges. '
226 'BRENNAN, Circuit Judge. Police stopped', ['SYKES', 'BRENNAN', 'ST EVE']),
227 # The Seventh Circuit lists the judges with only spaces between them.
228 ('Decided March 28, 2022 Before JOHN DOE, Circuit Judge AMY J. ST. ROE, '
229 'Circuit Judge RICHARD ROE, Chief Judge No. 21-1819 UNITED STATES OF '
230 'AMERICA, Plaintiff-Appellee, v. JANE DOE, Defendant-Appellant.',
231 ['JOHN DOE', 'AMY J ST ROE', 'RICHARD ROE']),
232 # Not a panel.
233 ('Before April 25, 2016, Sabaini made deposits of over $2,000.', []),
234 ('LYNCH, Circuit Judge. Before trial, Doe moved to suppress.', [])])
235def test_header_rules_find_the_panel_in_the_opinion(
236 opening: str,
237 expected: list[str]) -> None:
238 found = apply('header', opinion = opening)
239 assert found['panel_judges'] == ('; '.join(expected) or None)
242def test_header_rules_prefer_the_panel_in_the_opinion() -> None:
243 # CourtListener's "judges" may name only the author.
244 found = apply(
245 'courtlistener_header',
246 judges = 'Brennan',
247 opinion = 'Before SYKES, Chief Judge, and BRENNAN and ST. EVE, Circuit '
248 'Judges. BRENNAN, Circuit Judge.')
249 assert found['panel_judges'] == 'SYKES; BRENNAN; ST EVE'
252@pytest.mark.parametrize(('opening', 'roles'), [
253 # (party1 appellant, party1 appellee, party2 appellant, party2 appellee)
254 ('In the United States Court of Appeals For the Eleventh Circuit ____ No. '
255 '23-12565 ____ UNITED STATES OF AMERICA, Plaintiff-Appellee, versus JOHN '
256 'DOE, Defendant-Appellant. ____ Appeal from the United States District '
257 'Court', (False, True, True, False)),
258 # The government's appeal, with dashes around "v.".
259 ('UNITED STATES OF AMERICA, Appellant, –v.– JOHN DOE, Defendant-Appellee. '
260 'Before: LYNCH and PARK, Circuit Judges.', (True, False, False, True)),
261 # A short title before the caption.
262 ('22-1481 (L) United States v. Doe UNITED STATES COURT OF APPEALS FOR THE '
263 'SECOND CIRCUIT August Term 2023 Docket No. 22-1481 UNITED STATES OF '
264 'AMERICA, Appellee, v. JOHN DOE, AKA J. DOE, Defendant-Appellant.',
265 (False, True, True, False)),
266 # Docket numbers from another column between the role and "v.".
267 ('UNITED STATES OF AMERICA, No. 23-481 D.C. No. Plaintiff - Appellee, '
268 '3:18-cr-00136-SLG-1 v. MEMORANDUM* JOHN DOE, Jr., Defendant - '
269 'Appellant. Appeal from', (False, True, True, False)),
270 # One role, as the Third Circuit writes captions.
271 ('NOT PRECEDENTIAL UNITED STATES COURT OF APPEALS FOR THE THIRD CIRCUIT '
272 '____ No. 24-1625 ____ UNITED STATES OF AMERICA v. JOHN DOE, a/k/a '
273 'Johnny, Appellant ____ Appeal from the United States District Court',
274 (False, False, True, False)),
275 # A citation and a party in the opinion's words are not a caption.
276 ('LYNCH, Circuit Judge. Under United States v. Booker, 543 U.S. 220 '
277 '(2005), the guidelines are advisory. The appellant argues that the '
278 'district court erred. Appellee United States disagrees.',
279 (False, False, False, False))])
280def test_courtlistener_rules_find_the_caption_in_the_opinion(
281 opening: str,
282 roles: tuple[bool, bool, bool, bool]) -> None:
283 found = apply('courtlistener_header', party = 'United States v. Doe', opinion = opening)
284 assert (
285 found['party1_appellant'], found['party1_appellee'],
286 found['party2_appellant'], found['party2_appellee']) == roles
287 assert (found['caption'] is None) == (roles == (False, False, False, False))
290@pytest.mark.parametrize(('opening', 'expected'), [
291 # The Seventh Circuit's orders print the caption in two columns, so the
292 # district court's name falls between the roles and "v.".
293 ('No. 10-2228 Appeal from the United States District UNITED STATES OF '
294 'AMERICA, Court for the Northern District of Illinois, Plaintiff\u2010'
295 'Appellee, Eastern Division. v. No. 09 CR 78\u20101 JOHN DOE, Jane Roe, '
296 'Defendant\u2010Appellant. Judge. O R D E R John Doe pleaded guilty.',
297 ('Plaintiff\u2010Appellee', True, False, False, False)),
298 # "Appeal from the United States" is the district court, not the party,
299 # even with the other party's name between the words.
300 ('Appeal from the United States JOHN DOE, District Court for the '
301 'Northern Petitioner-Appellant, District of Illinois. v. No. 14-3216 '
302 'UNITED STATES OF AMERICA, Respondent-Appellee.',
303 ('Respondent-Appellee', True, False, False, False)),
304 # A government appeal, with the roles in a caption of numbered lines.
305 ('UNITED STATES OF AMERICA, 13 14 Appellant, 15 16 -v.- 17 18 JOHN DOE, '
306 '19 20 Defendant-Appellee.', ('Appellant', False, True, False, False)),
307 # No caption: the opening's sentences say who appeals.
308 ('PER CURIAM: John Doe, proceeding pro se, appeals from the order '
309 'denying his motion.', (None, False, False, False, True)),
310 ('PER CURIAM: Counsel for John Doe has filed a brief in accordance with '
311 'Anders v. California, 386 U.S. 738 (1967).',
312 (None, False, False, False, True)),
313 ('SMITH, Circuit Judge: Defendant-appellant John Doe asserts that the '
314 'search was unlawful.', (None, True, False, False, False)),
315 ('MEMORANDUM The United States appeals from the sentence imposed on '
316 'John Doe.', (None, False, False, True, False)),
317 # An earlier appeal is not this one, and a citation is not a party.
318 ('The government appealed the sentence, and we reversed. Under United '
319 'States v. Booker, 543 U.S. 220 (2005), the guidelines are advisory.',
320 (None, False, False, False, False))])
321def test_general_rules_find_who_appeals_in_the_opening(
322 opening: str,
323 expected: tuple[str | None, bool, bool, bool, bool]) -> None:
324 found = apply('courtlistener_header', party = 'United States v. Doe', opinion = opening)
325 assert (
326 found['opening_united_states_role'],
327 found['opening_defendant_appellant'],
328 found['opening_defendant_appellee'],
329 found['opening_government_appeals'],
330 found['opening_party_appeals']) == expected
333def test_courtlistener_rules_keep_the_caption_of_the_header() -> None:
334 found = apply(
335 'courtlistener_header',
336 party = 'Mary SMITH, Plaintiff-Appellant, v. ACME CORP., Defendant-Appellee',
337 opinion = 'ACME CORP., Plaintiff-Appellee, v. MARY SMITH, Defendant-Appellant.')
338 assert found['caption'].startswith('Mary SMITH')
339 assert found['party1_appellant'] and found['party2_appellee']
340 assert not found['party1_appellee'] and not found['party2_appellant']
343@pytest.mark.parametrize(('court', 'number', 'name'), [
344 ('UNITED STATES COURT OF APPEALS FOR THE TENTH CIRCUIT', 10, 'tenth_circuit'),
345 # The D.C. Circuit is not the District of Columbia's district court.
346 ('UNITED STATES COURT OF APPEALS FOR THE DISTRICT OF COLUMBIA CIRCUIT', 12, 'dc_circuit'),
347 ('UNITED STATES BANKRUPTCY APPELLATE PANEL OF THE NINTH CIRCUIT', 110,
348 'bankruptcy_appellate_panel_ninth_circuit'),
349 ('TEMPORARY EMERGENCY COURT OF APPEALS', 105, 'temporary_emergency_court_of_appeals'),
350 ('UNITED STATES COURT OF APPEALS FOR THE STATE OF NOWHERE', None, None)])
351def test_lexis_rules_find_the_court(court: str, number: int | None, name: str | None) -> None:
352 found = apply('lexis_nexis_header', court = court)
353 assert (found['court_num'], found['court_name']) == (number, name)
356def test_court_rules_are_made_from_the_table_of_courts() -> None:
357 made = rules.make_court_rules()
358 assert {rule['name'] for rule in made} == {'court_num', 'court_name'}
359 assert {rule['column'] for rule in made} == {'court'}
360 lower = rules.make_court_rules(column = 'history', prefix = 'lower_', levels = ('trial',))
361 assert {rule['name'] for rule in lower} == {'lower_court_num', 'lower_court_name'}
362 assert 'tenth_circuit' not in {rule['value'] for rule in lower}
363 assert rules.make_court_rules('nowhere') == []
366@pytest.mark.parametrize(('history', 'name'), [
367 ('Appeal from the United States District Court for the District of Colorado.',
368 'district_of_colorado'),
369 # Lexis abbreviations, after an earlier appeal that is not the court below.
370 ('(D.C. No. CR 05-0916 JH). (D. New Mexico). United States v. Mora, 262 Fed. '
371 'Appx. 864, 2008 U.S. App. LEXIS 2334 (10th Cir. N.M., 2008)', 'district_of_new_mexico'),
372 ('(D. of Kan.). (D.C. No.08-CR-10010-WEB-1).', 'district_of_kansas'),
373 ('(W.D. Oklahoma). (D.C. No. 5:03-cr-00243-F-1).', 'western_district_of_oklahoma'),
374 ('(D. N.M.). (D.Ct. No. 1:06-CR-01622-MCA-1).', 'district_of_new_mexico'),
375 ('Logan v. Sabre, Inc., 2008 U.S. Dist. LEXIS 37749 (N.D. Okla., May 7, 2008)',
376 'northern_district_of_oklahoma'),
377 ('(BAP No. NO-07-057). (BAP). In re Tollefsen, 397 B.R. 545 (B.A.P. 10th Cir., 2008)',
378 'bankruptcy_appellate_panel_tenth_circuit'),
379 # Only an earlier appeal, or an agency.
380 ('United States v. Collins, 511 F.3d 1276, 2008 U.S. App. LEXIS 174 (10th Cir. Okla., 2008)',
381 None),
382 ('Petition for review of an order of the Board of Immigration Appeals.', None)])
383def test_header_rules_find_the_lower_court(history: str, name: str | None) -> None:
384 found = apply('header', history = history)
385 assert found['lower_court_name'] == name
386 assert (found['lower_court_num'] is None) == (name is None)
389@pytest.mark.parametrize(('party', 'history', 'expected'), [
390 ('ACME CORP., Petitioner, v. NATIONAL LABOR RELATIONS BOARD, Respondent.',
391 'Petition for review of an order of the National Labor Relations Board.',
392 (None, 'National Labor Relations Board', 'National Labor Relations Board')),
393 # A company named for an agency's abbreviation, and an agency before "et al.".
394 ('PACIFIC GAS COMPANY; FMC WYOMING CORPORATION, Petitioners, v. UNITED STATES '
395 'DEPARTMENT OF LABOR et al., Respondents', '',
396 (None, 'Department of Labor', None)),
397 # An agency between parties, and a judge's initials in a docket number.
398 ('JOHN DOE, Plaintiff-Appellant, v. UNITED STATES OF AMERICA; FEDERAL BUREAU OF '
399 'PRISONS; ERIC H. HOLDER, JR., Attorney General, Defendants-Appellees.',
400 'D.C. No. 2:08-cr-00021-FMC-1. (D.C. No. 06-CR-126-CAB).',
401 (None, 'Bureau of Prisons', None))])
402def test_header_rules_find_agencies_that_are_parties(
403 party: str,
404 history: str,
405 expected: tuple[str | None, str | None, str | None]) -> None:
406 found = apply('header', party = party, history = history)
407 assert (
408 found['party1_agencies'], found['party2_agencies'], found['history_agencies']) == expected
411@pytest.mark.parametrize(('party', 'expected'), [
412 ('UNITED STATES OF AMERICA, Plaintiff-Appellee, v. JOHN DOE', True),
413 ('United States v. Doe', True),
414 ('JOHN DOE; UNITED STATES OF AMERICA, Defendants-Appellees, v. JANE ROE', True),
415 ('UNITED STATES ex rel. RUTH RITCHIE, Plaintiff, v. ACME CORP.', True),
416 ('USA, Plaintiff, v. DOE', True),
417 ('U.S. BANK, N.A., Defendant, v. DOE', False),
418 ('UNITED STATES FIDELITY AND GUARANTY CO., Plaintiff, v. DOE', False),
419 ('ERIC H. HOLDER, Attorney General of the United States, Respondent, v. DOE', False),
420 ('JOHN SMITH, United States Marshal, Defendant, v. DOE', False)])
421def test_header_rules_find_the_united_states(party: str, expected: bool) -> None:
422 assert apply('header', party = party)['party1_united_states'] is expected
425@pytest.mark.parametrize(('history', 'criminal', 'civil'), [
426 ('(D.C. No. 06-CR-126-CAB). (D. Wyo.).', True, False),
427 ('USDC No. 2:08-CR-4-1.', True, False),
428 ('No. 4:07CR00123', True, False),
429 ('Criminal Action No. 07-123', True, False),
430 ('(D.C. No. 08-cv-1478-ZLW).', False, True),
431 ('CIV. 05-1234', False, True),
432 ('Civil Action No. 05-123', False, True),
433 ('(D.C. Nos. CIV-05-630 JP/KBM & CR-03-2570 JP).', True, True),
434 # Words, not docket numbers.
435 ('Crawford v. Washington; see Fed. R. Crim. P. 35(b).', False, False),
436 ('A civil rights claim under 42 U.S.C. 1983.', False, False)])
437def test_header_rules_find_kinds_of_dockets(history: str, criminal: bool, civil: bool) -> None:
438 found = apply('header', history = history)
439 assert (found['docket_criminal'], found['docket_civil']) == (criminal, civil)
442@pytest.mark.parametrize(('future', 'granted'), [
443 ('Rehearing, en banc, granted by Doe v. Roe, 590 F.3d 1 (2009)', True),
444 ('Vacated by, Motion granted by Pulido v. Chrones, 567 F.3d 1 (2009)', True),
445 ('US Supreme Court certiorari denied by Grantham v. United States', False),
446 ('Mandate issued', False)])
447def test_lexis_rules_find_what_was_granted(future: str, granted: bool) -> None:
448 assert apply('lexis_nexis_header', future = future)['future_grant'] is granted
451def test_lexis_rules_find_concurrences_and_dissents_in_capitals() -> None:
452 found = apply(
453 'lexis_nexis',
454 text = (
455 '\nA v. B\n\nJUDGES: Before SMITH, JONES, and LEE, Circuit Judges.\n'
456 'OPINION BY: SMITH\n\nCONCUR BY: JONES\n\nOPINION\n\nWe affirm.\n'
457 'concurring: LEE, who did not write.\nLee, dissenting: in part.\n'
458 'dissenting).\nCONCUR\n\nJONES, Circuit Judge, concurring.\n'))
459 assert found['concurring_lines'] == 'CONCUR BY: JONES; CONCUR'
460 assert found['dissenting_lines'] is None
463@pytest.mark.parametrize(('opinion', 'decision', 'rulings'), [
464 # (affirm, reverse, vacate, remand, dismiss)
465 ('We review de novo and will reverse only if the error was plain. The '
466 'district court did not err. AFFIRMED.', 'AFFIRMED',
467 (True, False, False, False, False)),
468 ('Affirmed in part, vacated in part, and remanded by unpublished per '
469 'curiam opinion. Doe appeals.',
470 'Affirmed in part, vacated in part, and remanded by unpublished per '
471 'curiam opinion', (True, False, True, True, False)),
472 ('In Smith, we vacated a similar sentence. For these reasons, we vacate '
473 'the sentence and remand for resentencing.',
474 'we vacate the sentence and remand for resentencing.',
475 (False, False, True, True, False)),
476 ('We GRANT the petition for rehearing and VACATE our prior opinion. The '
477 'evidence was sufficient. We affirm.', 'We affirm.',
478 (True, False, False, False, False)),
479 ('The appeal is DISMISSED.', 'DISMISSED',
480 (False, False, False, False, True)),
481 # An earlier decision is not this one.
482 ('The court reversed the conviction in an earlier appeal.', None,
483 (False, False, False, False, False))])
484def test_federal_rules_find_the_stated_decision(
485 opinion: str,
486 decision: str | None,
487 rulings: tuple[bool, ...]) -> None:
488 found = apply('federal', opinion = opinion)
489 assert found['decision'] == decision
490 assert tuple(
491 found[f'decision_{r}']
492 for r in ('affirm', 'reverse', 'vacate', 'remand', 'dismiss')) == rulings
495@pytest.mark.parametrize(('text', 'expected'), [
496 ('Petition for review of an order of the National Labor Relations Board.', 'National Labor Relations Board'),
497 ('NATIONAL LABOR RELATIONS BOARD, Petitioner, v. ACME CORP.', 'National Labor Relations Board'),
498 ('The N.L.R.B. found that the NLRB had jurisdiction.', 'National Labor Relations Board'),
499 ('The SEC sued, and the Securities and Exchange Commission won.', 'Securities and Exchange Commission'),
500 ('Appeal from the United States Tax Court. The IRS assessed a deficiency.', 'Internal Revenue Service; United States Tax Court'),
501 ('The ATF agents searched the house.', 'Bureau of Alcohol Tobacco Firearms and Explosives'),
502 ('The U.S. Department of Transportation and the FAA regulate pilots.', 'Department of Transportation; Federal Aviation Administration'),
503 ('UNITED STATES DEPARTMENT OF LABOR, Respondent', 'Department of Labor'),
504 ('The Secretary of Labor sued under the Fair Labor Standards Act.', 'Department of Labor'),
505 ('the Department of State issued a passport', 'Department of State'),
506 ('The Commodity Futures Trading Commission (CFTC) brought the action.', 'Commodity Futures Trading Commission'),
507 ('The EPA issued a rule under the Clean Air Act.', 'Environmental Protection Agency'),
508 ('He served in the U.S. Army and later the Navy.', 'Department of the Army; Department of the Navy'),
509 ('The VA denied his claim for benefits.', 'Department of Veterans Affairs'),
510 ('A CMS manual governs Medicare reimbursement.', 'Health Care Financing Administration'),
511 ('The BIA affirmed, and the INS removed him.', 'Immigration and Naturalization Service'),
512 ('The General Accounting Office (GAO) reported.', 'Government Accountability Office'),
513 # Words and abbreviations that are not these agencies.
514 ('Claims under the Equal Pay Act (EPA) fail, so the EPA claim is dismissed.', None),
515 ('The ALJ relied on the Dictionary of Occupational Titles (DOT).', None),
516 ('The agreement is governed by the Federal Arbitration Act (FAA).', None),
517 ('JOHN DOE, Plaintiff-Appellant, v. JANE DOE.', None),
518 ('The Illinois Department of Transportation (IDOT) let the contract.', None),
519 ('the Pennsylvania Department of Labor and Industry denied benefits', None),
520 ('the state department of corrections transferred him', None),
521 ('Cal/OSHA cited the employer.', None),
522 ('SEC. 2. DEFINITIONS.', None),
523 ('Richmond, VA 23219. See Va. Code Ann.', None),
524 ('AETNA INS. CO. v. Smith', None),
525 ('The Salvation Army ran the shelter.', None),
526 ('The district court granted summary judgment.', None)])
527def test_federal_rules_find_agencies(text: str, expected: str | None) -> None:
528 found = apply('agencies', opinion = text)
529 assert found['agencies'] == expected
532def test_agencies_are_those_of_fjc_idb() -> None:
533 # Each agency of fjc-idb has rules, named by its code in their notes,
534 # except its codes for no agency, its second code for the Environmental
535 # Protection Agency, and "RTCO", which it does not name.
536 import fjc_idb.rules.appellate
537 book = amos.parsers.Rulebook.create('agencies')
538 codes = {
539 rule.note.split(':')[1].split('.')[0].strip()
540 for rule in book if rule.note.startswith('fjc-idb:')}
541 assert set(fjc_idb.rules.appellate.agencies) - codes == {'-8', '-9', '7', 'RTCO'}
542 values = {rule.value for rule in book}
543 assert len(values) == 104
544 assert all(',' not in value for value in values)
545 assert {rule.kind for rule in book} == {'categories'}
548def test_case_type_prefixes() -> None:
549 prefixes = rules.case_type_prefixes()
550 assert prefixes[:2] == ['criminal', 'civil']
551 assert {'tort', 'contract', 'ip', 'writ', 'constitutional'} <= set(prefixes)
552 assert 'party1' not in prefixes and 'citations' not in prefixes