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
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-30 22:54 +0000
1"""Tests the `wonka` dispatcher factories."""
3from __future__ import annotations
5import dataclasses
6from collections.abc import MutableMapping
7from typing import Any, ClassVar, NoReturn
9import pytest
11import wonka
12from wonka import dispatchers
15@dataclasses.dataclass
16class Settings(wonka.Delegate):
17 """`Delegate` that is created from a `dict`.
19 Args:
20 contents: stored settings. Defaults to an empty `dict`.
21 label: optional label. Defaults to `None`.
23 """
25 contents: dict[str, Any] = dataclasses.field(default_factory = dict)
26 label: str | None = None
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`.
35 Args:
36 item: settings to store.
37 label: optional label. Defaults to `None`.
39 Returns:
40 A `Settings` instance.
42 """
43 return cls(contents = item, label = label)
46@dataclasses.dataclass
47class Configuration(wonka.Sourcerer):
48 """`Sourcerer` that is created from a mapping."""
50 contents: dict[str, Any] = dataclasses.field(default_factory = dict)
51 sources: ClassVar[dict[Any, str]] = {MutableMapping: 'dictionary'}
53 @classmethod
54 def from_dictionary(cls, item: dict[str, Any]) -> Configuration:
55 """Returns a `Configuration` instance from a `dict`.
57 Args:
58 item: settings to store.
60 Returns:
61 A `Configuration` instance.
63 """
64 return cls(contents = item)
67@dataclasses.dataclass
68class Maker(wonka.Sourcerer):
69 """`Sourcerer` with several sources.
71 Args:
72 value: stored value. Defaults to `None`.
74 """
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'}
84 @classmethod
85 def from_flag(cls, item: bool) -> Maker:
86 """Returns a `Maker` from a `bool`.
88 Args:
89 item: value to store.
91 Returns:
92 A `Maker` instance.
94 """
95 return cls(value = ('flag', item))
97 @classmethod
98 def from_number(cls, item: int) -> Maker:
99 """Returns a `Maker` from an `int`.
101 Args:
102 item: value to store.
104 Returns:
105 A `Maker` instance.
107 """
108 return cls(value = item)
110 @classmethod
111 def from_mapping(cls, item: MutableMapping[str, Any]) -> Maker:
112 """Returns a `Maker` from a mapping.
114 Args:
115 item: value to store.
117 Returns:
118 A `Maker` instance.
120 """
121 return cls(value = dict(item))
123 @classmethod
124 def from_text(cls, item: str) -> Maker:
125 """Returns a `Maker` from a `str`.
127 Args:
128 item: value to store.
130 Returns:
131 A `Maker` instance.
133 """
134 return cls(value = item)
136 @classmethod
137 def from_kind(cls, item: type[Any]) -> Maker:
138 """Returns a `Maker` from a class.
140 Args:
141 item: class whose name is stored.
143 Returns:
144 A `Maker` instance.
146 """
147 return cls(value = item.__name__)
150@dataclasses.dataclass
151class Broken(wonka.Sourcerer):
152 """`Sourcerer` with a missing method and a method that fails."""
154 sources: ClassVar[dict[Any, str]] = {int: 'missing', str: 'boom'}
156 @classmethod
157 def from_boom(cls, item: str) -> NoReturn:
158 """Raises an `AttributeError`.
160 Args:
161 item: ignored item.
163 Raises:
164 AttributeError: always.
166 """
167 message = 'internal failure'
168 raise AttributeError(message)
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)
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'
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)
193def test_delegate_uses_global_method_namer() -> None:
194 """Tests that `Delegate` uses the global method namer."""
196 @dataclasses.dataclass
197 class Builder(wonka.Delegate):
198 """`Delegate` with a custom method naming convention."""
200 @classmethod
201 def make_int(cls, item: int) -> int:
202 """Returns `item` negated.
204 Args:
205 item: `int` to negate.
207 Returns:
208 `item` negated.
210 """
211 return -item
213 wonka.set_method_namer(lambda x: f'make_{x}')
214 assert Builder.create(3) == -3
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'
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)
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
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)
243def test_sourcerer_matches_subclasses() -> None:
244 """Tests that classes match sources that they are subclasses of."""
246 class Count(int):
247 """Subclass of `int`."""
249 assert Maker.create(Count).value is Count
250 assert Maker.create(Maker).value == 'Maker'
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)
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)
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')
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)
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'
289if __name__ == '__main__':
290 test_delegate()
291 test_sourcerer()