Contain all registry logic in helper methods.

This commit is contained in:
Emil Stenström 2020-02-15 09:37:35 +01:00
parent ecba6e3ed9
commit b2726a6832
4 changed files with 22 additions and 8 deletions

View file

@ -15,7 +15,18 @@ class ComponentRegistry(object):
self._registry[name] = component
def unregister(self, name):
self.get(name)
del self._registry[name]
def get(self, name):
if name not in self._registry:
raise NotRegistered('The component "%s" is not registered' % name)
del self._registry[name]
return self._registry[name]
def all(self):
return self._registry
def clear(self):
self._registry = {}

View file

@ -7,7 +7,7 @@ register = template.Library()
@register.simple_tag(name="component_dependencies")
def component_dependencies_tag():
unique_component_classes = set(registry._registry.values())
unique_component_classes = set(registry.all().values())
out = []
for component_class in unique_component_classes:
@ -18,6 +18,6 @@ def component_dependencies_tag():
@register.simple_tag(name="component")
def component_tag(name, *args, **kwargs):
component_class = registry._registry[name]
component_class = registry.get(name)
component = component_class()
return component.render(*args, **kwargs)

View file

@ -13,7 +13,7 @@ class ComponentRegistryTest(unittest.TestCase):
def test_simple_register(self):
self.registry.register(name="testcomponent", component=MockComponent)
self.assertEqual(
self.registry._registry,
self.registry.all(),
{"testcomponent": MockComponent}
)
@ -21,8 +21,11 @@ class ComponentRegistryTest(unittest.TestCase):
self.registry.register(name="testcomponent", component=MockComponent)
self.registry.register(name="testcomponent2", component=MockComponent)
self.assertEqual(
self.registry._registry,
{"testcomponent": MockComponent, "testcomponent2": MockComponent}
self.registry.all(),
{
"testcomponent": MockComponent,
"testcomponent2": MockComponent,
}
)
def test_prevent_registering_twice(self):
@ -33,7 +36,7 @@ class ComponentRegistryTest(unittest.TestCase):
def test_simple_unregister(self):
self.registry.register(name="testcomponent", component=MockComponent)
self.registry.unregister(name="testcomponent")
self.assertEqual(self.registry._registry, {})
self.assertEqual(self.registry.all(), {})
def test_raises_on_failed_unregister(self):
with self.assertRaises(component.NotRegistered):

View file

@ -29,7 +29,7 @@ class IffedComponent(SimpleComponent):
class ComponentTemplateTagTest(SimpleTestCase):
def setUp(self):
# NOTE: component.registry is global, so need to clear before each test
component.registry._registry = {}
component.registry.clear()
def test_single_component_dependencies(self):
component.registry.register(name="test", component=SimpleComponent)