Coverage for tests/artist/test_plots.py: 100%
70 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 plots module: courtpy's figures of cases, courts, and judges."""
3from __future__ import annotations
5import amos
6import numpy as np
7import pandas as pd
8import pytest
10import courtpy
12pytest.importorskip('matplotlib')
15def make_cases() -> courtpy.Cases:
16 """Returns cases of three courts, with what the plots draw."""
17 data = pd.DataFrame({
18 'court_name': ['tenth_circuit'] * 4 + ['fifth_circuit'] * 3 + ['dc_circuit'],
19 'court_num': [10, 10, 10, 10, 5, 5, 5, 12],
20 'lower_court_name': [
21 'district_of_colorado', 'district_of_colorado', 'district_of_kansas', None,
22 'northern_district_of_texas', 'northern_district_of_texas',
23 'southern_district_of_texas', 'district_of_columbia'],
24 'year': [2008, 2008, 2009, 2010, 2008, 2009, 2009, 2010],
25 'outcome_reversal': pd.array([True, False, False, True, False, False, True, pd.NA], dtype = 'boolean'),
26 'criminal_firearm': [True, True, False, False, True, False, False, False],
27 'type_immigration': [False, False, True, False, False, True, True, False],
28 'type_criminal': [True, True, False, False, True, False, False, True],
29 'judge_party1': [-1, -1, 1, 1, 1, 1, -1, 1],
30 'judge_party2': [-1, 1, 1, 1, 1, -1, -1, 1],
31 'judge_party3': [-1, 1, 1, None, 1, -1, 1, 1]},
32 index = pd.Index([f'c{n}' for n in range(8)], name = 'case_id'))
33 return courtpy.Cases.create(data)
36def draw(name: str, item: amos.Dataset, **parameters: object) -> object:
37 """Applies a plot from the library and returns its figure."""
38 amos.library.borrow(name)().apply(item, **parameters)
39 return item.figures[name]
42def test_plots_are_in_the_library() -> None:
43 for name in (
44 'court_rates', 'cases_over_time', 'issues_over_time', 'panel_composition',
45 'lower_court_rates', 'trends_by_administration', 'judge_network',
46 'idb_confusion_matrices', 'idb_missing_differences'):
47 assert amos.library.classify(name) == 'plot'
50def test_court_rates_are_measured_rates() -> None:
51 figure = draw('court_rates', make_cases())
52 axes = figure.axes[0]
53 # The courts are in the order of the table of courts, with their names.
54 assert [t.get_text() for t in axes.get_yticklabels()] == ['Fifth Circuit', 'Tenth Circuit']
55 assert [round(b.get_width(), 4) for b in axes.patches] == [round(1 / 3, 4), 0.5]
56 labels = [t.get_text() for t in axes.texts]
57 assert labels == [' 33% (n = 3)', ' 50% (n = 4)']
58 # The rate of every court is a line, and there are no error bars.
59 assert axes.lines[0].get_xdata()[0] == pytest.approx(3 / 7)
60 assert not axes.collections
63def test_cases_over_time_has_a_panel_for_each_court() -> None:
64 figure = draw('cases_over_time', make_cases())
65 shown = [a for a in figure.axes if a.get_visible()]
66 assert [a.get_title() for a in shown] == ['Fifth Circuit', 'Tenth Circuit', 'D.C. Circuit']
67 tenth = shown[1].lines[0]
68 assert list(tenth.get_xdata()) == [2008, 2009, 2010]
69 assert list(tenth.get_ydata()) == [2, 1, 1]
72def test_issues_over_time_counts_each_issue() -> None:
73 figure = draw('issues_over_time', make_cases(), issues = 'criminal_firearm, type_immigration')
74 fifth = next(a for a in figure.axes if a.get_title() == 'Fifth Circuit')
75 firearm, immigration = fifth.lines
76 assert firearm.get_label() == 'criminal firearm'
77 assert list(firearm.get_ydata()) == [1, 0, 0]
78 assert list(immigration.get_ydata()) == [0, 2, 0]
79 with pytest.raises(ValueError, match = 'issues'):
80 draw('issues_over_time', make_cases())
83def test_panel_composition_splits_by_party_and_column() -> None:
84 figure = draw('panel_composition', make_cases(), by = 'type_criminal')
85 axes = figure.axes[0]
86 assert [t.get_text() for t in axes.get_xticklabels()] == ['DDD', 'DDR', 'DRR', 'RRR']
87 heights = [round(b.get_height(), 4) for b in axes.patches]
88 # Other cases: DDR (c5 and c6) 1 of 2 and RRR (c2) 0; criminal: DDD
89 # (c0) 1, DRR (c1) 0, and RRR (c4) 0. c7 has no outcome, and c3 no
90 # third party.
91 assert heights == [0, 0.5, 0, 0, 1, 0, 0, 0]
94def test_lower_court_rates_group_by_reviewing_court() -> None:
95 figure = draw('lower_court_rates', make_cases())
96 axes = figure.axes[0]
97 labels = [t.get_text() for t in axes.get_yticklabels()]
98 assert labels == [
99 'Northern District of Texas (2)', 'Southern District of Texas (1)',
100 'District of Colorado (2)', 'District of Kansas (1)']
101 assert [round(b.get_width(), 4) for b in axes.patches] == [0, 1, 0.5, 0]
104def test_trends_by_administration_shade_the_presidents() -> None:
105 figure = draw('trends_by_administration', make_cases())
106 tenth = next(a for a in figure.axes if a.get_title() == 'Tenth Circuit')
107 assert list(tenth.lines[0].get_ydata()) == [0.5, 0, 1]
108 # Bush's term (Republican) and Obama's (Democratic) are shaded.
109 colors = {tuple(np.round(p.get_facecolor()[:3], 3)) for p in tenth.patches}
110 assert len(colors) == 2
113def test_judge_network() -> None:
114 pytest.importorskip('networkx')
115 votes = amos.Dataset(pd.DataFrame({
116 'case_id': ['a', 'a', 'a', 'b', 'b', 'b'],
117 'judge': ['LYNCH', 'HOWARD', 'BOUDIN', 'LYNCH', 'HOWARD', 'TORRUELLA'],
118 'judge_party': [-1, 1, 1, -1, 1, None],
119 'judge_dissented': [False, False, True, False, False, False]}))
120 figure = draw('judge_network', votes)
121 axes = figure.axes[0]
122 assert len(axes.collections[1].get_offsets()) == 4
123 # LYNCH and HOWARD sat together twice; the others once.
124 assert len(axes.collections[0].get_paths()) == 5
125 dissents = draw('judge_network', votes, dissents = True)
126 assert len(dissents.axes[0].collections[0].get_paths()) == 2
127 with pytest.raises(KeyError, match = 'cases_to_votes'):
128 draw('judge_network', make_cases())