Improve @containers.copy to replace subcontainer providers

This commit is contained in:
Roman Mogylatov 2021-01-27 09:15:06 -05:00
parent 78479c65e6
commit 31042cd99b
3 changed files with 1000 additions and 496 deletions

File diff suppressed because it is too large Load Diff

View File

@ -541,16 +541,25 @@ def copy(object container):
:return: Declarative container's copying decorator.
:rtype: callable(:py:class:`DeclarativeContainer`)
"""
def _decorator(copied_container):
cdef dict memo = dict()
for name, provider in six.iteritems(copied_container.cls_providers):
def _get_providers_memo(from_providers, source_providers):
memo = dict()
for name, provider in from_providers.items():
try:
source_provider = getattr(container, name)
except AttributeError:
pass
source_provider = source_providers[name]
except KeyError:
...
else:
memo[id(source_provider)] = provider
if hasattr(provider, 'providers') and hasattr(source_provider, 'providers'):
sub_memo = _get_providers_memo(provider.providers, source_provider.providers)
memo.update(sub_memo)
return memo
def _decorator(copied_container):
memo = _get_providers_memo(copied_container.cls_providers, container.providers)
providers_copy = deepcopy(container.providers, memo)
for name, provider in six.iteritems(providers_copy):
setattr(copied_container, name, provider)

View File

@ -296,6 +296,26 @@ class DeclarativeContainerTests(unittest.TestCase):
self.assertEqual(_Container1.p13(), 11)
self.assertEqual(_Container2.p13(), 22)
def test_copy_with_replacing_subcontainer_providers(self):
# See: https://github.com/ets-labs/python-dependency-injector/issues/374
class X(containers.DeclarativeContainer):
foo = providers.Dependency(instance_of=str)
def build_x():
return X(foo='1')
class A(containers.DeclarativeContainer):
x = providers.DependenciesContainer(**X.providers)
y = x.foo
@containers.copy(A)
class B1(A):
x = providers.Container(build_x)
b1 = B1()
self.assertEqual(b1.y(), '1')
def test_containers_attribute(self):
class Container(containers.DeclarativeContainer):
class Container1(containers.DeclarativeContainer):