python-dependency-injector/examples/di_demo2/demo.py

33 lines
771 B
Python
Raw Normal View History

2020-08-14 04:53:13 +03:00
from dependency_injector import containers, providers
2020-08-14 22:31:33 +03:00
from unittest import mock
2020-08-14 04:53:13 +03:00
2020-08-14 22:45:30 +03:00
from .example_di import ApiClient, Service
2020-08-14 04:53:13 +03:00
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
api_client = providers.Singleton(
ApiClient,
api_key=config.api_key,
timeout=config.timeout,
)
service = providers.Factory(
Service,
api_client=api_client,
)
if __name__ == '__main__':
container = Container()
container.config.from_yaml('config.yml')
service = container.service()
assert isinstance(service.api_client, ApiClient)
2020-08-14 22:31:33 +03:00
with container.api_client.override(mock.Mock()):
service = container.service()
assert isinstance(service.api_client, mock.Mock)