Coverage for tests/test_registries.py: 100%
97 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` registry factories."""
3from __future__ import annotations
5import dataclasses
6from typing import Any, ClassVar
8import pytest
9from conftest import Thing
11import wonka
12from wonka import registries
15@dataclasses.dataclass
16class Options(wonka.Subclasser):
17 """Base `Subclasser` for the tests."""
20@dataclasses.dataclass
21class Settings(Options):
22 """Intermediate subclass of `Options`."""
25@dataclasses.dataclass
26class Configuration(Settings):
27 """Indirect subclass of `Options` with stored contents.
29 Args:
30 contents: stored settings. Defaults to an empty `dict`.
32 """
34 contents: dict[str, Any] = dataclasses.field(default_factory = dict)
37@dataclasses.dataclass
38class Setup(Settings):
39 """Another indirect subclass of `Options`."""
42@dataclasses.dataclass
43class RegistrationDesk(wonka.Registrar):
44 """`Registrar` with a fixed registry."""
46 registry: ClassVar[dict[str, Any]] = {
47 'configuration': Configuration,
48 'setup': Setup,
49 'thing': Thing(value = 1)}
52@dataclasses.dataclass
53class Plugin(wonka.AutoRegistrar):
54 """`AutoRegistrar` family for the tests.
56 Args:
57 contents: stored settings. Defaults to an empty `dict`.
59 """
61 contents: dict[str, Any] = dataclasses.field(default_factory = dict)
64@dataclasses.dataclass
65class FastPlugin(Plugin):
66 """Direct subclass of `Plugin`."""
69@dataclasses.dataclass
70class SlowPlugin(FastPlugin):
71 """Indirect subclass of `Plugin`."""
74@dataclasses.dataclass
75class Gadget(wonka.AutoRegistrar):
76 """Second `AutoRegistrar` family for the tests."""
79@dataclasses.dataclass
80class Widget(Gadget):
81 """Direct subclass of `Gadget`."""
84""" Registrar """
87def test_registrar() -> None:
88 """Tests creating an instance from a registered class."""
89 config = RegistrationDesk.create(
90 'configuration',
91 parameters = {'contents': {'processors': 8}})
92 assert config.contents['processors'] == 8
93 assert isinstance(config, Configuration)
96def test_registrar_without_parameters_returns_class() -> None:
97 """Tests that a registered class is returned without parameters."""
98 assert RegistrationDesk.create('setup') is Setup
101def test_registrar_returns_copy_of_instance() -> None:
102 """Tests that changing a returned instance does not change the registry."""
103 thing = RegistrationDesk.create('thing', parameters = {'value': 2})
104 assert thing.value == 2
105 assert RegistrationDesk.registry['thing'].value == 1
108def test_registrar_accepts_kwargs() -> None:
109 """Tests that `create` accepts extra keyword arguments."""
110 assert RegistrationDesk.create('setup', extra = True) is Setup
113def test_registrar_missing_key() -> None:
114 """Tests that a missing key raises a `KeyError` with the key."""
115 with pytest.raises(KeyError, match = 'nope'):
116 RegistrationDesk.create('nope')
119""" Subclasser """
122def test_subclasser() -> None:
123 """Tests creating an instance of an indirect subclass."""
124 setup = Options.create(
125 'configuration',
126 parameters = {'contents': {'processors': 8}})
127 assert setup.contents['processors'] == 8
128 assert isinstance(setup, Configuration)
131def test_subclasser_indirect_and_missing() -> None:
132 """Tests direct, indirect, and missing subclasses."""
133 assert Options.create('setup') is Setup
134 assert isinstance(Options.create('settings', {}), Settings)
135 with pytest.raises(KeyError):
136 Options.create('options')
139def test_subclasser_from_intermediate_class() -> None:
140 """Tests that only subclasses of the calling class are found."""
141 assert Settings.create('setup') is Setup
142 with pytest.raises(KeyError):
143 Settings.create('settings')
146def test_get_all_subclasses_has_no_duplicates() -> None:
147 """Tests that a class with two parents in the family appears once."""
149 class Top:
150 """Top of a diamond inheritance."""
152 class Left(Top):
153 """Left side of a diamond inheritance."""
155 class Right(Top):
156 """Right side of a diamond inheritance."""
158 class Bottom(Left, Right):
159 """Bottom of a diamond inheritance."""
161 subclasses = registries._get_all_subclasses(Top)
162 assert subclasses == [Left, Bottom, Right]
165""" AutoRegistrar """
168def test_auto_registrar_registers_indirect_subclasses() -> None:
169 """Tests that direct and indirect subclasses are registered."""
170 assert Plugin.registry['fast_plugin'] is FastPlugin
171 assert Plugin.registry['slow_plugin'] is SlowPlugin
172 assert Plugin.registry['plugin'] is Plugin
175def test_auto_registrar_families_do_not_share_registries() -> None:
176 """Tests that each family gets its own registry."""
177 assert Plugin.registry is not Gadget.registry
178 assert wonka.AutoRegistrar.registry == {}
179 assert 'widget' in Gadget.registry
180 assert 'widget' not in Plugin.registry
181 assert 'fast_plugin' not in Gadget.registry
184def test_auto_registrar_create() -> None:
185 """Tests creating classes and instances from the registry."""
186 plugin = Plugin.create('fast_plugin', parameters = {'contents': {'a': 1}})
187 assert isinstance(plugin, FastPlugin)
188 assert plugin.contents == {'a': 1}
189 assert Plugin.create('slow_plugin') is SlowPlugin
190 with pytest.raises(KeyError):
191 Plugin.create('nope')
194def test_auto_registrar_custom_keyer() -> None:
195 """Tests that the global keyer names registered subclasses."""
196 wonka.set_keyer(lambda x: f'k_{x.__name__}')
198 @dataclasses.dataclass
199 class Custom(Plugin):
200 """Subclass registered with a custom key."""
202 assert Plugin.registry['k_Custom'] is Custom
205def test_auto_registrar_own_registry() -> None:
206 """Tests that a direct subclass with its own registry keeps it."""
207 own: dict[str, Any] = {}
209 @dataclasses.dataclass
210 class Tool(wonka.AutoRegistrar):
211 """`AutoRegistrar` family with a predefined registry."""
213 registry: ClassVar[dict[str, Any]] = own
215 assert Tool.registry is own
216 assert own == {'tool': Tool}
219if __name__ == '__main__':
220 test_registrar()
221 test_subclasser()