-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_7_providers.py
More file actions
89 lines (59 loc) · 1.77 KB
/
test_7_providers.py
File metadata and controls
89 lines (59 loc) · 1.77 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
from typing import Type
from ghoshell_container import Provider, Container, IoCContainer, INSTANCE, BootstrapProvider
class _Foo:
def __init__(self):
self.foo = 1
class _FooProvider(Provider[_Foo]):
def __init__(self, val: int = 2):
self.val = val
def singleton(self) -> bool:
return True
def factory(self, con: IoCContainer) -> INSTANCE:
foo = _Foo()
foo.foo = self.val
return foo
def test_register():
c = Container()
p = _FooProvider(2)
c.register(p)
foo = c.force_fetch(_Foo)
# generic check
assert p.contract() is _Foo
assert foo.foo is 2
# singleton bound
assert c.force_fetch(_Foo) is foo
class _FooBootstrapProvider(BootstrapProvider[_FooProvider]):
def singleton(self) -> bool:
return True
def factory(self, con: IoCContainer) -> INSTANCE:
return _Foo()
def contract(self) -> Type[INSTANCE]:
return _Foo
def bootstrap(self, container: IoCContainer) -> None:
foo = container.fetch(_Foo)
foo.foo = 3
def shutdown(f: _Foo):
f.foo = 0
container.add_shutdown(shutdown)
def test_register_boostrap():
c = Container()
c.register(_FooBootstrapProvider())
c.bootstrap()
foo = c.force_fetch(_Foo)
# bootstrap
assert foo.foo is 3
c.shutdown()
# shutdown is called
assert foo.foo is 0
def test_register_rebind():
c = Container()
c.register(_FooBootstrapProvider())
with c:
foo = c.force_fetch(_Foo)
assert foo.foo is 3
# rebind provider
c.register(_FooProvider(1))
assert foo.foo is 3
# the binding has been changed
assert c.force_fetch(_Foo) is not foo
assert c.force_fetch(_Foo).foo is 1