Coverage for tests/test_base.py: 100%

263 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-14 09:29 +0000

1"""Tests the base module: the library, ideas, vertexes, and criteria.""" 

2 

3from __future__ import annotations 

4 

5import abc 

6import dataclasses 

7import pathlib 

8from typing import Any 

9 

10import pytest 

11 

12import chrisjen 

13from chrisjen import base 

14 

15SETTINGS = pathlib.Path(__file__).parent / 'cancer_settings.ini' 

16 

17 

18""" Library """ 

19 

20 

21def test_the_library_of_the_package() -> None: 

22 contents = chrisjen.library.contents 

23 assert contents['idea'] is chrisjen.Idea 

24 assert contents['vertex']['technique'] is chrisjen.Technique 

25 assert contents['vertex']['none'] is chrisjen.NullVertex 

26 assert contents['vertex']['worker'] == { 

27 'flow': chrisjen.Flow, 

28 'benchmark': chrisjen.Benchmark, 

29 'contest': chrisjen.Contest, 

30 'survey': chrisjen.Survey, 

31 } 

32 assert contents['report'] == {'summary': chrisjen.Summary} 

33 assert contents['criteria'] == {} 

34 

35 

36def test_abstract_classes_form_genres() -> None: 

37 class Shelf(chrisjen.Genre, abc.ABC): 

38 pass 

39 

40 class Fiction(Shelf, abc.ABC): 

41 pass 

42 

43 class Novel(Fiction): 

44 pass 

45 

46 class Mystery(Novel): 

47 pass 

48 

49 class Poem(Shelf): 

50 pass 

51 

52 assert chrisjen.library['shelf'] == { 

53 'fiction': {'novel': Novel, 'mystery': Mystery}, 

54 'poem': Poem, 

55 } 

56 assert 'shelf' in chrisjen.library.genres 

57 assert 'fiction' in chrisjen.library.genres 

58 assert 'shelfs' in chrisjen.library.plurals 

59 assert chrisjen.library.all['mystery'] is Mystery 

60 

61 

62def test_adding_a_genre_again_keeps_its_layer() -> None: 

63 class Shelf(chrisjen.Genre, abc.ABC): 

64 pass 

65 

66 class Novel(Shelf): 

67 pass 

68 

69 chrisjen.library.add(Shelf) 

70 assert chrisjen.library['shelf'] == {'novel': Novel} 

71 

72 

73def test_add_errors() -> None: 

74 with pytest.raises(TypeError, match = 'subclass of Genre'): 

75 chrisjen.library.add(int) 

76 with pytest.raises(ValueError, match = 'Genre itself'): 

77 chrisjen.library.add(chrisjen.Genre) 

78 

79 class Shelf(chrisjen.Genre, abc.ABC): 

80 pass 

81 

82 with pytest.raises(ValueError, match = "'shelf' is already a genre"): 

83 type('Shelf', (chrisjen.Genre,), {}) 

84 

85 class Bookend(chrisjen.Genre): 

86 pass 

87 

88 with pytest.raises(ValueError, match = "'bookend' is already a stored"): 

89 type('Bookend', (chrisjen.Genre, abc.ABC), {}) 

90 

91 

92def test_add_with_a_name_and_other_ways_to_add() -> None: 

93 class Bookend(chrisjen.Genre): 

94 pass 

95 

96 chrisjen.library.add(Bookend, name = 'stand') 

97 assert chrisjen.library['stand'] is Bookend 

98 chrisjen.library['prop'] = Bookend 

99 assert chrisjen.library['prop'] is Bookend 

100 assert (chrisjen.library + Bookend) is chrisjen.library 

101 chrisjen.library['shelf'] = {'novel': Bookend} 

102 assert chrisjen.library['shelf'] == {'novel': Bookend} 

103 

104 

105def test_classify() -> None: 

106 class Shelf(chrisjen.Genre, abc.ABC): 

107 pass 

108 

109 class Fiction(Shelf, abc.ABC): 

110 pass 

111 

112 class Novel(Fiction): 

113 pass 

114 

115 class Bookend(chrisjen.Genre): 

116 pass 

117 

118 assert chrisjen.library.classify('novel') == 'fiction' 

119 assert chrisjen.library.classify(Novel) == 'fiction' 

120 assert chrisjen.library.classify(Novel()) == 'fiction' 

