Add support of overriding for container provider

This commit is contained in:
Roman Mogylatov 2021-01-12 08:41:59 -05:00
parent cebeb79b93
commit cd4807b2f9
3 changed files with 1293 additions and 1117 deletions

File diff suppressed because it is too large Load Diff

View File

@ -3069,13 +3069,21 @@ cdef class Container(Provider):
attribute_name=name))
return getattr(self.__container, name)
@property
def providers(self):
return self.__container.providers
@property
def container(self):
return self.__container
def override(self, provider):
"""Override provider with another provider."""
raise Error('Provider {0} can not be overridden'.format(self))
if not hasattr(provider, 'providers'):
raise Error('Container provider {0} can be overridden only by providers container'.format(self))
self.__container.override_providers = provider.providers
super().override(provider)
cpdef object _provide(self, tuple args, dict kwargs):
"""Return single instance."""

View File

@ -4,7 +4,7 @@ import copy
import unittest2 as unittest
from dependency_injector import containers, providers
from dependency_injector import containers, providers, errors
TEST_VALUE_1 = 'core_section_value1'
@ -52,3 +52,27 @@ class ContainerTests(unittest.TestCase):
application.config.override(_copied(TEST_CONFIG_1))
application.config.override(_copied(TEST_CONFIG_2))
self.assertEqual(application.dict_factory(), {'value': TEST_VALUE_2})
def test_override(self):
class D(containers.DeclarativeContainer):
foo = providers.Object('foo')
class A(containers.DeclarativeContainer):
d = providers.DependenciesContainer()
bar = providers.Callable(lambda f: f + '++', d.foo.provided)
class B(containers.DeclarativeContainer):
d = providers.Container(D)
a = providers.Container(A, d=d)
b = B(d=D())
result = b.a().bar()
self.assertEqual(result, 'foo++')
# See: https://github.com/ets-labs/python-dependency-injector/issues/354
def test_override_by_not_a_container(self):
provider = providers.Container(TestCore)
with self.assertRaises(errors.Error):
provider.override(providers.Object('foo'))