Coverage for tests/wrangler/test_parsers.py: 100%

157 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""Tests the parsers and cases modules with CourtListener cases.""" 

2 

3from __future__ import annotations 

4 

5import logging 

6import pathlib 

7 

8import amos 

9import pandas as pd 

10import pytest 

11from conftest import make_cluster, make_opinion, write_case 

12 

13import courtpy 

14from courtpy import cases, options, parsers 

15 

16 

17def test_parse_court_listener(court_listener_folder: pathlib.Path) -> None: 

18 table = courtpy.parse(court_listener_folder) 

19 assert list(table.index) == ['1', '2', '3'] 

20 assert table.index.name == 'case_id' 

21 assert list(table.columns[:4]) == ['source', 'cluster_id', 'docket_id', 'court'] 

22 doe = table.loc['1'] 

23 assert doe['court'] == 'ca1' and doe['court_num'] == 1 

24 assert doe['court_name'] == 'first_circuit' 

25 assert doe['party1'] == 'UNITED STATES of America, Plaintiff-Appellee,' 

26 assert doe['party2_appellant'] and doe['party1_united_states'] 

27 assert doe['disposition_reverse'] and doe['disposition_remand'] 

28 assert doe['panel_judges'] == 'LYNCH; HOWARD; THOMPSON' 

29 assert doe['panel_size'] == 3 and doe['author'] == 'LYNCH' 

30 assert doe['citations_case'] == '554 U.S. 570' 

31 assert doe['citations_statute'].startswith('18 U.S.C. § 922') 

32 assert doe['cite_federal_reporter'] and doe['published'] 

33 assert table.loc['2', 'dissenting'] == 'THOMPSON' 

34 assert table.loc['2', 'civil_titlevii'] 

35 assert pd.api.types.is_bool_dtype(table['published'].dtype) 

36 assert table['year'].dtype == 'int64' 

37 

38 

39def test_parse_finds_agencies(tmp_path: pathlib.Path) -> None: 

40 # The agencies of the caption, the history, and the opinion are listed 

41 # once each, in alphabetical order. 

42 folder = tmp_path / 'courtlistener' 

43 write_case(folder, make_cluster( 

44 4, case_name_full = 'NATIONAL LABOR RELATIONS BOARD, Petitioner, v. ACME CORP., Respondent', 

45 procedural_history = 'On application for enforcement of an order of the NLRB.'), 

46 [make_opinion(41, 4, html_with_citations = ( 

47 '<p>The Board relied on a ruling of the IRS. The NLRB is right.</p>'))]) 

48 write_case(folder, make_cluster(5), [make_opinion(51, 5)]) 

49 table = courtpy.parse(folder) 

50 assert table.loc['4', 'agencies'] == 'Internal Revenue Service; National Labor Relations Board' 

51 assert pd.isna(table.loc['5', 'agencies']) 

52 

53 

54def test_missing_values_get_nullable_types() -> None: 

55 data = pd.DataFrame({'published': [True, None], 'year': [2020.0, None], 'x': ['a', None]}) 

56 tidied = cases.tidy(data) 

57 assert tidied['published'].dtype == 'boolean' 

58 assert tidied['year'].dtype == 'Int64' 

59 assert tidied['x'].dtype != 'boolean' 

60 

61 

62def test_find_files_skips_hidden_folders(court_listener_folder: pathlib.Path) -> None: 

63 hidden = court_listener_folder / '.courtpy' 

64 hidden.mkdir() 

65 (hidden / 'state.json').write_text('{}', encoding = 'utf-8') 

66 assert len(parsers.find_files(court_listener_folder)) == 3 

67 with pytest.raises(ValueError, match = 'source must be one of'): 

68 parsers.find_files(court_listener_folder, 'westlaw') 

69 

70 

71def test_unreadable_case_is_skipped( 

72 court_listener_folder: pathlib.Path, 

73 caplog: pytest.LogCaptureFixture) -> None: 

74 (court_listener_folder / 'ca1' / '9.json').write_text('not json', encoding = 'utf-8') 

75 with caplog.at_level(logging.WARNING): 

76 table = courtpy.parse(court_listener_folder) 

77 assert len(table) == 3 

78 assert 'could not be parsed' in caplog.text 

79 

80 

81def test_parse_with_workers(court_listener_folder: pathlib.Path) -> None: 

82 table = courtpy.parse(court_listener_folder, workers = 2) 

83 assert list(table.index) == ['1', '2', '3'] 

84 

85 

86def test_chunked_workers_match_one_process( 

87 court_listener_folder: pathlib.Path, 

88 monkeypatch: pytest.MonkeyPatch, 

89 caplog: pytest.LogCaptureFixture) -> None: 

90 # With chunks of two cases, the four cases (one unreadable) are two 

91 # tasks for the pool, and the table is the same as with one process. 

92 (court_listener_folder / 'ca1' / '9.json').write_text('not json', encoding = 'utf-8') 

93 monkeypatch.setattr(options, '_CHUNK_SIZE', 2) 

94 serial = courtpy.parse(court_listener_folder, workers = 1) 

95 with caplog.at_level(logging.INFO, logger = 'courtpy.wrangler.parsers'): 

96 chunked = courtpy.parse(court_listener_folder, workers = 2) 

97 pd.testing.assert_frame_equal(chunked, serial) 

98 assert list(chunked.index) == ['1', '2', '3'] 

99 assert '2 of 4 cases parsed' in caplog.text 

100 assert '4 of 4 cases parsed' in caplog.text 

101 assert 'could not be parsed' in caplog.text 

102 

103 

104def test_custom_rulebook(court_listener_folder: pathlib.Path, tmp_path: pathlib.Path) -> None: 

105 rules = tmp_path / 'mine.csv' 

106 rules.write_text( 

107 'target,variable,kind,pattern,value,ignorecase,dotall,note\n' 

108 'opinion,mentions_firearm,flag,firearm,,TRUE,FALSE,\n' 

109 'opinion,we_count,count,\\bwe\\b,,TRUE,FALSE,\n', encoding = 'utf-8') 

110 table = courtpy.parse(court_listener_folder, rulebooks = [rules]) 

111 assert table.loc['1', 'mentions_firearm'] and not table.loc['2', 'mentions_firearm'] 

112 assert table.loc['1', 'we_count'] == 2 

113 assert 'party1_appellant' in table.columns and 'decision' in table.columns 

114 assert 'criminal_firearm' not in table.columns 

115 

116 

117def test_save_and_load(court_listener_folder: pathlib.Path, tmp_path: pathlib.Path) -> None: 

118 table = courtpy.parse(court_listener_folder) 

119 path = tmp_path / 'out' / 'cases.csv' 

120 saved = courtpy.Cases.create(table).save(path) 

121 assert saved == [path.with_suffix('.joblib'), path] 

122 # Nothing else is made beside the files. 

123 assert sorted(p.name for p in path.parent.iterdir()) == ['cases.csv', 'cases.joblib'] 

124 loaded = courtpy.Cases.load(path).data 

125 assert list(loaded.index) == ['1', '2', '3'] 

126 assert loaded.loc['1', 'panel_judges'] == 'LYNCH; HOWARD; THOMPSON' 

127 assert pd.isna(loaded.loc['3', 'dissenting']) 

128 # Lists that `split_values` makes are saved as text, as the rules write 

129 # them, in the table and in the dataset. 

130 listed = courtpy.code(table, 'split_values') 

131 listed.save(tmp_path / 'lists.parquet') 

132 assert listed.data.loc['1', 'panel_judges'] == ['LYNCH', 'HOWARD', 'THOMPSON'] 

133 for name in ('lists.parquet', 'lists.joblib'): 

134 loaded = courtpy.Cases.load(tmp_path / name).data 

135 assert loaded.loc['1', 'panel_judges'] == 'LYNCH; HOWARD; THOMPSON' 

136 assert pd.api.types.is_bool_dtype(loaded['published'].dtype) 

137 pd.testing.assert_series_equal(loaded['court_num'], table['court_num'], check_dtype = False) 

138 assert listed.history[-1]['technique'] == 'save_data' 

139 with pytest.raises(ValueError, match = 'must end in'): 

140 listed.save(tmp_path / 'lists.txt') 

141 with pytest.raises(TypeError, match = 'holds Cases'): 

142 courtpy.Votes.load(tmp_path / 'lists.joblib') 

143 

144 

145def test_parser_metadata_wins(court_listener_folder: pathlib.Path) -> None: 

146 parser = parsers.Parser.create('federal') 

147 case = cases.Case( 

148 id = 'x', source = 'courtlistener', 

149 sections = {'court': 'Court of Appeals for the First Circuit'}, 

150 metadata = {'court_num': 99, 'agency': None}) 

151 row = parser.parse(case) 

152 assert row['court_num'] == 99 

153 assert row['agency'] is None 

154 assert row['word_count'] == 0 

155 

156 

157def test_parse_recent_court_listener(recent_folder: pathlib.Path) -> None: 

158 # CourtListener has no full case name, judges, or disposition for the 

159 # case, so they are read from its opinion. 

160 table = courtpy.parse(recent_folder) 

161 doe = table.loc['4'] 

162 assert pd.isna(doe['judges']) and pd.isna(doe['disposition']) 

163 assert doe['caption'] == 'Appellee, versus JOHN DOE, Defendant-Appellant' 

164 assert doe['party2_appellant'] and doe['party1_appellee'] 

165 assert not doe['party1_appellant'] and not doe['party2_appellee'] 

166 assert doe['panel_judges'] == 'LYNCH; HOWARD; R THOMPSON' 

167 assert doe['panel_size'] == 3 

168 assert doe['decision'] == 'AFFIRMED' 

169 assert doe['decision_affirm'] and not doe['decision_reverse'] 

170 assert doe['opinion_reverse'] and not doe['disposition_affirm'] 

171 assert 'opening_lines' not in table.columns 

172 coded = courtpy.code(table).data.loc['4'] 

173 assert coded['type_criminal'] and coded['appeal_by_defendant'] 

174 assert not coded['outcome_reversal'] 

175 assert not coded['outcome_criminal_defendant_won'] 

176 

177 

178def test_keep_text_keeps_every_section(court_listener_folder: pathlib.Path) -> None: 

179 table = courtpy.parse(court_listener_folder, keep_text = True) 

180 for section in ('party', 'history', 'judges', 'opinion_by', 'opinion'): 

181 assert section in table.columns 

182 assert table.loc['2', 'party'].startswith('Mary SMITH') 

183 # The court's id from CourtListener's data is kept, not its name. 

184 assert table.loc['1', 'court'] == 'ca1' 

185 assert 'opinion' not in courtpy.parse(court_listener_folder).columns 

186 

187 

188def test_parse_all_is_amos_parse_all() -> None: 

189 assert amos.library.borrow('parse_all') is parsers.ParseAll 

190 assert issubclass(parsers.ParseAll, amos.parsers.ParseAll) 

191 

192 

193def test_parse_all_parses_kept_text_again(court_listener_folder: pathlib.Path) -> None: 

194 table = courtpy.parse(court_listener_folder, keep_text = True) 

195 dropped = ['panel_judges', 'party1_appellant', 'disposition_affirm', 'author', 'citations_case'] 

196 again = parsers.ParseAll().parse(table.drop(columns = dropped)) 

197 assert set(again.columns) == set(table.columns) 

198 for column in [*dropped, 'court_num', 'court_name', 'word_count', 'panel_size']: 

199 pd.testing.assert_series_equal( 

200 again[column], table[column], check_dtype = False, check_names = False) 

201 

202 

203def test_parse_all_applies_rulebooks(court_listener_folder: pathlib.Path, tmp_path: pathlib.Path) -> None: 

204 rules = tmp_path / 'heller.csv' 

205 rules.write_text('column,name,kind,pattern\nopinion,cites_heller,flags,554 U\\.S\\. 570\n', encoding = 'utf-8') 

206 table = courtpy.parse(court_listener_folder, keep_text = True) 

207 again = parsers.ParseAll().parse(table, rulebooks = [str(rules)]) 

208 assert again['cites_heller'].tolist() == [True, False, False] 

209 # Only the header rules, "general", and the rulebooks named are applied. 

210 assert 'citations_case' in again.columns and 'cites_heller' not in table.columns 

211 

212 

213def test_parse_all_with_rules_is_amos_parse_all(court_listener_folder: pathlib.Path) -> None: 

214 table = courtpy.parse(court_listener_folder) 

215 rules = [{'column': 'case_name', 'name': 'doe', 'kind': 'flags', 'pattern': 'Doe'}] 

216 found = parsers.ParseAll().parse(table, rules = rules) 

217 assert found['doe'].tolist() == [True, False, False] 

218 assert list(found.columns) == [*table.columns, 'doe'] 

219 

220 

221def test_parse_all_needs_kept_text(court_listener_folder: pathlib.Path) -> None: 

222 with pytest.raises(ValueError, match = 'keep_text'): 

223 parsers.ParseAll().parse(courtpy.parse(court_listener_folder))