Coverage for tests/test_dispatchers.py: 100%

105 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-30 22:54 +0000

1"""Tests the `wonka` dispatcher factories.""" 

2 

3from __future__ import annotations 

4 

5import dataclasses 

6from collections.abc import MutableMapping 

7from typing import Any, ClassVar, NoReturn 

8 

9import pytest 

10 

11import wonka 

12from wonka import dispatchers 

13 

14 

15@dataclasses.dataclass 

16class Settings(wonka.Delegate): 

17 """`Delegate` that is created from a `dict`. 

18 

19 Args: 

20 contents: stored settings. Defaults to an empty `dict`. 

21 label: optional label. Defaults to `None`. 

22 

23 """ 

24 

25 contents: dict[str, Any] = dataclasses.field(default_factory = dict) 

26 label: str | None = None 

27 

28 @classmethod 

29 def from_dict( 

30 cls, 

31 item: dict[str, Any], 

32 label: str | None = None) -> Settings: 

33 """Returns a `Settings` instance from a `dict`. 

34 

35 Args: 

36 item: settings to store. 

37 label: optional label. Defaults to `None`. 

38 

39 Returns: 

40 A `Settings` instance. 

41 

42 """ 

43 return cls(contents = item, label = label) 

44 

45 

46@dataclasses.dataclass 

47class Configuration(wonka.Sourcerer): 

48 """`Sourcerer` that is created from a mapping.""" 

49 

50 contents: dict[str, Any] = dataclasses.field(default_factory = dict) 

51 sources: ClassVar[dict[Any, str]] = {MutableMapping: 'dictionary'} 

52 

53 @classmethod 

54 def from_dictionary(cls, item: dict[str, Any]) -> Configuration: 

55 """Returns a `Configuration` instance from a `dict`. 

56 

57 Args: 

58 item: settings to store. 

59 

60 Returns: 

61 A `Configuration` instance. 

62 

63 """ 

64 return cls(contents = item) 

65 

66 

67@dataclasses.dataclass 

68class Maker(wonka.Sourcerer): 

69 """`Sourcerer` with several sources. 

70 

71 Args: 

72 value: stored value. Defaults to `None`. 

73 

74 """ 

75 

76 value: Any = None 

77 sources: ClassVar[dict[Any, str]] = { 

78 bool: 'flag', 

79 int: 'number', 

80 MutableMapping: 'mapping', 

81 str: 'text', 

82 type: 'kind'} 

83 

84 @classmethod 

85 def from_flag(cls, item: bool) -> Maker: 

86 """Returns a `Maker` from a `bool`. 

87 

88 Args: 

89 item: value to store. 

90 

91 Returns: 

92 A `Maker` instance. 

93 

94 """ 

95 return cls(value = ('flag', item)) 

96 

97 @classmethod 

98 def from_number(cls, item: int) -> Maker: 

99 """Returns a `Maker` from an `int`. 

100 

101 Args: 

102 item: value to store. 

103 

104 Returns: 

105 A `Maker` instance. 

106 

107 """ 

108 return cls(value = item) 

109 

110 @classmethod 

111 def from_mapping(cls, item: MutableMapping[str, Any]) -> Maker: 

112 """Returns a `Maker` from a mapping. 

113 

114 Args: 

115 item: value to store. 

116 

117 Returns: 

118 A `Maker` instance. 

119 

120 """ 

121 return cls(value = dict(item)) 

122 

123 @classmethod 

124 def from_text(cls, item: str) -> Maker: 

125 """Returns a `Maker` from a `str`. 

126 

127 Args: 

128 item: value to store. 

129 

130 Returns: 

131 A `Maker` instance. 

132 

133 """ 

134 return cls(value = item) 

135 

136 @classmethod 

137 def from_kind(cls, item: type[Any]) -> Maker: 

138 """Returns a `Maker` from a class. 

139 

140 Args: 

141 item: class whose name is stored. 

142 

143 Returns: 

144 A `Maker` instance. 

145 

146 """ 

147 return cls(value = item.__name__) 

148 

149 

150@dataclasses.dataclass 

151class Broken(wonka.Sourcerer): 

152 """`Sourcerer` with a missing method and a method that fails.""" 

153 

154 sources: ClassVar[dict[Any, str]] = {int: 'missing', str: 'boom'} 

155 

156 @classmethod 

157 def from_boom(cls, item: str) -> NoReturn: 

158 """Raises an `AttributeError`. 

159 

160 Args: 

161 item: ignored item. 

162 

163 Raises: 

164 AttributeError: always. 

165 

166 """ 

167 message = 'internal failure' 

168 raise AttributeError(message) 

169 

