Coverage for tests/test_utilities.py: 98%

180 statements  

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

1"""Tests shared utilities.""" 

2 

3from __future__ import annotations 

4 

5import abc 

6import inspect 

7from typing import Any 

8 

9import pytest 

10 

11from chrisjen import utilities 

12 

13 

14@pytest.mark.parametrize( 

15 ('item', 'expected'), 

16 [ 

17 (None, []), 

18 ('abc', ['abc']), 

19 ('', ['']), 

20 (b'ab', [b'ab']), 

21 ([1, 2], [1, 2]), 

22 ((1, 2), [1, 2]), 

23 (range(3), [0, 1, 2]), 

24 ({'a': 1}, ['a']), 

25 (5, [5]), 

26 (2.5, [2.5]), 

27 ], 

28) 

29def test_iterify(item: Any, expected: list[Any]) -> None: 

30 assert utilities._iterify(item) == expected 

31 

32 

33def test_iterify_returns_a_new_list() -> None: 

34 original = [1, 2] 

35 result = utilities._iterify(original) 

36 result.append(3) 

37 assert original == [1, 2] 

38 

39 

40class Vector: 

41 def __init__(self, values: list[float]) -> None: 

42 self.values = values 

43 

44 def __add__(self, other: Vector) -> Vector: 

45 return Vector([a + b for a, b in zip(self.values, other.values)]) 

46 

47 def __truediv__(self, divisor: int) -> Vector: 

48 return Vector([a / divisor for a in self.values]) 

49 

50 

51def test_average_of_numbers() -> None: 

52 assert utilities._average([1, 2, 3]) == 2 

53 assert utilities._average([1.5]) == 1.5 

54 assert utilities._average([1, 2]) == 1.5 

55 assert utilities._average((4, 6, 8, 10)) == 7 

56 

57 

58def test_average_of_objects_that_support_arithmetic() -> None: 

59 result = utilities._average([Vector([1, 2]), Vector([3, 6])]) 

60 assert result.values == [2, 4] 

61 

62 

63def test_average_does_not_change_its_items() -> None: 

64 first = Vector([1, 2]) 

65 utilities._average([first, Vector([3, 4])]) 

66 assert first.values == [1, 2] 

67 

68 

69def test_average_of_nothing() -> None: 

70 with pytest.raises(ValueError, match = 'empty'): 

71 utilities._average([]) 

72 

73 

74def test_average_of_things_that_cannot_be_added() -> None: 

75 with pytest.raises(TypeError, match = 'cannot average results of type str'): 

76 utilities._average(['a', 1]) 

77 with pytest.raises(TypeError, match = 'type list.*division by an int'): 

78 utilities._average([[1], [2]]) 

79 

80 

81def test_accepted_arguments_filters_by_signature() -> None: 

82 def function(item: Any, a: int, b: int = 1) -> None: 

83 return None 

84 

85 arguments = {'a': 1, 'b': 2, 'c': 3} 

86 assert utilities.accepted_arguments(function, arguments) == {'a': 1, 'b': 2} 

87 assert utilities.accepted_arguments(function, {}) == {} 

88 

89 

90def test_accepted_arguments_with_keywords_argument() -> None: 

91 def function(item: Any, **kwargs: Any) -> None: 

92 return None 

93 

94 arguments = {'a': 1, 'b': 2} 

95 result = utilities.accepted_arguments(function, arguments) 

96 assert result == arguments 

97 assert result is not arguments 

98 

99 

100def test_accepted_arguments_with_keyword_only_and_callable_objects() -> None: 

101 def function(item: Any, *, a: int) -> None: 

102 return None 

103 

104 assert utilities.accepted_arguments(function, {'a': 1, 'z': 2}) == {'a': 1} 

105 

106 class Callable: 

107 def __call__(self, item: Any, factor: int = 2) -> None: 

108 return None 

109 

110 assert utilities.accepted_arguments(Callable(), {'factor': 3, 'z': 1}) == { 

111 'factor': 3 

112 } 

113 

114 

115def test_accepted_arguments_when_signature_is_unavailable( 

116 monkeypatch: pytest.MonkeyPatch, 

117) -> None: 

