1
|
|
|
from abc import ABC, abstractmethod |
2
|
|
|
|
3
|
|
|
import pytest |
4
|
|
|
|
5
|
|
|
from lagom import Container, Alias |
6
|
|
|
from lagom.exceptions import UnresolvableType |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
class MySimpleAbc(ABC): |
10
|
|
|
stuff: str = "empty" |
11
|
|
|
|
12
|
|
|
@abstractmethod |
13
|
|
|
def bloop(self): |
14
|
|
|
pass |
15
|
|
|
|
16
|
|
|
|
17
|
|
|
class MySimpleDep(MySimpleAbc): |
18
|
|
|
stuff: str |
19
|
|
|
|
20
|
|
|
def __init__(self, stuff): |
21
|
|
|
self.stuff = stuff |
22
|
|
|
|
23
|
|
|
def bloop(self): |
24
|
|
|
return "beep" |
25
|
|
|
|
26
|
|
|
|
27
|
|
|
class MyMoreComplicatedDep: |
28
|
|
|
complicated_stuff: str |
29
|
|
|
|
30
|
|
|
def __init__(self, dep: MySimpleAbc): |
31
|
|
|
self.stuff = dep.stuff |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
class AnotherAbc(ABC): |
35
|
|
|
stuff: str = "empty" |
36
|
|
|
|
37
|
|
|
|
38
|
|
|
class AnotherConcrete(AnotherAbc): |
39
|
|
|
stuff = "full" |
40
|
|
|
|
41
|
|
|
|
42
|
|
|
@pytest.fixture |
43
|
|
|
def container_with_abc(container: Container): |
44
|
|
|
container.define(MySimpleAbc, lambda: MySimpleDep("hooray")) # type: ignore |
45
|
|
|
return container |
46
|
|
|
|
47
|
|
|
|
48
|
|
|
def test_registered_concrete_class_is_loaded(container_with_abc: Container): |
49
|
|
|
resolved = container_with_abc.resolve(MySimpleAbc) # type: ignore |
50
|
|
|
assert resolved.stuff == "hooray" |
51
|
|
|
|
52
|
|
|
|
53
|
|
|
def test_registered_concrete_class_is_used_for_other_objects( |
54
|
|
|
container_with_abc: Container, |
55
|
|
|
): |
56
|
|
|
resolved = container_with_abc.resolve(MyMoreComplicatedDep) |
57
|
|
|
assert resolved.stuff == "hooray" |
58
|
|
|
|
59
|
|
|
|
60
|
|
|
def test_alias_can_be_defined(container_with_abc: Container): |
61
|
|
|
container_with_abc.define(AnotherAbc, Alias(AnotherConcrete)) |
62
|
|
|
resolved = container_with_abc.resolve(AnotherAbc) |
63
|
|
|
assert resolved.stuff == "full" |
64
|
|
|
|
65
|
|
|
|
66
|
|
|
def test_trying_to_build_an_abc_raises_an_error(container: Container): |
67
|
|
|
with pytest.raises(UnresolvableType) as e_info: |
68
|
|
|
container.resolve(MySimpleAbc) # type: ignore |
69
|
|
|
assert "Unable to construct Abstract type MySimpleAbc" in str(e_info.value) |
70
|
|
|
assert "Try defining an alias or a concrete class to construct" in str(e_info.value) |
71
|
|
|
|