170 

171def test_delegate() -> None: 

172 """Tests that `Delegate` calls the method named after the item's type.""" 

173 contents = {'tree': 'house', 'ghost': 'town'} 

174 settings = Settings.create(contents) 

175 assert settings.contents['tree'] == 'house' 

176 assert isinstance(settings, Settings) 

177 

178 

179def test_delegate_passes_kwargs_and_parameters() -> None: 

180 """Tests that `Delegate` passes kwargs and injects `parameters`.""" 

181 settings = Settings.create({'a': 1}, label = 'given') 

182 assert settings.label == 'given' 

183 settings = Settings.create({'a': 1}, parameters = {'label': 'injected'}) 

184 assert settings.label == 'injected' 

185 

186 

187def test_delegate_no_method() -> None: 

188 """Tests that `Delegate` raises an error for an unsupported type.""" 

189 with pytest.raises(AttributeError, match = 'from_int'): 

190 Settings.create(1) 

191 

192 

193def test_delegate_uses_global_method_namer() -> None: 

194 """Tests that `Delegate` uses the global method namer.""" 

195 

196 @dataclasses.dataclass 

197 class Builder(wonka.Delegate): 

198 """`Delegate` with a custom method naming convention.""" 

199 

200 @classmethod 

201 def make_int(cls, item: int) -> int: 

202 """Returns `item` negated. 

203 

204 Args: 

205 item: `int` to negate. 

206 

207 Returns: 

208 `item` negated. 

209 

210 """ 

211 return -item 

212 

213 wonka.set_method_namer(lambda x: f'make_{x}') 

214 assert Builder.create(3) == -3 

215 

216 

217def test_delegate_str_item_names_method() -> None: 

218 """Tests that a `str` item is the name used for the creation method.""" 

219 settings = Settings.create('dict') 

220 assert settings.contents == 'dict' 

221 

222 

223def test_sourcerer() -> None: 

224 """Tests that `Sourcerer` calls the method for a matching source.""" 

225 contents = {'tree': 'house', 'ghost': 'town'} 

226 configuration = Configuration.create(contents) 

227 assert configuration.contents['tree'] == 'house' 

228 assert isinstance(configuration, Configuration) 

229 

230 

231def test_sourcerer_skips_non_matching_kinds() -> None: 

232 """Tests that `Sourcerer` checks every source until one matches.""" 

233 assert Maker.create('hi').value == 'hi' 

234 assert Maker.create({'a': 1}).value == {'a': 1} 

235 assert Maker.create(3).value == 3 

236 

237 

238def test_sourcerer_checks_sources_in_order() -> None: 

239 """Tests that the first matching source is used.""" 

240 assert Maker.create(True).value == ('flag', True) 

241 

242 

243def test_sourcerer_matches_subclasses() -> None: 

244 """Tests that classes match sources that they are subclasses of.""" 

245 

246 class Count(int): 

247 """Subclass of `int`.""" 

248 

249 assert Maker.create(Count).value is Count 

250 assert Maker.create(Maker).value == 'Maker' 

251 

252 

253def test_sourcerer_no_match() -> None: 

254 """Tests that `Sourcerer` raises a `KeyError` without a match.""" 

255 with pytest.raises(KeyError, match = 'does not match'): 

256 Maker.create(3.5) 

257 

258 

259def test_missing_builder_method() -> None: 

260 """Tests that a missing builder method raises an `AttributeError`.""" 

261 with pytest.raises(AttributeError, match = 'from_missing'): 

262 Broken.create(1) 

263 

264 

265def test_builder_attribute_error_not_masked() -> None: 

266 """Tests that an `AttributeError` inside a builder is not replaced.""" 

267 with pytest.raises(AttributeError, match = 'internal failure'): 

268 Broken.create('x') 

269 

270 

271def test_is_kind() -> None: 

272 """Tests `_is_kind` with instances and classes.""" 

273 assert dispatchers._is_kind(bool, int) 

274 assert dispatchers._is_kind(True, int) 

275 assert not dispatchers._is_kind('x', int) 

276 assert not dispatchers._is_kind(str, int) 

277 

278 

279def test_get_creation_method_name() -> None: 

280 """Tests naming creation methods with the default and a custom namer.""" 

281 assert dispatchers._get_creation_method_name('text') == 'from_text' 

282 assert dispatchers._get_creation_method_name({}) == 'from_dict' 

283 name = dispatchers._get_creation_method_name( 

284 'text', 

285 method_namer = lambda x: f'build_{x}') 

286 assert name == 'build_text' 

287 

288 

289if __name__ == '__main__': 

290 test_delegate() 

291 test_sourcerer()