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

161 statements  

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

1"""Tests the coders module.""" 

2 

3from __future__ import annotations 

4 

5import pathlib 

6 

7import amos 

8import pandas as pd 

9import pytest 

10 

11import courtpy 

12from courtpy import coders 

13from courtpy.wrangler import rules 

14 

15 

16@pytest.fixture 

17def coded(court_listener_folder: pathlib.Path) -> amos.Dataset: 

18 return courtpy.code(courtpy.parse(court_listener_folder)) 

19 

20 

21def test_coders_are_in_the_library() -> None: 

22 for name in ('code_parties', 'code_case_type', 'code_outcome'): 

23 assert amos.library.classify(name) == 'munger' 

24 assert amos.library.classify('drop_text_columns') == 'cleaner' 

25 

26 

27def test_mungers_record_their_columns(coded: amos.Dataset) -> None: 

28 parties, case_type, outcome = coded.history 

29 assert {'party1_appealing', 'party2_defending'} <= set(parties['created']) 

30 assert 'type_criminal' in case_type['created'] 

31 assert outcome['created'][0] == 'outcome_reversal' 

32 

33 

34def test_code_parties(coded: amos.Dataset) -> None: 

35 data = coded.data 

36 assert data.loc['1', 'party2_appealing'] and data.loc['1', 'party1_defending'] 

37 assert data.loc['2', 'party1_appealing'] and data.loc['2', 'party2_defending'] 

38 assert not data.loc['3', 'party1_appealing'] and not data.loc['3', 'party1_defending'] 

39 assert [entry['technique'] for entry in coded.history] == [ 

40 'code_parties', 'code_case_type', 'code_outcome'] 

41 

42 

43def test_code_parties_completes_opposites() -> None: 

44 roles = ['appellant', 'appellee', 'petitioner', 'respondent', 'plaintiff', 'defendant'] 

45 data = pd.DataFrame({f'{s}_{r}': [False] for s in ('party1', 'party2') for r in roles}) 

46 data['party2_appellant'] = True 

47 data['party1_plaintiff'] = True 

48 result = coders.CodeParties().apply(amos.Dataset(data)).data 

49 assert result.loc[0, 'party1_appellee'] and result.loc[0, 'party2_defendant'] 

50 assert result.loc[0, 'party2_appealing'] and result.loc[0, 'party1_defending'] 

51 

52 

53def _parsed_parties(**flags: list[bool]) -> pd.DataFrame: 

54 roles = [ 

55 'appellant', 'appellee', 'petitioner', 'respondent', 'plaintiff', 

56 'defendant', 'united_states'] 

57 size = len(next(iter(flags.values()))) 

58 data = pd.DataFrame({ 

59 f'{s}_{r}': [False] * size for s in ('party1', 'party2') for r in roles}) 

60 for column, values in flags.items(): 

61 data[column] = values 

62 return data 

63 

64 

65def test_code_parties_prefers_each_party_own_caption() -> None: 

66 # 0: a caption that joins several appeals names party2 both appellee and 

67 # appellant, so party2 takes the opposite of party1's role. 

68 # 1: a habeas petitioner who won below is the appellee. 

69 # 2: both appellants (a cross-appeal) leaves both unknown. 

70 # 3: party1 names itself both, and party2 decides. 

71 data = _parsed_parties( 

72 party1_appellant = [True, False, True, True], 

73 party1_appellee = [False, True, False, True], 

74 party1_petitioner = [False, True, False, False], 

75 party2_appellant = [True, True, True, False], 

76 party2_appellee = [True, False, False, True], 

77 party2_respondent = [False, True, False, False]) 

78 result = coders.CodeParties().apply(amos.Dataset(data)).data 

79 assert list(result['party1_appealing']) == [True, False, False, True] 

80 assert list(result['party1_defending']) == [False, True, False, False] 

81 assert list(result['party2_appealing']) == [False, True, False, False] 

82 assert list(result['party2_defending']) == [True, False, False, True] 

83 

84 

