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

94 statements  

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

1"""Tests the shapers module.""" 

2 

3from __future__ import annotations 

4 

5import amos 

6import pandas as pd 

7import pytest 

8 

9import courtpy 

10from courtpy import shapers 

11 

12 

13def coded() -> courtpy.Cases: 

14 """Returns cases with case types, parties' types, and outcomes.""" 

15 data = pd.DataFrame({ 

16 'case_id': ['1', '2', '3', '4'], 

17 'court_num': [1, 1, 2, 2], 

18 'court': ['ca1', 'ca1', 'ca2', 'ca2'], 

19 'year': [2019, 2020, 2020, 2020], 

20 'docket_number': ['19-1', '20-2', '20-3', '20-4'], 

21 'type_criminal': [True, False, False, False], 

22 'type_civil': [False, True, True, True], 

23 'type_tort': [False, True, False, True], 

24 'type_contract': [False, True, True, False], 

25 'party1_type': ['government', 'individual', 'corporation', 'individual'], 

26 'party2_type': ['individual', 'corporation', 'corporation', None], 

27 'party1_appealing': [False, True, True, False], 

28 'party2_appealing': [True, False, False, True], 

29 'outcome_party1_won': [True, False, True, False], 

30 'outcome_party2_won': [False, True, False, True], 

31 'outcome_reversal': [False, True, False, True], 

32 'judge_nid1': pd.array([101, 101, 201, 202], dtype = 'Int64'), 

33 'judge_nid2': pd.array([102, 103, 202, pd.NA], dtype = 'Int64')}) 

34 return courtpy.Cases.create(data) 

35 

36 

37def test_shapers_are_in_the_library() -> None: 

38 for name in ('cases_to_courts', 'cases_to_case_types', 'cases_to_party_types', 'cases_to_dockets', 'dockets_to_cases'): 

39 assert amos.library.classify(name) == 'shaper' 

40 

41 

42def test_cases_to_courts() -> None: 

43 dataset = shapers.CasesToCourts().apply(coded(), label = 'outcome_reversal') 

44 assert isinstance(dataset, courtpy.Courts) 

45 table = dataset.data 

46 assert table.index.name == 'court_num' and list(table.index) == [1, 2] 

47 assert list(table['cases']) == [2, 2] 

48 assert list(table['judges']) == [3, 2] 

49 assert list(table['type_criminal']) == [0.5, 0.0] 

50 assert list(table['type_tort']) == [0.5, 0.5] 

51 assert list(table['party_type_corporation']) == [0.5, 0.5] 

52 assert list(table['outcome_reversal']) == [0.5, 0.5] 

53 # Nothing about any one case is kept. 

54 assert not {'docket_number', 'court', 'case_id', 'judge_nid1', 'party1_type'} & set(table.columns) 

55 assert (dataset.label, dataset.groups) == ('outcome_reversal', []) 

56 # "by" makes a row for each court in each year, and "keep" keeps text. 

57 by_year = shapers.CasesToCourts().shape(coded().data, by = 'year', keep = 'court') 

58 assert list(by_year.index) == [(1, 2019), (1, 2020), (2, 2020)] 

59 assert list(by_year['court']) == ['ca1', 'ca1', 'ca2'] 

60 with pytest.raises(KeyError, match = 'no_such'): 

61 shapers.CasesToCourts().shape(coded().data, court = 'no_such') 

62 

63 

64def test_cases_to_case_types() -> None: 

65 dataset = shapers.CasesToCaseTypes().apply(coded()) 

66 assert isinstance(dataset, courtpy.CaseTypes) 

67 table = dataset.data 

68 assert table.index.name == 'case_type' 

69 # A case of several types counts for each of them. 

70 assert table['cases'].to_dict() == {'criminal': 1, 'civil': 3, 'tort': 2, 'contract': 2} 

71 assert table.loc['tort', 'outcome_reversal'] == 1.0 

72 assert table.loc['civil', 'party_type_individual'] == pytest.approx(2 / 3) 

73 assert 'docket_number' not in table 

74 by_court = shapers.CasesToCaseTypes().shape(coded().data, by = 'court_num') 

75 assert by_court.loc[('civil', 2), 'cases'] == 2 

76 with pytest.raises(KeyError, match = 'code_case_type'): 

77 shapers.CasesToCaseTypes().shape(pd.DataFrame({'x': [1]})) 

78 

79 

80def test_cases_to_party_types() -> None: 

81 dataset = shapers.CasesToPartyTypes().apply(coded()) 

82 assert isinstance(dataset, courtpy.PartyTypes) 

