Coverage for tests/test_cli.py: 100%

87 statements  

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

1"""Tests the command line interface.""" 

2 

3from __future__ import annotations 

4 

5import io 

6import pathlib 

7from typing import Any 

8 

9import pandas as pd 

10import pytest 

11 

12import courtpy 

13from courtpy import cli 

14 

15 

16def test_rules(capsys: pytest.CaptureFixture[str]) -> None: 

17 assert cli.main(['rules', 'federal']) == 0 

18 output = capsys.readouterr().out 

19 assert 'rules are valid' in output and 'outcome' not in output 

20 assert ' review_district' in output and ' party1_appellant' not in output 

21 assert cli.main(['rules', 'lexis_nexis_header']) == 0 

22 output = capsys.readouterr().out 

23 assert ' party1_appellant' in output and ' court_name' in output 

24 

25 

26def test_bad_rules(tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: 

27 path = tmp_path / 'bad.csv' 

28 path.write_text('target,variable,kind,pattern,ignorecase,dotall\nopinion,x,oops,x,TRUE,FALSE\n', 

29 encoding = 'utf-8') 

30 assert cli.main(['rules', str(path)]) == 1 

31 assert 'row 2' in capsys.readouterr().err 

32 

33 

34def test_parse(court_listener_folder: pathlib.Path, tmp_path: pathlib.Path) -> None: 

35 output = tmp_path / 'cases.csv' 

36 assert cli.main(['-q', 'parse', str(court_listener_folder), '--output', str(output)]) == 0 

37 table = courtpy.Cases.load(output).data 

38 assert 'outcome_reversal' in table.columns 

39 # The whole dataset is saved beside the table. 

40 whole = courtpy.Cases.load(output.with_suffix('.joblib')) 

41 assert [e['technique'] for e in whole.history][-1] == 'save_data' 

42 

43 

44def test_split_and_parse_lexis(tmp_path: pathlib.Path) -> None: 

45 fixtures = pathlib.Path(__file__).parent / 'fixtures' 

46 folder = tmp_path / 'lexis' 

47 assert cli.main(['-q', 'split', str(fixtures), '--folder', str(folder)]) == 0 

48 output = tmp_path / 'lexis.csv' 

49 assert cli.main([ 

50 '-q', 'parse', str(folder), '--source', 'lexis_nexis', '--output', str(output), 

51 '--no-code']) == 0 

52 assert len(courtpy.Cases.load(output).data) == 2 

53 

54 

55def test_key_commands(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: 

56 assert cli.main(['key', 'show']) == 1 

57 monkeypatch.setattr('sys.stdin', io.StringIO('abcd1234efgh5678\n')) 

58 assert cli.main(['key', 'set', '--stdin', '--store', 'file']) == 0 

59 assert cli.main(['key', 'show']) == 0 

60 output = capsys.readouterr().out 

61 assert 'abcd' in output and '5678' in output and 'abcd1234efgh5678' not in output 

62 assert cli.main(['key', 'delete']) == 0 

63 assert courtpy.secrets.find_api_key() is None 

64 

65 

66def test_download( 

67 tmp_path: pathlib.Path, 

68 monkeypatch: pytest.MonkeyPatch, 

69 capsys: pytest.CaptureFixture[str]) -> None: 

70 calls = [] 

71 

72 def record(self: courtpy.CourtListener, *args: object, **kwargs: object) -> list[pathlib.Path]: 

73 calls.append((self, args, kwargs)) 

74 return [] 

75 

76 monkeypatch.setattr(courtpy.CourtListener, 'download', record) 

77 monkeypatch.chdir(tmp_path) 

78 assert cli.main([ 

79 '-q', 'download', '--courts', 'federal_geographic_circuits', 'scotus', 

80 '--max-cases', '3', '--bulk-date', '2026-09-30', '--stream']) == 0 

81 client, args, kwargs = calls[0] 

82 assert client.bulk_date == '2026-09-30' and client.stream 

83 assert args == ( 

84 ['federal_geographic_circuits', 'scotus'], None, None, pathlib.Path('courtlistener')) 

85 assert kwargs == { 

86 'method': 'bulk', 'max_cases': 3, 'dockets': False, 'refresh': False} 

87 assert '0 cases saved in courtlistener' in capsys.readouterr().out 

88 

89 

90def test_download_needs_a_key(capsys: pytest.CaptureFixture[str]) -> None: 

91 assert cli.main(['-q', 'download', '--method', 'api', '--courts', 'ca1']) == 1 

92 assert 'no CourtListener API key' in capsys.readouterr().err 

93 

94 

95def test_judges(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: 

96 asked: dict[str, Any] = {} 

97 

98 def from_fjc(**kwargs: Any) -> courtpy.judges.Roster: 

99 asked.update(kwargs) 

100 return courtpy.judges.Roster(pd.DataFrame({ 

101 'nid': [1, 1, 2], 'judge': ['A', 'A', 'B'], 'last_name': ['A', 'A', 'B'], 

102 'first_name': ['X', 'X', 'Y'], 'court_num': [1, 2, 1], 'circuit_num': [1, 2, 1], 

103 'start_year': [1990, 2000, 1995], 'end_year': [2000, 2010, 2005]})) 

104 

105 monkeypatch.setattr(courtpy.judges.Roster, 'from_fjc', from_fjc) 

106 output = tmp_path / 'roster.csv' 

107 assert cli.main(['-q', 'judges', '--no-jcs', '--output', str(output)]) == 0 

108 assert asked == {'update': False, 'jcs': False, 'martin_quinn': False, 'rulebook': 'judges'} 

109 assert output.is_file() 

110 assert 'A roster of 2 judges was saved' in capsys.readouterr().out 

111 

112 

113def test_study_commands(capsys: pytest.CaptureFixture[str]) -> None: 

114 # A study adds a command of its own and changes a default of courtpy's. 

115 

116 def greet(arguments: Any) -> int: 

117 print(f'hello {arguments.name} with {arguments.rulebook}') 

118 return 0 

119 

120 def add_commands(commands: Any) -> None: 

121 hello = commands.add_parser('hello') 

122 hello.add_argument('name') 

123 hello.set_defaults(command = greet, rulebook = 'careers.csv') 

124 commands.choices['judges'].set_defaults(rulebook = 'careers.csv') 

125 

126 assert cli.main(['hello', 'court'], prog = 'study', add_commands = add_commands) == 0 

127 assert capsys.readouterr().out == 'hello court with careers.csv\n' 

128 assert cli.main(['rules', 'no_such_rules'], prog = 'study', add_commands = add_commands) == 1 

129 assert capsys.readouterr().err.startswith('study: ') 

130 with pytest.raises(SystemExit): 

131 cli.main(['--help'], prog = 'study', add_commands = add_commands) 

132 assert 'hello' in capsys.readouterr().out