85def test_code_parties_reads_the_opening_when_the_caption_is_silent() -> None: 

86 # 0: the opening gives the United States its role. 

87 # 1: the opening names the defendant as the appellant. 

88 # 2: the opening says that the defendant appeals. 

89 # 3: the opening says that the government appeals. 

90 # 4: a cross-appeal decides nothing. 

91 # 5: a role that the opening's sentences contradict decides nothing. 

92 # 6: a caption with roles decides, whatever the opening says. 

93 # 7: without the United States as a party, the opening decides nothing. 

94 # 8: the United States as the defendant in a civil suit. 

95 data = _parsed_parties( 

96 party1_united_states = [True] * 8 + [False], 

97 party2_united_states = [False] * 8 + [True], 

98 party2_appellee = [False] * 6 + [True, False, False]) 

99 data.loc[7, 'party1_united_states'] = False 

100 data['opening_united_states_role'] = [ 

101 'Plaintiff-Appellee', None, None, None, 

102 'Plaintiff-Appellee/Cross-Appellant', 'Plaintiff-Appellant', None, None, 

103 'Defendant - Appellee'] 

104 data['opening_defendant_appellant'] = [False, True] + [False] * 7 

105 data['opening_defendant_appellee'] = [False] * 9 

106 data['opening_government_appeals'] = [False, False, False, True] + [False] * 5 

107 data['opening_party_appeals'] = [False, False, True, False, False, True, True, True, False] 

108 result = coders.CodeParties().apply(amos.Dataset(data)).data 

109 assert list(result['party1_appealing']) == [ 

110 False, False, False, True, False, False, True, False, True] 

111 assert list(result['party2_appealing']) == [ 

112 True, True, True, False, False, False, False, False, False] 

113 assert list(result['party1_defending']) == [ 

114 True, True, True, False, False, False, False, False, False] 

115 assert list(result['party2_defending']) == [ 

116 False, False, False, True, False, False, True, False, True] 

117 

118 

119def test_consolidated_government_appeal() -> None: 

120 # "UNITED STATES of America, Appellant, v. Joseph PROCHILO, Defendant, 

121 # Appellee; United States of America, Appellant, v. Elvis Guerrero, 

122 # Defendant, Appellee": both parties' text names the United States. 

123 data = _parsed_parties( 

124 party1_appellant = [True], party1_united_states = [True], 

125 party2_appellant = [True], party2_appellee = [True], 

126 party2_defendant = [True], party2_united_states = [True]) 

127 data['docket_criminal'] = True 

128 data['disposition'] = 'Reversed.' 

129 for prefix in ('disposition', 'opinion'): 

130 for ruling in ('reverse', 'vacate', 'remand'): 

131 data[f'{prefix}_{ruling}'] = ruling == 'reverse' 

132 result = courtpy.code( 

133 amos.Dataset(data), ['code_parties', 'code_case_type', 'code_outcome']).data 

134 assert result.loc[0, 'party1_prosecution'] 

135 assert result.loc[0, 'party2_criminal_defendant'] 

136 assert not result.loc[0, 'appeal_by_defendant'] 

137 assert result.loc[0, 'outcome_prosecution_won'] 

138 

139 

140def test_consolidated_government_appeal_by_text() -> None: 

141 # Neither party is named a defendant, so the text decides which one is 

142 # the United States. 

143 data = _parsed_parties( 

144 party1_appellant = [True], party1_united_states = [True], 

145 party2_appellant = [True], party2_appellee = [True], 

146 party2_united_states = [True]) 

147 data['party1'] = 'UNITED STATES of America, Appellant,' 

148 data['party2'] = ( 

149 'Vincent BERTLING, Appellee; United States of America, Appellant, ' 

150 'v. Karl Raymond Bertling, Appellee') 

151 data['docket_criminal'] = True 

152 result = coders.CodeCaseType().apply( 

153 coders.CodeParties().apply(amos.Dataset(data))).data 

154 assert result.loc[0, 'party1_prosecution'] 

