Coverage for tests/test_workers.py: 100%

145 statements  

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

1"""Tests the worker designs.""" 

2 

3from __future__ import annotations 

4 

5import dataclasses 

6from typing import Any 

7 

8import pytest 

9 

10import chrisjen 

11 

12 

13def technique(name: str, function: Any) -> chrisjen.Technique: 

14 return chrisjen.Technique(name = name, contents = function) 

15 

16 

17def worker(design: type, nodes: list[Any], **kwargs: Any) -> Any: 

18 built = design(name = 'w', **kwargs) 

19 built.populate(nodes) 

20 return built 

21 

22 

23""" Flow """ 

24 

25 

26def test_flow_applies_nodes_in_order() -> None: 

27 flow = worker( 

28 chrisjen.Flow, 

29 [ 

30 technique('add', lambda x: x + 1), 

31 technique('double', lambda x: x * 2), 

32 ]) 

33 assert flow.apply(1) == 4 

34 

35 

36def test_flow_passes_keyword_arguments_to_its_nodes() -> None: 

37 def shift(item: Any, amount: int = 0) -> Any: 

38 return item + amount 

39 

40 flow = worker(chrisjen.Flow, [technique('shift', shift)]) 

41 assert flow.apply(1, amount = 5) == 6 

42 flow.parameters = {'amount': 2} 

43 assert flow.apply(1) == 3 

44 

45 

46def test_a_list_in_a_flow_is_applied_in_order() -> None: 

47 flow = worker( 

48 chrisjen.Flow, 

49 [ 

50 technique('add', lambda x: x + 1), 

51 [ 

52 technique('double', lambda x: x * 2), 

53 technique('neg', lambda x: -x), 

54 ], 

55 ]) 

56 assert [[node.name for node in path] for path in flow.walk()] == [ 

57 ['add', 'double', 'neg']] 

58 assert flow.apply(1) == -4 

59 

60 

61def test_an_empty_flow_returns_the_item() -> None: 

62 assert chrisjen.Flow(name = 'empty').apply(5) == 5 

63 

64 

65def test_workers_of_workers() -> None: 

66 inner = worker(chrisjen.Flow, [technique('add', lambda x: x + 1)]) 

67 inner.name = 'inner' 

68 outer = worker( 

69 chrisjen.Flow, [inner, technique('negate', lambda x: -x)]) 

70 assert outer.apply(1) == -2 

71 

72 

73""" Benchmark """ 

74 

75 

76def test_benchmark_repeats_until_the_criteria_is_met() -> None: 

77 bench = worker( 

78 chrisjen.Benchmark, 

79 [technique('double', lambda x: x * 2)], 

80 criteria = chrisjen.Criteria(contents = lambda x: x > 100)) 

81 assert bench.apply(1) == 128 

82 assert bench.iterations == 7 

83 

84 

85def test_benchmark_stops_at_max_iterations() -> None: 

86 bench = worker( 

87 chrisjen.Benchmark, 

88 [technique('add', lambda x: x + 1)], 

89 criteria = chrisjen.Criteria(contents = lambda x: False), 

90 max_iterations = 3) 

91 assert bench.apply(0) == 3 

92 assert bench.iterations == 3 

93 

94 

95def test_benchmark_needs_criteria() -> None: 

96 with pytest.raises(ValueError, match = 'needs criteria'): 

97 chrisjen.Benchmark(name = 'b').apply(1) 

98 

99 

100""" Contest """ 

101 

102 

103def test_contest_keeps_the_best_path() -> None: 

104 contest = worker( 

105 chrisjen.Contest, 

106 [[technique('half', lambda x: x / 2), chrisjen.NullVertex()]], 

107 criteria = chrisjen.Criteria(contents = lambda x: x)) 

108 assert contest.apply(10) == 10 

109 assert contest.winner == 'none' 

110 assert contest.results == {'half': 5.0, 'none': 10} 

111 

112 

113def test_contest_tries_every_combination() -> None: 

114 contest = worker( 

115 chrisjen.Contest, 

116 [ 

117 [ 

118 technique('add', lambda x: x + 1), 

119 technique('double', lambda x: x * 2), 

120 ], 

121 [technique('negate', lambda x: -x), chrisjen.NullVertex()], 

122 ], 

123 criteria = chrisjen.Criteria(contents = lambda x: x)) 

124 assert contest.apply(3) == 6 

125 assert contest.results == { 

126 'add > negate': -4, 

127 'add > none': 4, 

128 'double > negate': -6, 

129 'double > none': 6, 

130 } 

131 assert contest.winner == 'double > none' 

132 

133 

134def test_each_path_uses_its_own_copies_of_the_nodes() -> None: 

135 @dataclasses.dataclass 

136 class Counter(chrisjen.Technique): 

137 calls: int = 0 

138 

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

140 self.calls += 1 

141 return self.calls 

142 

143 counter = Counter(name = 'counter') 

144 survey = worker( 

145 chrisjen.Survey, 

146 [counter, [technique('a', lambda x: x), technique('b', lambda x: x)]]) 

147 assert survey.results == {} 

148 assert survey.apply(0) == 1 

149 assert survey.results == {'counter > a': 1, 'counter > b': 1} 

150 assert counter.calls == 0 

151 

152 

153def test_contest_ties_go_to_the_first_path() -> None: 

154 contest = worker( 

155 chrisjen.Contest, 

156 [[technique('a', lambda x: x), technique('b', lambda x: x)]], 

157 criteria = chrisjen.Criteria(contents = lambda x: 0)) 