83 table = dataset.data 

84 assert table.index.name == 'party_type' 

85 # Each party is a row: three individuals, three corporations, and one 

86 # government (the missing type is left out). 

87 assert table['parties'].to_dict() == {'government': 1, 'individual': 3, 'corporation': 3} 

88 assert table.loc['individual', 'party_won'] == 0.0 

89 assert table.loc['corporation', 'party_won'] == pytest.approx(2 / 3) 

90 assert table.loc['government', 'party_appealing'] == 0.0 

91 assert table.loc['corporation', 'type_contract'] == 1.0 

92 assert 'party1_appealing' not in table and 'docket_number' not in table 

93 with pytest.raises(KeyError, match = 'party1_type'): 

94 shapers.CasesToPartyTypes().shape(pd.DataFrame({'x': [1]})) 

95 

96 

97def test_add_party_type_flags() -> None: 

98 flags = shapers.add_party_type_flags(coded().data) 

99 assert list(flags['party_type_government']) == [True, False, False, False] 

100 plain = pd.DataFrame({'x': [1]}) 

101 assert shapers.add_party_type_flags(plain) is plain 

102 

103 

104def test_summarize() -> None: 

105 data = pd.DataFrame({ 

106 'group': ['a', 'a', 'b'], 'x': [1.0, 3.0, 5.0], 'flag': [True, False, True], 

107 'case_id': [1, 2, 3], 'name': ['p', 'q', 'r']}) 

108 table = shapers.summarize(data, ['group'], count = 'n') 

109 assert list(table.columns) == ['x', 'flag', 'n'] 

110 assert list(table['x']) == [2.0, 5.0] and list(table['flag']) == [0.5, 1.0] 

111 listed = shapers.summarize(data, ['group'], how = {'name': 'list'}, keep = 'name') 

112 assert listed.loc['a', 'name'] == ['p', 'q'] 

113 

114 

115def test_cases_to_dockets_and_back() -> None: 

116 data = pd.DataFrame({ 

117 'case_id': ['a', 'b', 'c', 'd'], 

118 'docket_numbers': ['17-1; 17-2', '18-5', None, ['19-7', '19-8']], 

119 'docket_number': ['Nos. 17-1, 17-2', '18-5', None, '19-7'], 

120 'docket_id': [10, 20, 30, 40], 

121 'x': [1, 2, 3, 4]}) 

122 cases = courtpy.Cases.create(data.copy()) 

123 dockets = shapers.CasesToDockets().apply(cases, groups = 'case_id', label = 'x') 

124 assert isinstance(dockets, courtpy.Dockets) 

125 table = dockets.data 

126 assert table.index.name == 'case_docket' 

127 assert list(table.index) == ['a-1', 'a-2', 'b-1', 'c-1', 'd-1', 'd-2'] 

128 assert list(table.columns[:2]) == ['case_id', 'docket'] 

129 assert list(table['docket'].fillna('')) == ['17-1', '17-2', '18-5', '', '19-7', '19-8'] 

130 # Each row has only its own docket number. 

131 assert 'docket_numbers' not in table 

132 assert list(table['x']) == [1, 1, 2, 3, 4, 4] 

133 # CourtListener's id for the docket of each case is kept. 

134 assert list(table['docket_id']) == [10, 10, 20, 30, 40, 40] 

135 assert (dockets.label, dockets.groups) == ('x', ['case_id']) 

136 back = shapers.DocketsToCases().apply(dockets) 

137 assert isinstance(back, courtpy.Cases) 

138 assert list(back.data.index) == ['a', 'b', 'c', 'd'] 

139 assert list(back.data['docket_numbers'].fillna('')) == ['17-1; 17-2', '18-5', '', '19-7; 19-8'] 

140 assert back.groups == [] and 'docket' not in back.data 

141 assert list(back.data['docket_id']) == [10, 20, 30, 40] 

142 # Without "docket_numbers", the numbers in "docket_number" are used. 

143 from_text = shapers.CasesToDockets().shape(data.drop(columns = 'docket_numbers').set_index('case_id')) 

144 assert list(from_text['docket'].iloc[:2]) == ['17-1', '17-2'] 

145 with pytest.raises(KeyError, match = 'docket_numbers'): 

146 shapers.CasesToDockets().shape(pd.DataFrame({'x': [1]}, index = pd.Index(['a'], name = 'case_id'))) 

147 with pytest.raises(KeyError, match = 'case_id'): 

148 shapers.DocketsToCases().shape(pd.DataFrame({'x': [1]}))