|
1
|
|
|
from typing import NewType, List |
|
2
|
|
|
|
|
3
|
|
|
try: |
|
4
|
|
|
from typing import Protocol |
|
5
|
|
|
except ImportError: |
|
6
|
|
|
from typing_extensions import Protocol # type: ignore |
|
7
|
|
|
|
|
8
|
|
|
from lagom import Container |
|
9
|
|
|
|
|
10
|
|
|
MyServiceUrl = NewType("MyServiceUrl", str) |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
class ApiClientOfSomeKind: |
|
14
|
|
|
def __init__(self, url: MyServiceUrl): |
|
15
|
|
|
pass |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
class LoadBalancePerhaps: |
|
19
|
|
|
def __init__(self, urls: List[MyServiceUrl]): |
|
20
|
|
|
pass |
|
21
|
|
|
|
|
22
|
|
|
|
|
23
|
|
|
class BakerProtocol(Protocol): |
|
24
|
|
|
def bake(self) -> str: |
|
25
|
|
|
pass |
|
26
|
|
|
|
|
27
|
|
|
|
|
28
|
|
|
class Bakery: |
|
29
|
|
|
def __init__(self, baker: BakerProtocol): |
|
30
|
|
|
pass |
|
31
|
|
|
|
|
32
|
|
|
|
|
33
|
|
|
class CrumpetBaker: |
|
34
|
|
|
def bake(self) -> str: |
|
35
|
|
|
return "crumpets" |
|
36
|
|
|
|
|
37
|
|
|
|
|
38
|
|
|
def test_newtype_works_well_with_the_container(container: Container): |
|
39
|
|
|
container[MyServiceUrl] = MyServiceUrl("https://roll.diceapi.com") |
|
|
|
|
|
|
40
|
|
|
api_client = container[ApiClientOfSomeKind] |
|
41
|
|
|
assert isinstance(api_client, ApiClientOfSomeKind) |
|
42
|
|
|
|
|
43
|
|
|
|
|
44
|
|
|
def test_lists_of_newtype_work_well_with_the_container(container: Container): |
|
45
|
|
|
container[List[MyServiceUrl]] = [ |
|
46
|
|
|
MyServiceUrl("https://roll.diceapi.com"), |
|
|
|
|
|
|
47
|
|
|
MyServiceUrl("https://lol.diceapi.com"), |
|
48
|
|
|
] |
|
49
|
|
|
load_balancer = container[LoadBalancePerhaps] |
|
50
|
|
|
assert isinstance(load_balancer, LoadBalancePerhaps) |
|
51
|
|
|
|
|
52
|
|
|
|
|
53
|
|
|
def test_protocols_work_well_with_the_container(container: Container): |
|
54
|
|
|
# TODO: update contracts so this type ignore can be removed |
|
55
|
|
|
container[BakerProtocol] = CrumpetBaker # type: ignore |
|
56
|
|
|
bakery = container[Bakery] |
|
57
|
|
|
assert isinstance(bakery, Bakery) |
|
58
|
|
|
|