118 def broken(function: Any) -> inspect.Signature: 

119 raise ValueError 

120 

121 monkeypatch.setattr(inspect, 'signature', broken) 

122 arguments = {'a': 1} 

123 assert utilities.accepted_arguments(len, arguments) == arguments 

124 

125 

126""" Importing by path """ 

127 

128 

129def test_import_object_from_dotted_and_colon_paths() -> None: 

130 import collections 

131 import os.path 

132 import statistics 

133 

134 assert utilities.import_object('statistics.fmean') is statistics.fmean 

135 assert utilities.import_object('statistics:fmean') is statistics.fmean 

136 assert utilities.import_object('statistics') is statistics 

137 assert utilities.import_object('os.path') is os.path 

138 assert utilities.import_object('builtins.str.upper') is str.upper 

139 assert utilities.import_object('builtins:str.upper') is str.upper 

140 assert ( 

141 utilities.import_object('collections:OrderedDict.fromkeys') 

142 == collections.OrderedDict.fromkeys 

143 ) 

144 assert utilities.import_object('statistics.NormalDist') is ( 

145 statistics.NormalDist 

146 ) 

147 

148 

149def test_import_object_errors() -> None: 

150 with pytest.raises(ImportError, match = "'no_such_module.tool'.*no module"): 

151 utilities.import_object('no_such_module.tool') 

152 with pytest.raises(ImportError, match = "'no_such_module:tool'.*no module"): 

153 utilities.import_object('no_such_module:tool') 

154 with pytest.raises(ImportError, match = "'statistics.nope'"): 

155 utilities.import_object('statistics.nope') 

156 with pytest.raises(ImportError, match = "'statistics:fmean.nope'"): 

157 utilities.import_object('statistics:fmean.nope') 

158 # A bare name that is not a module cannot be imported. 

159 with pytest.raises(ImportError): 

160 utilities.import_object('str.upper') 

161 

162 

163def test_import_object_does_not_hide_a_modules_own_import_errors( 

164 tmp_path: Any, monkeypatch: pytest.MonkeyPatch 

165) -> None: 

166 module = tmp_path / 'tt_broken_module.py' 

167 module.write_text('import tt_dependency_that_does_not_exist\n') 

168 monkeypatch.syspath_prepend(str(tmp_path)) 

169 with pytest.raises(ModuleNotFoundError) as error: 

170 utilities.import_object('tt_broken_module.tool') 

171 assert error.value.name == 'tt_dependency_that_does_not_exist' 

172 with pytest.raises(ModuleNotFoundError): 

173 utilities.import_object('tt_broken_module:tool') 

174 

175 

176def test_import_object_finds_modules_created_after_the_first_call( 

177 tmp_path: Any, monkeypatch: pytest.MonkeyPatch 

178) -> None: 

179 with pytest.raises(ImportError): 

180 utilities.import_object('tt_late_module.tool') 

181 (tmp_path / 'tt_late_module.py').write_text( 

182 'def tool(item):\n return 7\n' 

183 ) 

184 monkeypatch.syspath_prepend(str(tmp_path)) 

185 assert utilities.import_object('tt_late_module.tool')(0) == 7 

186 

187 

188def test_import_object_imports_submodules_that_are_not_imported_yet( 

189 tmp_path: Any, monkeypatch: pytest.MonkeyPatch 

190) -> None: 

191 package = tmp_path / 'tt_package' 

192 package.mkdir() 

193 (package / '__init__.py').write_text('') 

194 (package / 'sub.py').write_text('def tool(item):\n return item + 1\n') 

195 monkeypatch.syspath_prepend(str(tmp_path)) 

196 assert utilities.import_object('tt_package.sub.tool')(1) == 2 

197 assert utilities.import_object('tt_package.sub:tool')(1) == 2 

198 

199 

200""" Naming """ 

201 

202 

203def test_snakify() -> None: 

204 assert utilities._snakify('ThingOne') == 'thing_one' 

205 assert utilities._snakify('HTTPServer') == 'http_server' 

206 assert utilities._snakify('already_snake') == 'already_snake' 