158 contest.apply(1) 

159 assert contest.winner == 'a' 

160 

161 

162def test_contest_does_not_change_the_input() -> None: 

163 def append(item: list[int]) -> list[int]: 

164 item.append(1) 

165 return item 

166 

167 contest = worker( 

168 chrisjen.Contest, 

169 [[technique('a', append), technique('b', append)]], 

170 criteria = chrisjen.Criteria(contents = len)) 

171 original: list[int] = [] 

172 assert contest.apply(original) == [1] 

173 assert original == [] 

174 

175 

176def test_contest_scores_every_path() -> None: 

177 contest = worker( 

178 chrisjen.Contest, 

179 [[technique('half', lambda x: x / 2), chrisjen.NullVertex()]], 

180 criteria = chrisjen.Criteria(contents = lambda x: -x)) 

181 assert contest.apply(10) == 5.0 

182 assert contest.scores == {'half': -5.0, 'none': -10} 

183 

184 

185def test_contest_that_conserves_memory_keeps_only_the_winner() -> None: 

186 contest = worker( 

187 chrisjen.Contest, 

188 [[ 

189 technique('half', lambda x: x / 2), 

190 chrisjen.NullVertex(), 

191 technique('third', lambda x: x / 3), 

192 ]], 

193 criteria = chrisjen.Criteria(contents = lambda x: x), 

194 conserve_memory = True) 

195 assert contest.apply(12) == 12 

196 assert contest.winner == 'none' 

197 assert contest.results == {'none': 12} 

198 assert contest.scores == {'half': 6.0, 'none': 12, 'third': 4.0} 

199 

200 

201def test_a_design_can_observe_each_result_before_it_is_dropped() -> None: 

202 @dataclasses.dataclass 

203 class Noting(chrisjen.Contest): 

204 notes: dict[str, Any] = dataclasses.field(default_factory = dict) 

205 

206 def _observe(self, label: str, result: Any) -> None: 

207 self.notes[label] = (result, self.scores[label]) 

208 

209 contest = worker( 

210 Noting, 

211 [[technique('half', lambda x: x / 2), chrisjen.NullVertex()]], 

212 criteria = chrisjen.Criteria(contents = lambda x: -x), 

213 conserve_memory = True) 

214 assert contest.apply(10) == 5.0 

215 assert contest.results == {'half': 5.0} 

216 assert contest.notes == {'half': (5.0, -5.0), 'none': (10, -10)} 

217 

218 

219class Big: 

220 """A result that counts how many of its kind are in memory.""" 

221 

222 alive = 0 

223 most = 0 

224 

225 def __init__(self, size: int) -> None: 

226 self.size = size 

227 Big.alive += 1 

228 Big.most = max(Big.most, Big.alive) 

229 

230 def __del__(self) -> None: 

231 Big.alive -= 1 

232 

233 def __add__(self, other: Big) -> Big: 

234 return Big(self.size + other.size) 

235 

236 def __truediv__(self, count: int) -> float: 

237 return self.size / count 

238 

239 

240def most_in_memory(design: type, conserve_memory: bool, **kwargs: Any) -> int: 

241 built = worker( 

242 design, 

243 [[technique(str(n), lambda x, n = n: Big(n)) for n in range(6)]], 

244 conserve_memory = conserve_memory, 

245 **kwargs) 

246 Big.alive = Big.most = 0 

247 built.apply(0) 

248 return Big.most 

249 

250 

251def test_conserving_memory_drops_results_as_paths_are_applied() -> None: 

252 criteria = chrisjen.Criteria(contents = lambda x: x.size % 4) 

253 assert most_in_memory(chrisjen.Contest, False, criteria = criteria) == 6 

254 assert most_in_memory(chrisjen.Contest, True, criteria = criteria) == 2 

255 # The running total and the newest result. 

256 assert most_in_memory(chrisjen.Survey, True) <= 3 

257 

258 

259def test_contest_errors() -> None: 

260 with pytest.raises(ValueError, match = 'no paths'): 

261 chrisjen.Contest(name = 'c').apply(1) 

262 contest = worker(chrisjen.Contest, [technique('a', lambda x: x)]) 

263 with pytest.raises(ValueError, match = 'needs criteria'): 

264 contest.apply(1) 

265 

266 

267""" Survey """ 

268 

269 

270def test_survey_averages_the_paths() -> None: 

271 survey = worker( 

272 chrisjen.Survey, 

273 [[technique('half', lambda x: x / 2), chrisjen.NullVertex()]]) 

274 assert survey.apply(4) == 3.0 

275 assert survey.average == 3.0 

276 assert survey.results == {'half': 2.0, 'none': 4} 

277 

278 

279def test_survey_that_conserves_memory_keeps_no_results() -> None: 

280 survey = worker( 

281 chrisjen.Survey, 

282 [[technique('half', lambda x: x / 2), chrisjen.NullVertex()]], 

283 conserve_memory = True) 

284 assert survey.apply(4) == 3.0 

285 assert survey.results == {} 

286 

287 

288def test_survey_of_paths_with_several_nodes() -> None: 

289 inner = worker( 

290 chrisjen.Flow, 

291 [technique('add', lambda x: x + 1), technique('add2', lambda x: x + 2)]) 

292 inner.name = 'inner' 

293 survey = worker(chrisjen.Survey, [[inner, chrisjen.NullVertex()]]) 

294 assert survey.apply(1) == 2.5