155 assert result.loc[0, 'party2_criminal_defendant'] 

156 assert result.loc[0, 'party2_defending'] 

157 

158 

159def test_cross_roles_with_spaces_are_not_plain_roles() -> None: 

160 book = amos.parsers.Rulebook.create(rules.RULEBOOKS['header']) 

161 patterns = { 

162 rule.names[0]: rule.pattern for rule in book 

163 if rule.columns == ('party1',)} 

164 caption = 'UNITED STATES of America, Plaintiff-Appellant Cross Appellee,' 

165 found = {name: bool(patterns[name].search(caption)) for name in ( 

166 'party1_appellant', 'party1_appellee', 'party1_cross_appellee')} 

167 assert found == { 

168 'party1_appellant': True, 'party1_appellee': False, 

169 'party1_cross_appellee': True} 

170 

171 

172def test_code_case_type(coded: amos.Dataset) -> None: 

173 data = coded.data 

174 assert list(data['type_criminal']) == [True, False, False] 

175 assert data.loc['1', 'party1_prosecution'] and data.loc['1', 'party2_criminal_defendant'] 

176 assert data.loc['2', 'party1_civil_plaintiff'] and data.loc['2', 'party2_civil_defendant'] 

177 # Every case that is not criminal is civil, and each other prefix of the 

178 # rules of the topics of cases is a type too. 

179 assert list(data['type_civil']) == [False, True, True] 

180 assert isinstance(coded, courtpy.Cases) 

181 types = [c for c in data.columns if c.startswith('type_')] 

182 assert types[:2] == ['type_criminal', 'type_civil'] 

183 assert {'type_tort', 'type_contract', 'type_ip', 'type_constitutional'} <= set(types) 

184 

185 

186def test_code_case_type_prefixes() -> None: 

187 data = pd.DataFrame({ 

188 'party1_united_states': [False, False], 'party2_united_states': [False, False], 

189 'party1_plaintiff': [True, False], 'party2_plaintiff': [False, False], 

190 'party1_defendant': [False, False], 'party2_defendant': [True, False], 

191 'immigration_asylum': [False, True], 'immigration_removal': [False, False], 

192 'tort_negligence': [True, False]}) 

193 data = coders.CodeCaseType().apply(amos.Dataset(data), prefixes = 'immigration, tort').data 

194 # A prefix added to the rules is a type once the cases have its columns. 

195 assert list(data['type_immigration']) == [False, True] 

196 assert list(data['type_tort']) == [True, False] 

197 

198 

199def test_code_outcome(coded: amos.Dataset) -> None: 

200 data = coded.data 

201 # Case 1 is reversed by its disposition, case 2 affirmed (although its 

202 # dissent says "reverse"), and case 3 has no disposition, so the opinion's 

203 # "We vacate" is used. 

204 assert list(data['outcome_reversal']) == [True, False, True] 

205 assert data.loc['1', 'outcome_party2_won'] and not data.loc['1', 'outcome_party1_won'] 

206 assert data.loc['1', 'outcome_criminal_defendant_won'] 

207 assert not data.loc['1', 'outcome_prosecution_won'] 

208 assert pd.isna(data.loc['1', 'outcome_civil_plaintiff_won']) 

209 assert data.loc['1', 'appeal_by_defendant'] 

210 assert not data.loc['2', 'outcome_civil_plaintiff_won'] 

211 assert data.loc['2', 'outcome_civil_defendant_won'] 

212 assert not data.loc['2', 'appeal_by_defendant'] 

213 assert pd.isna(data.loc['3', 'outcome_party1_won']) 

214 assert data['outcome_party1_won'].dtype == 'boolean' 

215 

216 

217def test_drop_text_columns(coded: amos.Dataset) -> None: 

218 coded.data['case_name'] = coded.data['case_name'].astype('category') 

219 coders.DropTextColumns().apply(coded, keep = ['court']) 

220 data = coded.data 

221 for column in ('party1', 'panel_judges', 'date_filed', 'url', 'citations_case'): 