207 assert utilities._snakify('Version2Thing') == 'version2_thing' 

208 assert utilities._snakify('') == '' 

209 

210 

211def test_namify() -> None: 

212 class ThingOne: 

213 pass 

214 

215 class Named: 

216 name = 'given' 

217 

218 instance_with_name = Named() 

219 instance_with_name.name = 'chosen' 

220 assert utilities._namify('text') == 'text' 

221 assert utilities._namify(ThingOne) == 'thing_one' 

222 assert utilities._namify(ThingOne()) == 'thing_one' 

223 assert utilities._namify(instance_with_name) == 'chosen' 

224 # A class attribute called name is not used for a class. 

225 assert utilities._namify(Named) == 'named' 

226 assert utilities._namify(5) == 'int' 

227 assert utilities._namify(len) == 'len' 

228 

229 

230""" Nested dicts and settings """ 

231 

232 

233LAYERS = { 

234 'vertex': { 

235 'technique': int, 

236 'step': {'scale': str}, 

237 'worker': {'flow': float, 'contest': list}, 

238 }, 

239 'idea': dict, 

240} 

241 

242 

243def test_flatten_dict_and_all_classes() -> None: 

244 expected = { 

245 'technique': int, 

246 'scale': str, 

247 'flow': float, 

248 'contest': list, 

249 'idea': dict, 

250 } 

251 assert utilities.flatten_dict(LAYERS) == expected 

252 assert utilities._all_classes(LAYERS) == expected 

253 # The first value found for a name is kept. 

254 assert utilities.flatten_dict({'a': {'x': 1}, 'b': {'x': 2}}) == {'x': 1} 

255 

256 

257def test_all_genres_and_all_keys() -> None: 

258 assert utilities._all_genres(LAYERS) == ['vertex', 'step', 'worker'] 

259 assert utilities._get_all_keys(LAYERS) == [ 

260 'vertex', 'technique', 'step', 'scale', 'worker', 'flow', 'contest', 

261 'idea'] 

262 

263 

264def test_find_and_find_genre() -> None: 

265 assert utilities._find(LAYERS, 'contest') is list 

266 assert utilities._find(LAYERS, 'step') == {'scale': str} 

267 assert utilities._find(LAYERS, 'nothing') is utilities._MISSING 

268 assert utilities._find_genre(LAYERS, 'contest') == 'worker' 

269 assert utilities._find_genre(LAYERS, 'technique') == 'vertex' 

270 assert utilities._find_genre(LAYERS, 'idea') is None 

271 assert utilities._find_genre(LAYERS, 'nothing') is utilities._MISSING 

272 

273 

274def test_get_path_and_is_abstract() -> None: 

275 class Root(abc.ABC): # noqa: B024 

276 pass 

277 

278 class Shelf(Root, abc.ABC): 

279 pass 

280 

281 class Novel(Shelf): 

282 pass 

283 

284 class Mystery(Novel): 

285 pass 

286 

287 assert utilities._is_abstract(Shelf) 

288 assert not utilities._is_abstract(Novel) 

289 assert utilities._get_path(Mystery, Root, utilities._namify) == ['shelf'] 

290 assert utilities._get_path(Shelf, Root, utilities._namify) == [] 

291 

292 

293@pytest.mark.parametrize( 

294 ('item', 'expected'), 

295 [ 

296 ('a, b,c', ['a', 'b', 'c']), 

297 (['a', 'b, c'], ['a', 'b', 'c']), 

298 ('single', ['single']), 

299 (' , ', []), 

300 (None, []), 

301 ], 

302) 

303def test_listify_names(item: Any, expected: list[str]) -> None: 

304 assert utilities.listify_names(item) == expected 

305 

306 

307def test_apply_path() -> None: 

308 class Adder: 

309 def __init__(self, amount: int) -> None: 

310 self.amount = amount 

311 

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

313 return item + self.amount + kwargs.get('bonus', 0) 

314 

315 path = [Adder(1), Adder(10)] 

316 assert utilities._apply_path(path, 0) == 11 

317 assert utilities._apply_path(path, 0, bonus = 100) == 211 

318 assert utilities._apply_path([], 5) == 5