Coverage for tests/conftest.py: 96%

102 statements  

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

1"""Shared fixtures for the tests.""" 

2 

3from __future__ import annotations 

4 

5import copy 

6import json 

7import pathlib 

8from collections.abc import Iterator 

9from typing import Any 

10 

11import chrisjen 

12import fjc_biographies.downloader 

13import fjc_idb.downloader 

14import pytest 

15 

16import courtpy 

17 

18FIXTURES = pathlib.Path(__file__).parent / 'fixtures' 

19 

20 

21@pytest.fixture(autouse = True) 

22def restore_library() -> Iterator[None]: 

23 """Removes the classes that a test adds to the library.""" 

24 saved = copy.deepcopy(chrisjen.library.contents) 

25 yield 

26 chrisjen.library.contents.clear() 

27 chrisjen.library.contents.update(saved) 

28 

29 

30@pytest.fixture(autouse = True) 

31def private_secrets( 

32 tmp_path: pathlib.Path, 

33 monkeypatch: pytest.MonkeyPatch) -> None: 

34 """Keeps tests away from the user's real API key and folders.""" 

35 monkeypatch.delenv(courtpy.options._ENV_API_KEY, raising = False) 

36 monkeypatch.setenv(courtpy.options._ENV_CONFIG, str(tmp_path / 'config')) 

37 monkeypatch.setenv(courtpy.options._ENV_DATA, str(tmp_path / 'data')) 

38 monkeypatch.setattr(courtpy.secrets, '_keyring', lambda: None) 

39 

40 

41def make_cluster(cluster_id: int, **changes: Any) -> dict[str, Any]: 

42 """Returns a CourtListener cluster like those the API returns.""" 

43 cluster = { 

44 'id': cluster_id, 

45 'absolute_url': f'/opinion/{cluster_id}/united-states-v-doe/', 

46 'docket_id': cluster_id * 10, 

47 'docket': f'https://www.courtlistener.com/api/rest/v4/dockets/{cluster_id * 10}/', 

48 'case_name': 'United States v. Doe', 

49 'case_name_full': ( 

50 'UNITED STATES of America, Plaintiff-Appellee, v. John DOE, ' 

51 'Defendant-Appellant'), 

52 'date_filed': '2020-03-04', 

53 'judges': 'Before Lynch, Howard, and Thompson, Circuit Judges.', 

54 'panel': [ 

55 'https://www.courtlistener.com/api/rest/v4/people/101/', 

56 'https://www.courtlistener.com/api/rest/v4/people/102/', 

57 'https://www.courtlistener.com/api/rest/v4/people/103/'], 

58 'citations': [{'volume': 950, 'reporter': 'F.3d', 'page': '12', 'type': 1}], 

59 'precedential_status': 'Published', 

60 'disposition': 'Reversed and remanded.', 

61 'attorneys': 'Jane Roe, Assistant United States Attorney, for appellee.', 

62 'procedural_history': '', 

63 'history': '', 

64 'nature_of_suit': '', 

65 'posture': '', 

66 'syllabus': '', 

67 'citation_count': 4} 

68 cluster.update(changes) 

69 return cluster 

70 

71 

72def make_opinion(opinion_id: int, cluster_id: int, **changes: Any) -> dict[str, Any]: 

73 """Returns a CourtListener opinion like those the API returns.""" 

74 opinion = { 

75 'id': opinion_id, 

76 'cluster_id': cluster_id, 

77 'cluster': f'https://www.courtlistener.com/api/rest/v4/clusters/{cluster_id}/', 

78 'type': '010combined', 

79 'author_id': 101, 

80 'author_str': 'Lynch', 

81 'per_curiam': False, 

82 'joined_by_str': '', 

83 'ordering_key': None, 

84 'html_with_citations': ( 

85 '<p>LYNCH, Circuit Judge. John Doe appeals his conviction for ' 

86 'possession of a firearm. He argues that the search violated the ' 

87 'Fourth Amendment. We review de novo.</p>' 

88 '<p><span class="star-pagination">*14</span>The district court ' 

89 'erred. See 554 U.S. 570 and 18 U.S.C. § 922(g). We reverse ' 

90 'and remand.</p>'), 

91 'plain_text': ''} 