121 assert chrisjen.library.classify('fiction') == 'shelf' 

122 assert chrisjen.library.classify(chrisjen.Contest) == 'worker' 

123 with pytest.raises(ValueError, match = 'not in a genre'): 

124 chrisjen.library.classify('shelf') 

125 with pytest.raises(ValueError, match = 'not in a genre'): 

126 chrisjen.library.classify(Bookend) 

127 with pytest.raises(ValueError, match = 'not in the library'): 

128 chrisjen.library.classify('nothing') 

129 with pytest.raises(ValueError, match = 'not in the library'): 

130 chrisjen.library.classify(int) 

131 

132 

133def test_delete() -> None: 

134 class Shelf(chrisjen.Genre, abc.ABC): 

135 pass 

136 

137 class Fiction(Shelf, abc.ABC): 

138 pass 

139 

140 class Novel(Fiction): 

141 pass 

142 

143 class Poem(Shelf): 

144 pass 

145 

146 del chrisjen.library['fiction'] 

147 assert chrisjen.library['shelf'] == {'poem': Poem} 

148 chrisjen.library.delete('poem') 

149 assert chrisjen.library['shelf'] == {} 

150 with pytest.raises(KeyError, match = 'not in the library'): 

151 chrisjen.library.delete('nothing') 

152 

153 

154def test_get_genre() -> None: 

155 assert chrisjen.library.get_genre('worker')['flow'] is chrisjen.Flow 

156 assert chrisjen.library.get_genre(chrisjen.Report) == { 

157 'summary': chrisjen.Summary} 

158 with pytest.raises(KeyError, match = 'not a layer'): 

159 chrisjen.library.get_genre('flow') 

160 

161 

162def test_borrow() -> None: 

163 class Analyst(chrisjen.Contest): 

164 pass 

165 

166 library = chrisjen.library 

167 assert library.borrow('flow') is chrisjen.Flow 

168 assert library.borrow(['analyst', 'flow'], genre = 'worker') is Analyst 

169 assert library.borrow(['critic', 'flow'], genre = 'worker') is chrisjen.Flow 

170 # Only classes in the genre are found. 

171 with pytest.raises(KeyError, match = "no class named 'technique'"): 

172 library.borrow('technique', genre = 'worker') 

173 with pytest.raises(KeyError, match = r"no class named \['a', 'b'\]"): 

174 library.borrow(['a', 'b']) 

175 

176 

177def test_a_separate_library() -> None: 

178 library = chrisjen.Library() 

179 library.add(chrisjen.Flow) 

180 assert library.contents == {'vertex': {'worker': {'flow': chrisjen.Flow}}} 

181 assert list(library) == ['vertex'] 

182 assert len(library) == 1 

183 

184 

185""" Idea """ 

186 

187 

188def test_idea_from_a_dict() -> None: 

189 idea = chrisjen.Idea.create({ 

190 'general': {'verbose': True}, 

191 'files': {'root': 'data'}, 

192 'demo_project': {'demo_workers': 'prepare, model'}, 

193 'prepare': { 

194 'steps': 'clean, scale', 

195 'clean_techniques': 'drop, none', 

196 'criterion': 'accuracy', 

197 'scale_criterion': 'variance', 

198 }, 

199 'model': {'design': 'contest', 'techniques': ['forest', 'linear']}, 

200 'scale_parameters': {'factor': 3}, 

201 }) 

202 assert isinstance(idea, chrisjen.Idea) 

203 assert list(idea.workers) == ['demo', 'prepare', 'model'] 

204 assert idea.parameters == {'scale': {'factor': 3}} 

205 assert idea.designs == { 

206 'model': 'contest', 'demo': 'flow', 'prepare': 'flow'} 

207 assert idea.criteria == {'prepare': 'accuracy', 'scale': 'variance'} 

208 assert idea.steps == { 

209 'demo': ['prepare', 'model'], 'prepare': ['clean', 'scale']} 

210 assert idea.techniques == { 

211 'clean': ['drop', 'none'], 'model': ['forest', 'linear']} 

212 

213 

214def test_idea_from_a_file() -> None: 

215 idea = chrisjen.Idea.create(SETTINGS) 

216 assert list(idea.workers) == [ 

217 'wisconsin_cancer', 'wrangler', 'analyst', 'critic'] 

