Add implementation + tests

This commit is contained in:
Roman Mogylatov 2021-02-05 16:53:59 -05:00
parent 2fadbf0f81
commit ef0f5f5ebe
4 changed files with 986 additions and 723 deletions

File diff suppressed because it is too large Load Diff

View File

@ -43,6 +43,8 @@ class Container:
def unwire(self) -> None: ...
def init_resources(self) -> Optional[Awaitable]: ...
def shutdown_resources(self) -> Optional[Awaitable]: ...
def apply_container_providers_overridings(self) -> None: ...
def reset_singletons(self) -> None: ...
@overload
def traverse(self, types: Optional[Sequence[Type]] = None) -> Iterator[Provider]: ...
@classmethod

View File

@ -271,6 +271,11 @@ class DynamicContainer(Container):
for provider in self.traverse(types=[providers.Container]):
provider.apply_overridings()
def reset_singletons(self):
"""Reset all container singletons."""
for provider in self.traverse(types=[providers.Singleton]):
provider.reset()
class DeclarativeContainerMetaClass(type):
"""Declarative inversion of control container meta class."""

View File

@ -287,3 +287,51 @@ class DeclarativeContainerInstanceTests(unittest.TestCase):
self.assertEqual(_init1.shutdown_counter, 2)
self.assertEqual(_init2.init_counter, 2)
self.assertEqual(_init2.shutdown_counter, 2)
def reset_singletons(self):
class SubSubContainer(containers.DeclarativeContainer):
singleton = providers.Singleton(object)
class SubContainer(containers.DeclarativeContainer):
singleton = providers.Singleton(object)
sub_sub_container = providers.Container(SubSubContainer)
class Container(containers.DeclarativeContainer):
singleton = providers.Singleton(object)
sub_container = providers.Container(SubContainer)
container = Container()
obj11 = container.singleton()
obj12 = container.sub_container().singleton()
obj13 = container.sub_container().sub_sub_container().singleton()
obj21 = container.singleton()
obj22 = container.sub_container().singleton()
obj23 = container.sub_container().sub_sub_container().singleton()
self.assertIs(obj11, obj21)
self.assertIs(obj12, obj22)
self.assertIs(obj13, obj23)
container.reset_singletons()
obj31 = container.singleton()
obj32 = container.sub_container().singleton()
obj33 = container.sub_container().sub_sub_container().singleton()
obj41 = container.singleton()
obj42 = container.sub_container().singleton()
obj43 = container.sub_container().sub_sub_container().singleton()
self.assertIsNot(obj11, obj31)
self.assertIsNot(obj12, obj32)
self.assertIsNot(obj13, obj33)
self.assertIsNot(obj21, obj31)
self.assertIsNot(obj22, obj32)
self.assertIsNot(obj23, obj33)
self.assertIs(obj31, obj41)
self.assertIs(obj32, obj42)
self.assertIs(obj33, obj43)