92 opinion.update(changes) 

93 return opinion 

94 

95 

96def write_case( 

97 folder: pathlib.Path, 

98 cluster: dict[str, Any], 

99 opinions: list[dict[str, Any]], 

100 court: str = 'ca1') -> pathlib.Path: 

101 """Saves a CourtListener case the way the downloaders do.""" 

102 path = courtpy.courtlistener.case_path(folder, court, cluster['id']) 

103 courtpy.courtlistener.save_case(path, { 

104 'source': 'courtlistener', 

105 'court': { 

106 'id': court, 

107 'full_name': 'Court of Appeals for the First Circuit', 

108 'citation_string': '1st Cir.', 

109 'jurisdiction': 'F'}, 

110 'cluster': cluster, 

111 'docket': None, 

112 'citations': courtpy.courtlistener.citation_strings(cluster['citations']), 

113 'opinions': [courtpy.courtlistener.slim_opinion(o) for o in opinions]}) 

114 return path 

115 

116 

117@pytest.fixture 

118def court_listener_folder(tmp_path: pathlib.Path) -> pathlib.Path: 

119 """Returns a folder with three saved CourtListener cases.""" 

120 folder = tmp_path / 'courtlistener' 

121 write_case(folder, make_cluster(1), [make_opinion(11, 1)]) 

122 write_case( 

123 folder, 

124 make_cluster( 

125 2, case_name = 'Smith v. Acme Corp.', 

126 case_name_full = 'Mary SMITH, Plaintiff-Appellant, v. ACME CORP., Defendant-Appellee', 

127 disposition = 'Affirmed.', attorneys = 'Pat Lee for appellant.', 

128 precedential_status = 'Unpublished'), 

129 [ 

130 make_opinion(21, 2, html_with_citations = ( 

131 '<p>Smith appeals the dismissal of her Title VII claim. We ' 

132 'affirm.</p>')), 

133 make_opinion( 

134 22, 2, type = '040dissent', author_str = 'Thompson', 

135 html_with_citations = '<p>THOMPSON, Circuit Judge, dissenting. I would reverse.</p>')]) 

136 write_case( 

137 folder, 

138 make_cluster(3, disposition = '', case_name = 'Brown v. Board', 

139 case_name_full = 'Brown v. Board'), 

140 [make_opinion(31, 3, plain_text = 'We vacate the judgment.', html_with_citations = '')]) 

141 return folder 

142 

143@pytest.fixture 

144def recent_folder(tmp_path: pathlib.Path) -> pathlib.Path: 

145 """Returns a folder with a case like CourtListener's recent ones. 

146 

147 CourtListener has no full case name, judges, or disposition for it: the 

148 caption, the panel, and the decision are only in the opinion's text. 

149 

150 """ 

151 folder = tmp_path / 'recent' 

152 write_case( 

153 folder, 

154 make_cluster( 

155 4, case_name_full = '', judges = '', panel = [], disposition = '', 

156 attorneys = ''), 

157 [make_opinion(41, 4, author_str = '', per_curiam = True, html_with_citations = ( 

158 '<p>[DO NOT PUBLISH] In the United States Court of Appeals For the ' 

159 'First Circuit ____ No. 23-1234 ____</p>' 

160 '<p>UNITED STATES OF AMERICA, Plaintiff-Appellee, versus JOHN DOE, ' 

161 'Defendant-Appellant.</p>' 

162 '<p>Appeal from the United States District Court ____</p>' 

163 '<p>Before LYNCH, Chief Judge, and HOWARD and R. THOMPSON, Circuit ' 

164 'Judges.</p>' 

165 '<p>PER CURIAM: John Doe appeals his sentence for possession of a ' 

166 'firearm. We will reverse only if the district court abused its ' 

167 'discretion. It did not.</p><p>AFFIRMED.</p>'))]) 