218 assert idea.designs == { 

219 'wisconsin_cancer': 'flow', 

220 'analyst': 'contest', 

221 'critic': 'flow', 

222 'wrangler': 'flow', 

223 } 

224 assert idea.steps['wisconsin_cancer'] == ['wrangler', 'analyst', 'critic'] 

225 assert idea.techniques['scale'] == ['minmax', 'robust', 'normalize'] 

226 assert idea.parameters['scaler']['n_bins'] == 5 

227 assert idea.criteria == {} 

228 

229 

230def test_get_settings() -> None: 

231 idea = chrisjen.Idea.create({ 

232 'demo_project': {'max_iterations': 5, 'scale_copy': False}, 

233 'model': {'max_iterations': 2, 'label': 'target'}, 

234 }) 

235 assert idea.get_settings('demo', ['max_iterations', 'label']) == { 

236 'max_iterations': 5} 

237 assert idea.get_settings('model', ['max_iterations', 'label']) == { 

238 'max_iterations': 2, 'label': 'target'} 

239 assert idea.get_settings('scale', ['copy']) == {'copy': False} 

240 assert idea.get_settings('other', ['copy']) == {} 

241 

242 

243def test_idea_ignores_settings_that_are_not_sections() -> None: 

244 idea = chrisjen.Idea.create({ 

245 'version': 2, 

246 'demo_project': {'techniques': 'none'}, 

247 'none_parameters': {'unused': True}, 

248 }) 

249 assert list(idea.workers) == ['demo'] 

250 assert idea.parameters == {'none': {'unused': True}} 

251 

252 

253def test_steps_take_precedence_over_workers() -> None: 

254 idea = chrisjen.Idea.create( 

255 {'a_project': {'a_workers': 'x', 'steps': 'y'}}) 

256 assert idea.steps == {'a': ['y']} 

257 

258 

259""" Vertex """ 

260 

261 

262def test_vertexes_are_hashed_and_compared_by_name() -> None: 

263 first = chrisjen.Technique(name = 'same', contents = len) 

264 second = chrisjen.NullVertex(name = 'same') 

265 assert first == second 

266 assert hash(first) == hash('same') 

267 assert first == 'same' 

268 assert len({first, second}) == 1 

269 

270 

271def test_apply_merges_parameters() -> None: 

272 @dataclasses.dataclass 

273 class Adder(chrisjen.Vertex): 

274 def apply(self, item: Any, **kwargs: Any) -> Any: 

275 return item + kwargs.get('amount', 0) 

276 

277 vertex = Adder(name = 'a', parameters = {'amount': 2}) 

278 assert vertex.apply(1) == 3 

279 assert vertex.apply(1, amount = 10) == 11 

280 with pytest.raises(TypeError): 

281 chrisjen.Vertex() 

282 

283 

284def test_apply_called_through_super_is_not_wrapped_again() -> None: 

285 @dataclasses.dataclass 

286 class Adder(chrisjen.Vertex): 

287 def apply(self, item: Any, **kwargs: Any) -> Any: 

288 return item + kwargs.get('amount', 0) 

289 

290 @dataclasses.dataclass 

291 class Doubler(Adder): 

292 def apply(self, item: Any, **kwargs: Any) -> Any: 

293 # Uses up "amount", which the parent class must not get back from 

294 # `parameters`. 

295 amount = kwargs.pop('amount', 0) 

296 return super().apply(item * 2, **kwargs) + amount 

297 

298 @dataclasses.dataclass 

299 class Inheritor(Doubler): 

300 pass 

301 

302 vertex = Doubler(name = 'd', parameters = {'amount': 3}) 

303 assert vertex.apply(1) == 5 

304 assert vertex.apply(1, amount = 10) == 12 

305 assert Inheritor(name = 'i', parameters = {'amount': 3}).apply(1) == 5 

306 assert Adder(name = 'a', parameters = {'amount': 3}).apply(1) == 4 

307 

308 

309def test_apply_accepts_a_parameter_named_method() -> None: 

310 @dataclasses.dataclass 

311 class Chooser(chrisjen.Vertex): 

312 def apply(self, item: Any, **kwargs: Any) -> Any: 

313 return kwargs['method'] 

314 

315 vertex = Chooser(name = 'c', parameters = {'method': 'mean'}) 

316 assert vertex.apply(1) == 'mean' 

