Implement container.check_dependencies() (#396)

* Add implementation, typing stubs, and tests

* Add docs and example

* Update changelog
This commit is contained in:
Roman Mogylatov 2021-02-14 18:47:15 -05:00 committed by GitHub
parent 2c5bb45bf1
commit 8eea9c4e45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 7453 additions and 6715 deletions

View File

@ -0,0 +1,18 @@
.. _check-container-dependencies:
Check container dependencies
----------------------------
To check container dependencies use method ``.check_dependencies()``.
.. literalinclude:: ../../examples/containers/check_dependencies.py
:language: python
:lines: 3-
:emphasize-lines: 12
Method ``.check_dependencies()`` raises an error if container has any undefined dependencies.
If all dependencies are provided or have defaults, no error is raised.
See also: :ref:`dependency-provider`.
.. disqus::

View File

@ -24,4 +24,5 @@ Containers module API docs - :py:mod:`dependency_injector.containers`.
specialization
overriding
reset_singletons
check_dependencies
traversal

View File

@ -7,6 +7,13 @@ that were made in every particular version.
From version 0.7.6 *Dependency Injector* framework strictly
follows `Semantic versioning`_
Development version
-------------------
- Add method ``container.check_dependencies()`` to check if all container dependencies
are defined.
See issue: `#383 <https://github.com/ets-labs/python-dependency-injector/issues/383>`_.
Thanks to `@shaunc <https://github.com/shaunc>`_ for suggesting the feature.
4.21.0
------
- Improve ``Dependency`` provider error message: when dependency is undefined,

View File

@ -1,3 +1,5 @@
.. _dependency-provider:
Dependency provider
===================
@ -31,4 +33,6 @@ dependency provider will wrap it into the ``Object`` provider.
:lines: 16-23
:emphasize-lines: 3
See also: :ref:`check-container-dependencies`.
.. disqus::

View File

@ -0,0 +1,15 @@
"""Container dependencies check example."""
from dependency_injector import containers, providers
class Container(containers.DeclarativeContainer):
service1 = providers.Dependency()
service2 = providers.Dependency()
if __name__ == '__main__':
container = Container()
container.check_dependencies() # <-- raises error:
# Container has undefined dependencies: "Container.service1", "Container.service2"

File diff suppressed because it is too large Load Diff

View File

@ -45,6 +45,7 @@ class Container:
def shutdown_resources(self) -> Optional[Awaitable]: ...
def apply_container_providers_overridings(self) -> None: ...
def reset_singletons(self) -> None: ...
def check_dependencies(self) -> None: ...
@overload
def resolve_provider_name(self, provider: Provider) -> str: ...
@classmethod

View File

@ -305,6 +305,30 @@ class DynamicContainer(Container):
for provider in self.traverse(types=[providers.BaseSingleton]):
provider.reset()
def check_dependencies(self):
"""Check if container dependencies are defined.
If any dependency is undefined, raises an error.
"""
undefined = [
dependency
for dependency in self.traverse(types=[providers.Dependency])
if not dependency.is_defined
]
if not undefined:
return
container_name = self.parent_name if self.parent_name else self.__class__.__name__
undefined_names = [
f'"{dependency.parent_name if dependency.parent_name else dependency}"'
for dependency in undefined
]
raise errors.Error(
f'Container "{container_name}" has undefined dependencies: '
f'{", ".join(undefined_names)}',
)
def resolve_provider_name(self, provider):
"""Try to resolve provider name."""
for provider_name, container_provider in self.providers.items():

File diff suppressed because it is too large Load Diff

View File

@ -106,6 +106,8 @@ class Dependency(Provider[T]):
def instance_of(self) -> Type[T]: ...
@property
def default(self) -> Provider[T]: ...
@property
def is_defined(self) -> bool: ...
def provided_by(self, provider: Provider) -> OverridingContext: ...
@property
def parent(self) -> Optional[ProviderParent]: ...

View File

@ -708,6 +708,11 @@ cdef class Dependency(Provider):
"""Return default provider."""
return self.__default
@property
def is_defined(self):
"""Return True if dependency is defined."""
return self.__last_overriding or self.__default is not UNDEFINED
def provided_by(self, provider):
"""Set external dependency provider.

View File

@ -336,6 +336,35 @@ class DeclarativeContainerInstanceTests(unittest.TestCase):
self.assertIs(obj32, obj42)
self.assertIs(obj33, obj43)
def test_check_dependencies(self):
class SubContainer(containers.DeclarativeContainer):
dependency = providers.Dependency()
class Container(containers.DeclarativeContainer):
dependency = providers.Dependency()
dependencies_container = providers.DependenciesContainer()
provider = providers.List(dependencies_container.dependency)
sub_container = providers.Container(SubContainer)
container = Container()
with self.assertRaises(errors.Error) as context:
container.check_dependencies()
self.assertIn('Container "Container" has undefined dependencies:', str(context.exception))
self.assertIn('"Container.dependency"', str(context.exception))
self.assertIn('"Container.dependencies_container.dependency"', str(context.exception))
self.assertIn('"Container.sub_container.dependency"', str(context.exception))
def test_check_dependencies_all_defined(self):
class Container(containers.DeclarativeContainer):
dependency = providers.Dependency()
container = Container(dependency='provided')
result = container.check_dependencies()
self.assertIsNone(result)
def test_assign_parent(self):
parent = providers.DependenciesContainer()
container = ContainerA()

View File

@ -352,6 +352,19 @@ class DependencyTests(unittest.TestCase):
self.assertEqual(provider.default(), {'foo': 'bar'})
self.assertIs(provider.default, default)
def test_is_defined(self):
provider = providers.Dependency()
self.assertFalse(provider.is_defined)
def test_is_defined_when_overridden(self):
provider = providers.Dependency()
provider.override('value')
self.assertTrue(provider.is_defined)
def test_is_defined_with_default(self):
provider = providers.Dependency(default='value')
self.assertTrue(provider.is_defined)
def test_call_overridden(self):
self.provider.provided_by(providers.Factory(list))
self.assertIsInstance(self.provider(), list)