Coverage for src/metaclass_registry/testing.py: 100%
17 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 00:39 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 00:39 +0000
1"""Test support: stand-in members of a registered family.
3A registry key names one class, so a test cannot define a second class under
4the key of a registered one, and a class a test does register stays registered
5for the rest of the process. ``restored_registry`` frees the keys a test's
6stand-ins need for the duration of a block and then puts the registry back
7exactly as it was.
8"""
10from collections.abc import Iterator
11from contextlib import contextmanager
13from .core import RegistryKey
16@contextmanager
17def restored_registry(
18 family: type,
19 *,
20 released: tuple[RegistryKey, ...] = (),
21) -> Iterator[None]:
22 """Restore ``family.__registry__`` on exit; free ``released`` keys inside.
24 Classes registered inside the block are not registered after it, and the
25 classes that held the released keys hold them again. Only the primary
26 registry is touched.
27 """
28 from .strategies import _invalidate_family_projections
30 registry: dict[RegistryKey, object] = getattr(family, "__registry__")
31 # Finish lazy discovery first: a discovery that ran inside the block would
32 # find the released keys occupied by stand-ins.
33 len(registry)
34 registered = dict(dict.items(registry))
35 for key in released:
36 dict.pop(registry, key, None)
37 _invalidate_family_projections()
38 try:
39 yield
40 finally:
41 dict.clear(registry)
42 dict.update(registry, registered)
43 _invalidate_family_projections()