317 assert vertex.apply(1, method = 'median') == 'median' 

318 

319 

320def test_apply_from_a_mixin_is_wrapped() -> None: 

321 class Mixin: 

322 def apply(self, item: Any, **kwargs: Any) -> Any: 

323 return item + kwargs.get('amount', 0) 

324 

325 @dataclasses.dataclass 

326 class Adder(Mixin, chrisjen.Vertex): 

327 pass 

328 

329 assert Adder(name = 'a', parameters = {'amount': 2}).apply(1) == 3 

330 

331 

332def test_call_apply_can_be_overridden() -> None: 

333 @dataclasses.dataclass 

334 class Logged(chrisjen.Vertex): 

335 calls: list[Any] = dataclasses.field(default_factory = list) 

336 

337 def apply(self, item: Any, **kwargs: Any) -> Any: 

338 return item + 1 

339 

340 def _call_apply( 

341 self, 

342 method: Any, 

343 item: Any, 

344 /, 

345 **kwargs: Any) -> Any: 

346 result = super()._call_apply(method, item, **kwargs) 

347 self.calls.append(result) 

348 return result 

349 

350 @dataclasses.dataclass 

351 class Twice(Logged): 

352 def apply(self, item: Any, **kwargs: Any) -> Any: 

353 return super().apply(super().apply(item)) 

354 

355 vertex = Twice(name = 't') 

356 assert vertex.apply(0) == 2 

357 assert vertex.calls == [2] 

358 

359 

360def test_build_passes_settings_to_the_constructor() -> None: 

361 class Holder: 

362 idea = chrisjen.Idea.create({ 

363 'grow_project': {'max_iterations': 3, 'unknown': 'skipped'}, 

364 'grow_parameters': {'factor': 2}, 

365 }) 

366 

367 bench = chrisjen.Benchmark.build('grow', Holder()) 

368 assert bench.name == 'grow' 

369 assert bench.max_iterations == 3 

370 assert bench.parameters == {'factor': 2} 

371 # Arguments win over the settings. 

372 bench = chrisjen.Benchmark.build( 

373 'grow', Holder(), {'factor': 5}, max_iterations = 9) 

374 assert bench.max_iterations == 9 

375 assert bench.parameters == {'factor': 5} 

376 

377 

378def test_build_takes_general_settings_that_are_shared() -> None: 

379 class Holder: 

380 idea = chrisjen.Idea.create({ 

381 'general': {'conserve_memory': True, 'max_iterations': 3}, 

382 'race_project': {'design': 'contest'}, 

383 'keep_project': {'design': 'contest', 'conserve_memory': False}, 

384 }) 

385 

386 assert chrisjen.Contest.build('race', Holder()).conserve_memory 

387 # A worker's own setting wins over the general one. 

388 assert not chrisjen.Contest.build('keep', Holder()).conserve_memory 

389 # Only the settings in options._GENERAL_SETTINGS are shared. 

390 assert chrisjen.Benchmark.build('race', Holder()).max_iterations is None 

391 

392 

393""" Criteria """ 

394 

395 

396def test_criteria_wraps_a_tool() -> None: 

397 criteria = chrisjen.Criteria(contents = sum) 

398 assert criteria.score([1, 2]) == 3 

399 assert criteria.test([1, 2]) 

400 assert not criteria.test([]) 

401 mean = chrisjen.Criteria(contents = 'statistics.fmean') 

402 assert mean.score([1, 2, 3]) == 2.0 

403 rounded = chrisjen.Criteria(contents = round, parameters = {'ndigits': 1}) 

404 assert rounded.score(3.14159) == 3.1 

405 

406 

407def test_criteria_without_a_tool() -> None: 

408 with pytest.raises(NotImplementedError, match = 'no tool'): 

409 chrisjen.Criteria().score(1) 

410 

411 

412def test_criteria_subclasses() -> None: 

413 @dataclasses.dataclass 

414 class Positive(chrisjen.Criteria): 

415 def score(self, item: Any) -> Any: 

416 return item > 0 

417 

418 assert chrisjen.library['criteria'] == {'positive': Positive} 

419 assert Positive().test(1) 

420 assert not Positive().test(-1) 

421 

422 

423def test_report_is_abstract() -> None: 

424 with pytest.raises(TypeError): 

425 base.Report()