-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_4_bind.py
More file actions
121 lines (79 loc) · 2.15 KB
/
test_4_bind.py
File metadata and controls
121 lines (79 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import pytest
from ghoshell_container import Container
container = Container()
class _Foo:
pass
class _Bar:
def __init__(self, foo: _Foo):
self.foo = foo
class _Baz(_Foo):
pass
class _Cat:
def __init__(self, bar: _Bar, a: int):
self.bar = bar
self.a = a
@container.factory(_Foo)
def make_foo() -> _Foo:
return _Foo()
def make_foo2() -> _Foo:
return _Foo()
def test_bind_decorator():
assert isinstance(container.force_fetch(_Foo), _Foo)
def test_bind_with_singleton():
c = Container()
c.bind(_Foo, _Foo())
assert c.bound(_Foo)
assert isinstance(container.force_fetch(_Foo), _Foo)
def test_bind_with_singleton_factory():
c = Container()
# bind with factory
c.bind(_Foo, make_foo2)
foo = c.get(_Foo)
foo2 = c.get(_Foo)
assert isinstance(foo, _Foo)
assert foo is foo2
def test_bind_with_injection():
c = Container()
c.set(_Foo, _Foo())
c.bind(_Bar)
assert isinstance(c.get(_Bar), _Bar)
assert isinstance(c.get(_Bar).foo, _Foo)
def test_bind_but_not_singleton():
c = Container()
c.bind(_Foo, make_foo2, singleton=False)
foo = c.get(_Foo)
foo2 = c.get(_Foo)
# make twice
assert foo is not foo2
def test_bind_with_subclass():
c = Container()
# bind with subclass
c.bind(_Foo, _Baz)
assert isinstance(c.get(_Foo), _Baz)
assert isinstance(c.force_fetch(_Foo), _Foo)
def test_bind_none():
c = Container()
# bind itself
c.bind(_Foo)
assert isinstance(container.force_fetch(_Foo), _Foo)
def test_bind_with_invalid_subclass():
c = Container()
with pytest.raises(TypeError):
c.bind(_Foo, _Bar)
def test_not_allowed_to_bind_abstract():
from abc import ABC, abstractmethod
class Te(ABC):
@abstractmethod
def m(self):
pass
c = Container()
with pytest.raises(TypeError):
c.bind(Te)
with pytest.raises(RuntimeError):
c.make(Te)
def test_bind_with_kwargs():
c = Container()
c.bind(_Cat, kwargs=dict(a=1))
assert isinstance(c.get(_Cat), _Cat)
assert c.get(_Cat).a is 1
assert len(list(c.contracts())) == 1