Skip to content

Commit 4f111aa

Browse files
committed
Update provider overriding example to use container and fix bug
1 parent d61281a commit 4f111aa

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

examples/providers/overriding.py

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
"""Simple providers overriding example."""
22

3+
import dataclasses
34
import unittest.mock
45

5-
from dependency_injector import providers
6+
from dependency_injector import containers, providers
67

78

89
class ApiClient:
@@ -13,30 +14,35 @@ class ApiClientStub(ApiClient):
1314
...
1415

1516

17+
@dataclasses.dataclass
1618
class Service:
17-
def __init__(self, api_client: ApiClient):
18-
self._api_client = api_client
19+
api_client: ApiClient
1920

2021

21-
api_client_factory = providers.Factory(ApiClient)
22-
service_factory = providers.Factory(
23-
Service,
24-
api_client=api_client_factory,
25-
)
22+
class Container(containers.DeclarativeContainer):
23+
24+
api_client_factory = providers.Factory(ApiClient)
25+
26+
service_factory = providers.Factory(
27+
Service,
28+
api_client=api_client_factory,
29+
)
2630

2731

2832
if __name__ == '__main__':
33+
container = Container()
34+
2935
# 1. Use .override() to replace the API client with stub
30-
api_client_factory.override(providers.Factory(ApiClientStub))
31-
service1 = service_factory()
36+
container.api_client_factory.override(providers.Factory(ApiClientStub))
37+
service1 = container.service_factory()
3238
assert isinstance(service1.api_client, ApiClientStub)
3339

3440
# 2. Use .override() as a context manager to mock the API client in testing
35-
with api_client_factory.override(unittest.mock.Mock(ApiClient)):
36-
service3 = service_factory()
37-
assert isinstance(service3.api_client, unittest.mock.Mock)
41+
with container.api_client_factory.override(unittest.mock.Mock(ApiClient)):
42+
service2 = container.service_factory()
43+
assert isinstance(service2.api_client, unittest.mock.Mock)
3844

3945
# 3. Use .reset_override() to get back to normal
40-
api_client_factory.reset_override()
41-
service3 = service_factory()
46+
container.api_client_factory.reset_override()
47+
service3 = container.service_factory()
4248
assert isinstance(service3.api_client, ApiClient)

0 commit comments

Comments
 (0)