168 return folder 

169 

170 

171 

172@pytest.fixture 

173def lexis_folder(tmp_path: pathlib.Path) -> pathlib.Path: 

174 """Returns a folder with the sample Lexis-Nexis cases, divided.""" 

175 folder = tmp_path / 'lexis_nexis' 

176 courtpy.lexis.split(FIXTURES / 'lexis_batch.txt', folder) 

177 return folder 

178 

179 

180class FakeResponse: 

181 """A response like those from `requests`.""" 

182 

183 def __init__( 

184 self, 

185 payload: Any = None, 

186 status_code: int = 200, 

187 headers: dict[str, str] | None = None) -> None: 

188 self.payload = payload 

189 self.status_code = status_code 

190 self.headers = headers or {} 

191 self.text = json.dumps(payload) 

192 

193 def json(self) -> Any: 

194 """Returns the payload.""" 

195 return self.payload 

196 

197 

198class FakeSession: 

199 """A session that answers requests from a list of handlers.""" 

200 

201 def __init__(self, handler: Any) -> None: 

202 self.handler = handler 

203 self.headers: dict[str, str] = {} 

204 self.calls: list[tuple[str, dict[str, Any] | None]] = [] 

205 self.sent_headers: list[dict[str, str] | None] = [] 

206 

207 def get(self, url: str, params: dict[str, Any] | None = None, **kwargs: Any) -> FakeResponse: 

208 """Records the request and returns the handler's response.""" 

209 self.calls.append((url, params)) 

210 self.sent_headers.append(kwargs.get('headers')) 

211 return self.handler(url, params) 

212 

213 

214class Reply: 

215 """The response of a web site to a request for a page or a file.""" 

216 

217 def __init__(self, content: bytes, status: int = 200) -> None: 

218 self.content = content 

219 self.status = status 

220 

221 @property 

222 def text(self) -> str: 

223 """Returns the content as text.""" 

224 return self.content.decode('utf-8') 

225 

226 def raise_for_status(self) -> None: 

227 """Raises an error for a response that failed.""" 

228 if self.status >= 400: 

229 raise RuntimeError(f'status {self.status}') 

230 

231 

232class Site: 

233 """A session that serves pages and files by their addresses.""" 

234 

235 def __init__(self, pages: dict[str, bytes | str], status: int = 200) -> None: 

236 self.pages = pages 

237 self.status = status 

238 self.headers: dict[str, str] = {} 

239 self.urls: list[str] = [] 

240 

241 def get(self, url: str, **kwargs: Any) -> Reply: 

242 """Records the request and returns the page or file at an address.""" 

243 self.urls.append(url) 

244 if url not in self.pages: 244 ↛ 245line 244 didn't jump to line 245 because the condition on line 244 was never true

245 return Reply(b'', 404) 

246 page = self.pages[url] 

247 return Reply(page.encode('utf-8') if isinstance(page, str) else page, self.status) 

248 

249 

250@pytest.fixture(autouse = True) 

251def no_network(monkeypatch: pytest.MonkeyPatch) -> None: 

252 """Stops a test from downloading anything from a real site.""" 

253 

254 def refuse(self: Any, method: str, url: str, **kwargs: Any) -> None: 

255 raise AssertionError(f'a test asked the network for {url}') 

256 

257 def refuse_fjc(url: str) -> None: 

258 raise AssertionError(f'a test asked the network for {url}') 

259 

260 monkeypatch.setattr(courtpy.utilities.requests.Session, 'request', refuse) 

261 # fjc-idb and fjc-biographies download with urllib rather than requests. 

262 monkeypatch.setattr(fjc_idb.downloader, '_open', refuse_fjc) 

263 monkeypatch.setattr(fjc_biographies.downloader, '_open', refuse_fjc)