Coverage for tests/test_clusters.py: 99%
111 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` constructor storage classes."""
3from __future__ import annotations
5import dataclasses
6from typing import Any, ClassVar
8import pytest
9from conftest import Adder, Doubler
11import wonka
14@dataclasses.dataclass
15class Options(wonka.Subclasser):
16 """Base `Subclasser` for the tests."""
19@dataclasses.dataclass
20class Settings(Options):
21 """Intermediate subclass of `Options`."""
24@dataclasses.dataclass
25class Configuration(Settings):
26 """Indirect subclass of `Options` with stored contents.
28 Args:
29 contents: stored settings. Defaults to an empty `dict`.
31 """
33 contents: dict[str, Any] = dataclasses.field(default_factory = dict)
36@dataclasses.dataclass
37class RegistrationDesk(wonka.Registrar):
38 """`Registrar` with a fixed registry."""
40 registry: ClassVar[dict[str, Any]] = {'configuration': Configuration}
43class Duck:
44 """Class with a `create` class method that is not a `wonka` class."""
46 @classmethod
47 def create(cls, item: Any) -> Any:
48 """Returns `item`.
50 Args:
51 item: item to return.
53 Returns:
54 `item`, unchanged.
56 """
57 return item
60def test_manufacturer() -> None:
61 """Tests creating items with constructors stored in a `Manufacturer`."""
62 depot = wonka.Manufacturer()
63 depot.add(Options)
64 depot.add({'registration': RegistrationDesk})
65 setup = depot['options'].create(
66 'configuration',
67 parameters = {'contents': {'processors': 8}})
68 assert setup.contents['processors'] == 8
69 assert isinstance(setup, Configuration)
70 registration = depot['registration'].create(
71 'configuration',
72 parameters = {'contents': {'tree': 'house'}})
73 assert registration.contents['tree'] == 'house'
74 assert isinstance(registration, Configuration)
77def test_add_validation() -> None:
78 """Tests that `add` rejects anything that is not a constructor."""
79 depot = wonka.Manufacturer()
80 with pytest.raises(TypeError):
81 depot.add(3) # type: ignore[arg-type]
82 with pytest.raises(TypeError):
83 depot.add({'ok': Adder, 'bad': 3}) # type: ignore[dict-item]
84 assert len(depot) == 0
87def test_add_manager_instance() -> None:
88 """Tests that a `Manager` instance can be stored."""
89 depot = wonka.Manufacturer()
90 depot.add({'line': wonka.Assembler([Adder, Doubler])})
91 assert depot['line'].create(1) == 4
94def test_add_uses_global_keyer() -> None:
95 """Tests that `add` names a single constructor with the global keyer."""
96 wonka.set_keyer(lambda x: x.__name__.upper())
97 depot = wonka.Manufacturer()
98 depot.add(Adder)
99 assert depot.keys() == ('ADDER',)
102def test_add_duck_type_with_relaxed_compatibility() -> None:
103 """Tests that relaxed compatibility allows other classes with `create`."""
104 depot = wonka.Manufacturer()
105 with pytest.raises(TypeError):
106 depot.add(Duck) # type: ignore[arg-type]
107 wonka.set_compatibility_rule(False)
108 depot.add(Duck) # type: ignore[arg-type]
109 assert depot['duck'] is Duck
112def test_mapping_interface() -> None:
113 """Tests the `dict`-like methods of `Manufacturer`."""
114 depot = wonka.Manufacturer()
115 depot.add(Adder)
116 depot.add({'doubler': Doubler})
117 assert depot.keys() == ('adder', 'doubler')
118 assert depot.values() == (Adder, Doubler)
119 assert depot.items() == (('adder', Adder), ('doubler', Doubler))
120 assert depot['adder'] is Adder
121 assert list(depot) == ['adder', 'doubler']
122 del depot['adder']
123 assert len(depot) == 1
124 with pytest.raises(KeyError):
125 del depot['adder']
126 with pytest.raises(KeyError):
127 depot.delete('adder')
130def test_setitem() -> None:
131 """Tests setting a constructor with a key."""
132 depot = wonka.Manufacturer()
133 depot['x'] = Adder
134 assert depot['x'] is Adder
137def test_add_operator_returns_copy() -> None:
138 """Tests that `+` returns a new instance and leaves both unchanged."""
139 depot = wonka.Manufacturer({'adder': Adder})
140 combined = depot + Doubler
141 assert combined is not depot
142 assert combined.keys() == ('adder', 'doubler')
143 assert depot.keys() == ('adder',)
144 assert isinstance(combined, wonka.Manufacturer)
145 mapping = {'d': Doubler}
146 assert (depot + mapping).keys() == ('adder', 'd')
147 assert mapping == {'d': Doubler}
150def test_add_operator_validates() -> None:
151 """Tests that `+` raises the same errors as `add`."""
152 depot = wonka.Manufacturer()
153 with pytest.raises(TypeError):
154 depot + 3 # type: ignore[operator]
157def test_inplace_add_operator() -> None:
158 """Tests that `+=` adds to the instance in place."""
159 depot = wonka.Manufacturer()
160 original = depot
161 depot += Adder
162 depot += {'doubler': Doubler}
163 assert depot is original
164 assert depot.keys() == ('adder', 'doubler')
167def test_subset() -> None:
168 """Tests `subset` with `include`, `exclude`, or both."""
169 depot = wonka.Manufacturer(
170 {'adder': Adder, 'doubler': Doubler, 'options': Options})
171 assert depot.subset(include = 'adder').keys() == ('adder',)
172 assert depot.subset(exclude = 'adder').keys() == ('doubler', 'options')
173 assert depot.subset(
174 include = ['adder', 'doubler'],
175 exclude = ['doubler']).keys() == ('adder',)
176 assert depot.keys() == ('adder', 'doubler', 'options')
179def test_subset_returns_new_instance() -> None:
180 """Tests that `subset` does not share `contents` with the original."""
181 depot = wonka.Manufacturer({'adder': Adder})
182 subset = depot.subset(include = 'adder')
183 assert subset is not depot
184 subset['doubler'] = Doubler
185 assert depot.keys() == ('adder',)
188def test_subset_errors() -> None:
189 """Tests that `subset` raises errors for missing or absent arguments."""
190 depot = wonka.Manufacturer({'adder': Adder})
191 with pytest.raises(ValueError, match = 'include or exclude'):
192 depot.subset()
193 with pytest.raises(KeyError):
194 depot.subset(include = 'missing')
197if __name__ == '__main__':
198 test_manufacturer()