222 assert column not in data.columns 

223 for column in ('court', 'case_name', 'court_num', 'published', 'outcome_party1_won', 'year'): 

224 assert column in data.columns 

225 

226 

227def test_drop_text_columns_keeps_label() -> None: 

228 dataset = amos.Dataset(pd.DataFrame({'note': ['a', 'b'], 'x': [1, 2]}), label = 'note') 

229 coders.DropTextColumns().apply(dataset) 

230 assert list(dataset.data.columns) == ['note', 'x'] 

231 

232 

233def test_missing_columns() -> None: 

234 with pytest.raises(KeyError, match = 'federal rules'): 

235 coders.CodeOutcome().apply(amos.Dataset(pd.DataFrame({'x': [1]}))) 

236 

237 

238def test_code_outcome_prefers_stated_decisions() -> None: 

239 # The header's disposition, then the decision that the opinion states, 

240 # and only then "reverse", "vacate", or "remand" anywhere in the opinion. 

241 data = pd.DataFrame({ 

242 'disposition': ['Affirmed.', None, None, None], 

243 'decision': ['we reverse.', 'AFFIRMED', 'VACATED AND REMANDED', None], 

244 'decision_reverse': [True, False, False, False], 

245 'decision_vacate': [False, False, True, False], 

246 'decision_remand': [False, False, True, False], 

247 'opinion_reverse': [True, True, False, True]}) 

248 for column in ('disposition_reverse', 'disposition_vacate', 'disposition_remand', 

249 'opinion_vacate', 'opinion_remand'): 

250 data[column] = False 

251 result = coders.CodeOutcome().apply(amos.Dataset(data)).data 

252 assert list(result['outcome_reversal']) == [False, False, True, True] 

253 # Rules that find no "decision" leave the opinion's words. 

254 result = coders.CodeOutcome().apply(amos.Dataset( 

255 data.drop(columns = [c for c in data.columns if c.startswith('decision')]))).data 

256 assert list(result['outcome_reversal']) == [False, True, False, True] 

257 

258 

259def test_tidy_cases() -> None: 

260 assert amos.library.classify('tidy_cases') == 'munger' 

261 data = pd.DataFrame({ 

262 'published': [True, None, False], 

263 'year': [2019.0, None, 2020.0], 

264 'score': [0.5, None, 1.0]}) 

265 tidied = courtpy.code(data, ['tidy_cases']).data 

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

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

268 assert tidied['score'].dtype == 'float64' 

269 

270 

271def test_split_values() -> None: 

272 assert amos.library.classify('split_values') == 'munger' 

273 data = pd.DataFrame({ 

274 'panel_judges': ['LYNCH; HOWARD; THOMPSON', None, 'KAYATTA'], 

275 'agencies': ['Internal Revenue Service; United States Tax Court', None, None], 

276 'notes': ['a; b', None, None]}) 

277 listed = coders.SplitValues().apply(amos.Dataset(data.copy())).data 

278 assert listed['panel_judges'].tolist() == [['LYNCH', 'HOWARD', 'THOMPSON'], [], ['KAYATTA']] 

279 assert listed['agencies'].tolist() == [['Internal Revenue Service', 'United States Tax Court'], [], []] 

280 # Only the columns of rules that make several values are split. 

281 assert listed['notes'].equals(data['notes']) 

282 wide = coders.SplitValues().apply( 

283 amos.Dataset(data.copy()), columns = 'agencies', into = 'columns').data 

284 assert wide['agencies_1'].tolist() == ['Internal Revenue Service', None, None] 

285 assert wide['agencies_2'].tolist() == ['United States Tax Court', None, None] 

286 assert 'agencies' in wide.columns and 'agencies_3' not in wide.columns 

287 with pytest.raises(ValueError, match = 'into'): 

288 coders.SplitValues().apply(amos.Dataset(data.copy()), into = 'rows') 

289 with pytest.raises(KeyError): 

290 coders.SplitValues().apply(amos.Dataset(data.copy()), columns = 'missing')