Add implementation, tests, and typing stubs

This commit is contained in:
Roman Mogylatov 2021-02-05 17:59:31 -05:00
parent 4013225132
commit d48e2ea972
4 changed files with 2883 additions and 2651 deletions

File diff suppressed because it is too large Load Diff

View File

@ -267,6 +267,7 @@ class BaseSingleton(Provider[T]):
def set_attributes(self, **kwargs: Injection) -> BaseSingleton[T]: ...
def clear_attributes(self) -> BaseSingleton[T]: ...
def reset(self) -> None: ...
def full_reset(self) -> None: ...
class Singleton(BaseSingleton[T]): ...

View File

@ -2468,6 +2468,15 @@ cdef class BaseSingleton(Provider):
"""
raise NotImplementedError()
def full_reset(self):
"""Reset cached instance in current and all underlying singletons, if any.
:rtype: None
"""
self.reset()
for provider in self.traverse(types=[BaseSingleton]):
provider.reset()
@property
def related(self):
"""Return related providers generator."""

View File

@ -355,6 +355,37 @@ class _BaseSingletonTestCase(object):
self.assertIsNot(instance1, instance2)
def test_reset_with_singleton(self):
dependent_singleton = providers.Singleton(object)
provider = self.singleton_cls(dict, dependency=dependent_singleton)
dependent_instance = dependent_singleton()
instance1 = provider()
self.assertIs(instance1['dependency'], dependent_instance)
provider.reset()
instance2 = provider()
self.assertIs(instance1['dependency'], dependent_instance)
self.assertIsNot(instance1, instance2)
def test_full_reset(self):
dependent_singleton = providers.Singleton(object)
provider = self.singleton_cls(dict, dependency=dependent_singleton)
dependent_instance1 = dependent_singleton()
instance1 = provider()
self.assertIs(instance1['dependency'], dependent_instance1)
provider.full_reset()
dependent_instance2 = dependent_singleton()
instance2 = provider()
self.assertIsNot(instance2['dependency'], dependent_instance1)
self.assertIsNot(dependent_instance1, dependent_instance2)
self.assertIsNot(instance1, instance2)
class SingletonTests(_BaseSingletonTestCase, unittest.TestCase):