mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2024-11-25 11:04:01 +03:00
Update provider overriding example to use container and fix bug
This commit is contained in:
parent
d61281a0b9
commit
4f111aae9b
|
@ -1,8 +1,9 @@
|
||||||
"""Simple providers overriding example."""
|
"""Simple providers overriding example."""
|
||||||
|
|
||||||
|
import dataclasses
|
||||||
import unittest.mock
|
import unittest.mock
|
||||||
|
|
||||||
from dependency_injector import providers
|
from dependency_injector import containers, providers
|
||||||
|
|
||||||
|
|
||||||
class ApiClient:
|
class ApiClient:
|
||||||
|
@ -13,30 +14,35 @@ class ApiClientStub(ApiClient):
|
||||||
...
|
...
|
||||||
|
|
||||||
|
|
||||||
|
@dataclasses.dataclass
|
||||||
class Service:
|
class Service:
|
||||||
def __init__(self, api_client: ApiClient):
|
api_client: ApiClient
|
||||||
self._api_client = api_client
|
|
||||||
|
|
||||||
|
|
||||||
api_client_factory = providers.Factory(ApiClient)
|
class Container(containers.DeclarativeContainer):
|
||||||
service_factory = providers.Factory(
|
|
||||||
Service,
|
api_client_factory = providers.Factory(ApiClient)
|
||||||
api_client=api_client_factory,
|
|
||||||
)
|
service_factory = providers.Factory(
|
||||||
|
Service,
|
||||||
|
api_client=api_client_factory,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
container = Container()
|
||||||
|
|
||||||
# 1. Use .override() to replace the API client with stub
|
# 1. Use .override() to replace the API client with stub
|
||||||
api_client_factory.override(providers.Factory(ApiClientStub))
|
container.api_client_factory.override(providers.Factory(ApiClientStub))
|
||||||
service1 = service_factory()
|
service1 = container.service_factory()
|
||||||
assert isinstance(service1.api_client, ApiClientStub)
|
assert isinstance(service1.api_client, ApiClientStub)
|
||||||
|
|
||||||
# 2. Use .override() as a context manager to mock the API client in testing
|
# 2. Use .override() as a context manager to mock the API client in testing
|
||||||
with api_client_factory.override(unittest.mock.Mock(ApiClient)):
|
with container.api_client_factory.override(unittest.mock.Mock(ApiClient)):
|
||||||
service3 = service_factory()
|
service2 = container.service_factory()
|
||||||
assert isinstance(service3.api_client, unittest.mock.Mock)
|
assert isinstance(service2.api_client, unittest.mock.Mock)
|
||||||
|
|
||||||
# 3. Use .reset_override() to get back to normal
|
# 3. Use .reset_override() to get back to normal
|
||||||
api_client_factory.reset_override()
|
container.api_client_factory.reset_override()
|
||||||
service3 = service_factory()
|
service3 = container.service_factory()
|
||||||
assert isinstance(service3.api_client, ApiClient)
|
assert isinstance(service3.api_client, ApiClient)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user