Add overriding demo to the README

This commit is contained in:
Roman Mogylatov 2020-08-14 15:45:30 -04:00
parent 684745a6b4
commit 925801c73f
4 changed files with 34 additions and 26 deletions

View File

@ -109,19 +109,9 @@ your application objects when you apply dependency injection principle:
.. code-block:: python
from dependency_injector import containers, providers
from unittest import mock
class ApiClient:
def __init__(self, api_key: str, timeout: int):
self.api_key = api_key
self.timeout = timeout
class Service:
def __init__(self, api_client: ApiClient):
self.api_client = api_client
from .example_di import ApiClient, Service
class Container(containers.DeclarativeContainer):
@ -145,9 +135,12 @@ your application objects when you apply dependency injection principle:
container.config.from_yaml('config.yml')
service = container.service()
assert isinstance(service.api_client, ApiClient)
with container.api_client.override(mock.Mock()):
service = container.service()
assert isinstance(service.api_client, mock.Mock)
`More examples <https://github.com/ets-labs/python-dependency-injector/tree/master/examples>`_
Installation

View File

@ -1,18 +1,7 @@
from dependency_injector import containers, providers
from unittest import mock
class ApiClient:
def __init__(self, api_key: str, timeout: int):
self.api_key = api_key
self.timeout = timeout
class Service:
def __init__(self, api_client: ApiClient):
self.api_client = api_client
from .example_di import ApiClient, Service
class Container(containers.DeclarativeContainer):
@ -41,4 +30,3 @@ if __name__ == '__main__':
with container.api_client.override(mock.Mock()):
service = container.service()
assert isinstance(service.api_client, mock.Mock)

View File

@ -0,0 +1,13 @@
class ApiClient:
def __init__(self, api_key: str, timeout: int):
self.api_key = api_key
self.timeout = timeout
class Service:
def __init__(self, api_client: ApiClient):
self.api_client = api_client

View File

@ -0,0 +1,14 @@
import os
class ApiClient:
def __init__(self):
self.api_key = os.getenv('API_KEY')
self.timeout = os.getenv('TIMEOUT')
class Service:
def __init__(self):
self.api_client = ApiClient()