Skip to content

Commit 588b2f2

Browse files
committed
Add simple_service to examples/
1 parent 91f0958 commit 588b2f2

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,10 @@ if __name__ == "__main__":
118118
assert "hello world" == my_function()
119119
```
120120

121+
## Examples
122+
123+
If you would like to see more examples, feel free to check out [examples/](examples).
124+
121125
## Authors
122126

123127
| [![Zac Scott](https://avatars.githubusercontent.com/u/38968222?s=128&v=4)](https://github.com/scottzach1) |

examples/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Examples
2+
3+
This directory shows various examples of how to use the Python Injector Framework in your application.
4+
5+
| Name | Description |
6+
|:----------------------------------|:-------------------------------------------------------------------------------------|
7+
| [simple_service/](simple_service) | A bare bones application showcasing injecting an API service and mocking for pytest. |

examples/simple_service/main.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from pif import providers, wiring
2+
3+
4+
class ApiClient:
5+
"""
6+
An API client that takes a domain and token.
7+
"""
8+
9+
def __init__(self, domain: str, token: str):
10+
assert domain and token
11+
12+
def do_stuff(self): ...
13+
14+
15+
# Define some providers to use for injection.
16+
ApiDomainProvider = providers.BlankProvider()
17+
ApiTokenProvider = providers.BlankProvider()
18+
ApiClientProvider = providers.Singleton[ApiClient](ApiClient, domain=ApiDomainProvider, token=ApiTokenProvider)
19+
20+
21+
@wiring.injected
22+
def main(client: ApiClient = ApiClientProvider):
23+
"""
24+
Your application logic.
25+
"""
26+
client.do_stuff()
27+
28+
29+
if __name__ == "__main__":
30+
ApiDomainProvider.override_existing("example.domain.com")
31+
ApiTokenProvider.override_existing("*****")
32+
33+
main()

examples/simple_service/test.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from unittest.mock import MagicMock
2+
3+
import main
4+
5+
6+
def test_main():
7+
"""
8+
Showcase how we can patch our main method for testing.
9+
"""
10+
mock = MagicMock()
11+
12+
with main.ApiClientProvider.override_existing(mock):
13+
main.main()
14+
15+
assert mock.do_stuff.call_count == 1

0 commit comments

Comments
 (0)