-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_context_provider.py
More file actions
57 lines (39 loc) · 2.15 KB
/
test_context_provider.py
File metadata and controls
57 lines (39 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
import dataclasses
import datetime
import pytest
from modern_di import Container, Group, Scope, providers
request_context_provider = providers.ContextProvider(scope=Scope.REQUEST, context_type=datetime.datetime)
@dataclasses.dataclass(kw_only=True, slots=True, frozen=True)
class SomeFactory:
arg1: datetime.datetime
class MyGroup(Group):
context_provider = providers.ContextProvider(scope=Scope.APP, context_type=datetime.datetime)
some_factory = providers.Factory(creator=SomeFactory)
def test_context_provider() -> None:
now = datetime.datetime.now(tz=datetime.timezone.utc)
app_container = Container(context={datetime.datetime: now})
app_container.validate_provider(MyGroup.context_provider)
instance1 = app_container.resolve_provider(MyGroup.context_provider)
instance2 = app_container.resolve_provider(MyGroup.context_provider)
assert instance1 is instance2 is now
def test_context_provider_set_context_after_creation() -> None:
now = datetime.datetime.now(tz=datetime.timezone.utc)
app_container = Container()
app_container.set_context(datetime.datetime, now)
instance1 = app_container.resolve_provider(MyGroup.context_provider)
instance2 = app_container.resolve_provider(MyGroup.context_provider)
assert instance1 is instance2 is now
def test_context_provider_not_found() -> None:
app_container = Container()
assert app_container.resolve_provider(MyGroup.context_provider) is None
def test_context_provider_not_found_but_required() -> None:
app_container = Container(groups=[MyGroup])
with pytest.raises(RuntimeError, match=r"Argument arg1 of type <class 'datetime.datetime'> cannot be resolved"):
app_container.resolve(SomeFactory)
def test_context_provider_in_request_scope() -> None:
now = datetime.datetime.now(tz=datetime.timezone.utc)
app_container = Container()
request_container = app_container.build_child_container(context={datetime.datetime: now}, scope=Scope.REQUEST)
instance1 = request_container.resolve_provider(request_context_provider)
instance2 = request_container.resolve_provider(request_context_provider)
assert instance1 is instance2 is now