modern-di 0.4.2__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of modern-di might be problematic. Click here for more details.

Files changed (59) hide show
  1. {modern_di-0.4.2 → modern_di-0.5.0}/.github/workflows/publish.yml +8 -4
  2. {modern_di-0.4.2 → modern_di-0.5.0}/PKG-INFO +1 -1
  3. modern_di-0.5.0/integrations/fastapi/Justfile +18 -0
  4. modern_di-0.5.0/integrations/fastapi/modern_di_fastapi/__init__.py +9 -0
  5. modern_di-0.5.0/integrations/fastapi/modern_di_fastapi/main.py +47 -0
  6. {modern_di-0.4.2 → modern_di-0.5.0}/integrations/fastapi/pyproject.toml +0 -3
  7. modern_di-0.5.0/integrations/fastapi/tests/conftest.py +28 -0
  8. modern_di-0.5.0/integrations/fastapi/tests/dependencies.py +17 -0
  9. modern_di-0.5.0/integrations/fastapi/tests/test_routes.py +57 -0
  10. modern_di-0.5.0/integrations/fastapi/tests/test_websockets.py +33 -0
  11. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/container.py +23 -11
  12. modern_di-0.5.0/modern_di/scope.py +9 -0
  13. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/test_context_adapter.py +1 -1
  14. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/test_factory.py +8 -2
  15. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/test_selector.py +1 -1
  16. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/test_singleton.py +2 -2
  17. modern_di-0.5.0/tests/test_container.py +46 -0
  18. modern_di-0.4.2/integrations/fastapi/modern_di_fastapi/__init__.py +0 -9
  19. modern_di-0.4.2/integrations/fastapi/modern_di_fastapi/depends.py +0 -24
  20. modern_di-0.4.2/integrations/fastapi/modern_di_fastapi/middleware.py +0 -27
  21. modern_di-0.4.2/integrations/fastapi/tests/test_fastapi_di.py +0 -69
  22. modern_di-0.4.2/modern_di/scope.py +0 -8
  23. modern_di-0.4.2/tests/test_container.py +0 -41
  24. {modern_di-0.4.2 → modern_di-0.5.0}/.github/workflows/core-ci.yml +0 -0
  25. {modern_di-0.4.2 → modern_di-0.5.0}/.github/workflows/fastapi-ci.yml +0 -0
  26. {modern_di-0.4.2 → modern_di-0.5.0}/.gitignore +0 -0
  27. {modern_di-0.4.2 → modern_di-0.5.0}/.readthedocs.yaml +0 -0
  28. {modern_di-0.4.2 → modern_di-0.5.0}/Justfile +0 -0
  29. {modern_di-0.4.2 → modern_di-0.5.0}/LICENSE +0 -0
  30. {modern_di-0.4.2 → modern_di-0.5.0}/README.md +0 -0
  31. {modern_di-0.4.2 → modern_di-0.5.0}/docs/conf.py +0 -0
  32. {modern_di-0.4.2 → modern_di-0.5.0}/docs/dev/contributing.md +0 -0
  33. {modern_di-0.4.2 → modern_di-0.5.0}/docs/dev/development-notes.md +0 -0
  34. {modern_di-0.4.2 → modern_di-0.5.0}/docs/index.md +0 -0
  35. {modern_di-0.4.2 → modern_di-0.5.0}/docs/requirements.txt +0 -0
  36. {modern_di-0.4.2 → modern_di-0.5.0}/integrations/fastapi/README.md +0 -0
  37. {modern_di-0.4.2 → modern_di-0.5.0}/integrations/fastapi/modern_di_fastapi/py.typed +0 -0
  38. {modern_di-0.4.2 → modern_di-0.5.0}/integrations/fastapi/tests/__init__.py +0 -0
  39. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/__init__.py +0 -0
  40. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/graph.py +0 -0
  41. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/provider_state.py +0 -0
  42. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/__init__.py +0 -0
  43. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/abstract.py +0 -0
  44. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/context_adapter.py +0 -0
  45. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/dict.py +0 -0
  46. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/factory.py +0 -0
  47. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/list.py +0 -0
  48. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/resource.py +0 -0
  49. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/selector.py +0 -0
  50. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/providers/singleton.py +0 -0
  51. {modern_di-0.4.2 → modern_di-0.5.0}/modern_di/py.typed +0 -0
  52. {modern_di-0.4.2 → modern_di-0.5.0}/pyproject.toml +0 -0
  53. {modern_di-0.4.2 → modern_di-0.5.0}/tests/__init__.py +0 -0
  54. {modern_di-0.4.2 → modern_di-0.5.0}/tests/creators.py +0 -0
  55. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/__init__.py +0 -0
  56. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/test_dict.py +0 -0
  57. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/test_list.py +0 -0
  58. {modern_di-0.4.2 → modern_di-0.5.0}/tests/providers/test_resource.py +0 -0
  59. {modern_di-0.4.2 → modern_di-0.5.0}/tests/test_graph.py +0 -0
@@ -15,12 +15,16 @@ jobs:
15
15
  with:
16
16
  enable-cache: true
17
17
  cache-dependency-glob: "pyproject.toml"
18
- - run: just publish modern-di
19
- if: startsWith(github.ref_name, 'core')
18
+
19
+ - if: startsWith(github.ref_name, 'core')
20
+ run: just publish modern-di
20
21
  env:
21
22
  PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
22
23
 
23
- - run: just publish modern-di-fastapi
24
- if: startsWith(github.ref_name, 'fastapi')
24
+ - if: startsWith(github.ref_name, 'fastapi')
25
+ run: |
26
+ export SETUPTOOLS_SCM_PRETEND_VERSION=$(echo "${{ github.ref_name }}" | sed 's/^fastapi-//; s/-.*$//')
27
+ echo "SETUPTOOLS_SCM_PRETEND_VERSION=$SETUPTOOLS_SCM_PRETEND_VERSION"
28
+ just publish modern-di-fastapi
25
29
  env:
26
30
  PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: modern-di
3
- Version: 0.4.2
3
+ Version: 0.5.0
4
4
  Summary: Dependency Injection framework with IOC-container and scopes
5
5
  Project-URL: repository, https://github.com/modern-python/modern-di
6
6
  Project-URL: docs, https://modern-di.readthedocs.io
@@ -0,0 +1,18 @@
1
+ default: install lint test
2
+
3
+ install:
4
+ uv lock --upgrade
5
+ uv sync --all-extras --frozen
6
+
7
+ lint:
8
+ uv run ruff format .
9
+ uv run ruff check . --fix
10
+ uv run mypy .
11
+
12
+ lint-ci:
13
+ uv run ruff format . --check
14
+ uv run ruff check . --no-fix
15
+ uv run mypy .
16
+
17
+ test *args:
18
+ uv run pytest {{ args }}
@@ -0,0 +1,9 @@
1
+ from modern_di_fastapi.main import Provide, build_request_container, fetch_di_container, setup_di
2
+
3
+
4
+ __all__ = [
5
+ "Provide",
6
+ "build_request_container",
7
+ "fetch_di_container",
8
+ "setup_di",
9
+ ]
@@ -0,0 +1,47 @@
1
+ import dataclasses
2
+ import enum
3
+ import typing
4
+
5
+ import fastapi
6
+ from modern_di import Container, Scope, providers
7
+ from starlette.requests import HTTPConnection
8
+
9
+
10
+ T_co = typing.TypeVar("T_co", covariant=True)
11
+
12
+
13
+ def setup_di(app: fastapi.FastAPI, scope: enum.IntEnum = Scope.APP) -> Container:
14
+ app.state.di_container = Container(scope=scope)
15
+ return app.state.di_container
16
+
17
+
18
+ def fetch_di_container(app: fastapi.FastAPI) -> Container:
19
+ return typing.cast(Container, app.state.di_container)
20
+
21
+
22
+ async def build_request_container(connection: HTTPConnection) -> typing.AsyncIterator[Container]:
23
+ context: dict[str, typing.Any] = {}
24
+ scope: Scope | None = None
25
+ if isinstance(connection, fastapi.Request):
26
+ scope = Scope.REQUEST
27
+ context["request"] = connection
28
+ elif isinstance(connection, fastapi.WebSocket):
29
+ context["websocket"] = connection
30
+ scope = Scope.SESSION
31
+ container: Container = fetch_di_container(connection.app)
32
+ async with container.build_child_container(context=context, scope=scope) as request_container:
33
+ yield request_container
34
+
35
+
36
+ @dataclasses.dataclass(slots=True, frozen=True)
37
+ class Dependency(typing.Generic[T_co]):
38
+ dependency: providers.AbstractProvider[T_co]
39
+
40
+ async def __call__(
41
+ self, request_container: typing.Annotated[Container, fastapi.Depends(build_request_container)]
42
+ ) -> T_co:
43
+ return await self.dependency.async_resolve(request_container)
44
+
45
+
46
+ def Provide(dependency: providers.AbstractProvider[T_co], *, use_cache: bool = True) -> T_co: # noqa: N802
47
+ return typing.cast(T_co, fastapi.Depends(dependency=Dependency(dependency), use_cache=use_cache))
@@ -49,9 +49,6 @@ build-backend = "hatchling.build"
49
49
  source = "vcs"
50
50
  fallback-version = "0"
51
51
 
52
- [tool.hatch.build.targets.wheel]
53
- packages = ["integrations/fastapi"]
54
-
55
52
  [tool.mypy]
56
53
  python_version = "3.10"
57
54
  strict = true
@@ -0,0 +1,28 @@
1
+ import contextlib
2
+ import typing
3
+
4
+ import fastapi
5
+ import pytest
6
+ from asgi_lifespan import LifespanManager
7
+ from starlette.testclient import TestClient
8
+
9
+ from modern_di_fastapi import setup_di
10
+
11
+
12
+ @contextlib.asynccontextmanager
13
+ async def lifespan(app_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
14
+ container = setup_di(app_)
15
+ async with container:
16
+ yield
17
+
18
+
19
+ @pytest.fixture
20
+ async def app() -> typing.AsyncIterator[fastapi.FastAPI]:
21
+ app_ = fastapi.FastAPI(lifespan=lifespan)
22
+ async with LifespanManager(app_):
23
+ yield app_
24
+
25
+
26
+ @pytest.fixture
27
+ def client(app: fastapi.FastAPI) -> TestClient:
28
+ return TestClient(app=app)
@@ -0,0 +1,17 @@
1
+ import dataclasses
2
+
3
+ import fastapi
4
+
5
+
6
+ @dataclasses.dataclass(kw_only=True, slots=True)
7
+ class SimpleCreator:
8
+ dep1: str
9
+
10
+
11
+ @dataclasses.dataclass(kw_only=True, slots=True)
12
+ class DependentCreator:
13
+ dep1: SimpleCreator
14
+
15
+
16
+ def context_adapter_function(*, request: fastapi.Request, **_: object) -> str:
17
+ return request.method
@@ -0,0 +1,57 @@
1
+ import typing
2
+
3
+ import fastapi
4
+ import modern_di
5
+ from modern_di import Scope, providers
6
+ from starlette import status
7
+ from starlette.testclient import TestClient
8
+
9
+ from modern_di_fastapi import Provide, build_request_container
10
+ from tests.dependencies import DependentCreator, SimpleCreator, context_adapter_function
11
+
12
+
13
+ app_factory = providers.Factory(Scope.APP, SimpleCreator, dep1="original")
14
+ request_factory = providers.Factory(Scope.REQUEST, DependentCreator, dep1=app_factory.cast)
15
+ action_factory = providers.Factory(Scope.ACTION, DependentCreator, dep1=app_factory.cast)
16
+ context_adapter = providers.ContextAdapter(Scope.REQUEST, context_adapter_function)
17
+
18
+
19
+ def test_factories(client: TestClient, app: fastapi.FastAPI) -> None:
20
+ @app.get("/")
21
+ async def read_root(
22
+ app_factory_instance: typing.Annotated[SimpleCreator, Provide(app_factory)],
23
+ request_factory_instance: typing.Annotated[DependentCreator, Provide(request_factory)],
24
+ ) -> None:
25
+ assert isinstance(app_factory_instance, SimpleCreator)
26
+ assert isinstance(request_factory_instance, DependentCreator)
27
+ assert request_factory_instance.dep1 is not app_factory_instance
28
+
29
+ response = client.get("/")
30
+ assert response.status_code == status.HTTP_200_OK
31
+ assert response.json() is None
32
+
33
+
34
+ def test_context_adapter(client: TestClient, app: fastapi.FastAPI) -> None:
35
+ @app.get("/")
36
+ async def read_root(
37
+ method: typing.Annotated[str, Provide(context_adapter)],
38
+ ) -> None:
39
+ assert method == "GET"
40
+
41
+ response = client.get("/")
42
+ assert response.status_code == status.HTTP_200_OK
43
+ assert response.json() is None
44
+
45
+
46
+ def test_factories_action_scope(client: TestClient, app: fastapi.FastAPI) -> None:
47
+ @app.get("/")
48
+ async def read_root(
49
+ request_container: typing.Annotated[modern_di.Container, fastapi.Depends(build_request_container)],
50
+ ) -> None:
51
+ with request_container.build_child_container() as action_container:
52
+ action_factory_instance = action_factory.sync_resolve(action_container)
53
+ assert isinstance(action_factory_instance, DependentCreator)
54
+
55
+ response = client.get("/")
56
+ assert response.status_code == status.HTTP_200_OK
57
+ assert response.json() is None
@@ -0,0 +1,33 @@
1
+ import typing
2
+
3
+ import fastapi
4
+ from modern_di import Scope, providers
5
+ from starlette.testclient import TestClient
6
+
7
+ from modern_di_fastapi import Provide
8
+ from tests.dependencies import DependentCreator, SimpleCreator
9
+
10
+
11
+ app_factory = providers.Factory(Scope.APP, SimpleCreator, dep1="original")
12
+ session_factory = providers.Factory(Scope.SESSION, DependentCreator, dep1=app_factory.cast)
13
+ request_factory = providers.Factory(Scope.REQUEST, DependentCreator, dep1=app_factory.cast)
14
+
15
+
16
+ async def test_factories(client: TestClient, app: fastapi.FastAPI) -> None:
17
+ @app.websocket("/ws")
18
+ async def websocket_endpoint(
19
+ websocket: fastapi.WebSocket,
20
+ app_factory_instance: typing.Annotated[SimpleCreator, Provide(app_factory)],
21
+ session_factory_instance: typing.Annotated[DependentCreator, Provide(session_factory)],
22
+ ) -> None:
23
+ assert isinstance(app_factory_instance, SimpleCreator)
24
+ assert isinstance(session_factory_instance, DependentCreator)
25
+ assert session_factory_instance.dep1 is not app_factory_instance
26
+
27
+ await websocket.accept()
28
+ await websocket.send_json({"msg": "Hello WebSocket"})
29
+ await websocket.close()
30
+
31
+ with client.websocket_connect("/ws") as websocket:
32
+ data = websocket.receive_json()
33
+ assert data == {"msg": "Hello WebSocket"}
@@ -23,10 +23,6 @@ class Container(contextlib.AbstractAsyncContextManager["Container"]):
23
23
  parent_container: typing.Optional["Container"] = None,
24
24
  context: dict[str, typing.Any] | None = None,
25
25
  ) -> None:
26
- if scope.value != 1 and parent_container is None:
27
- msg = "Only first scope can be used without parent_container"
28
- raise RuntimeError(msg)
29
-
30
26
  self.scope = scope
31
27
  self.parent_container = parent_container
32
28
  self.context: dict[str, typing.Any] = context or {}
@@ -38,27 +34,43 @@ class Container(contextlib.AbstractAsyncContextManager["Container"]):
38
34
  self._is_async = None
39
35
  self._provider_states = {}
40
36
  self._overrides = {}
37
+ self.context = {}
41
38
 
42
39
  def _check_entered(self) -> None:
43
40
  if self._is_async is None:
44
41
  msg = "Enter the context first"
45
42
  raise RuntimeError(msg)
46
43
 
47
- def build_child_container(self, context: dict[str, typing.Any] | None = None) -> "typing_extensions.Self":
44
+ def build_child_container(
45
+ self, context: dict[str, typing.Any] | None = None, scope: enum.IntEnum | None = None
46
+ ) -> "typing_extensions.Self":
48
47
  self._check_entered()
48
+ if scope and scope <= self.scope:
49
+ msg = "Scope of child container must be more than current scope"
50
+ raise RuntimeError(msg)
49
51
 
50
- try:
51
- new_scope = self.scope.__class__(self.scope.value + 1)
52
- except ValueError as exc:
53
- msg = f"Max scope is reached, {self.scope.name}"
54
- raise RuntimeError(msg) from exc
52
+ if not scope:
53
+ try:
54
+ scope = self.scope.__class__(self.scope.value + 1)
55
+ except ValueError as exc:
56
+ msg = f"Max scope is reached, {self.scope.name}"
57
+ raise RuntimeError(msg) from exc
55
58
 
56
- return self.__class__(scope=new_scope, parent_container=self, context=context)
59
+ return self.__class__(scope=scope, parent_container=self, context=context)
57
60
 
58
61
  def find_container(self, scope: enum.IntEnum) -> "typing_extensions.Self":
59
62
  container = self
63
+ if container.scope < scope:
64
+ msg = f"Scope {scope.name} is not initialized"
65
+ raise RuntimeError(msg)
66
+
60
67
  while container.scope > scope and container.parent_container:
61
68
  container = typing.cast("typing_extensions.Self", container.parent_container)
69
+
70
+ if container.scope != scope:
71
+ msg = f"Scope {scope.name} is skipped"
72
+ raise RuntimeError(msg)
73
+
62
74
  return container
63
75
 
64
76
  def fetch_provider_state(
@@ -0,0 +1,9 @@
1
+ import enum
2
+
3
+
4
+ class Scope(enum.IntEnum):
5
+ APP = 1
6
+ SESSION = 2
7
+ REQUEST = 3
8
+ ACTION = 4
9
+ STEP = 5
@@ -23,7 +23,7 @@ async def test_context_adapter_in_request_scope() -> None:
23
23
  now = datetime.datetime.now(tz=datetime.timezone.utc)
24
24
  async with (
25
25
  Container(scope=Scope.APP) as app_container,
26
- app_container.build_child_container(context={"now": now}) as request_container,
26
+ app_container.build_child_container(context={"now": now}, scope=Scope.REQUEST) as request_container,
27
27
  ):
28
28
  instance1 = await request_context_adapter.async_resolve(request_container)
29
29
  instance2 = request_context_adapter.sync_resolve(request_container)
@@ -34,12 +34,12 @@ async def test_app_factory() -> None:
34
34
 
35
35
  async def test_request_factory() -> None:
36
36
  with Container(scope=Scope.APP) as app_container:
37
- with app_container.build_child_container() as request_container:
37
+ with app_container.build_child_container(scope=Scope.REQUEST) as request_container:
38
38
  instance1 = request_factory.sync_resolve(request_container)
39
39
  instance2 = request_factory.sync_resolve(request_container)
40
40
  assert instance1 is not instance2
41
41
 
42
- async with app_container.build_child_container() as request_container:
42
+ async with app_container.build_child_container(scope=Scope.REQUEST) as request_container:
43
43
  instance3 = await request_factory.async_resolve(request_container)
44
44
  instance4 = await request_factory.async_resolve(request_container)
45
45
  assert instance3 is not instance4
@@ -85,3 +85,9 @@ async def test_factory_wrong_dependency_scope() -> None:
85
85
  request_factory_ = providers.Factory(Scope.REQUEST, SimpleCreator, dep1="original")
86
86
  with pytest.raises(RuntimeError, match="Scope of dependency cannot be more than scope of dependent"):
87
87
  providers.Singleton(Scope.APP, some_factory, request_factory_.cast)
88
+
89
+
90
+ async def test_factory_scope_is_not_initialized() -> None:
91
+ async with Container(scope=Scope.APP) as app_container:
92
+ with pytest.raises(RuntimeError, match="Scope REQUEST is not initialize"):
93
+ await request_factory.async_resolve(app_container)
@@ -23,7 +23,7 @@ async def test_selector() -> None:
23
23
  async def test_selector_in_request_scope() -> None:
24
24
  async with (
25
25
  Container(scope=Scope.APP) as app_container,
26
- app_container.build_child_container(context={"option": "request"}) as request_container,
26
+ app_container.build_child_container(context={"option": "request"}, scope=Scope.REQUEST) as request_container,
27
27
  ):
28
28
  instance1 = await request_selector.async_resolve(request_container)
29
29
  instance2 = request_selector.sync_resolve(request_container)
@@ -43,12 +43,12 @@ async def test_app_singleton() -> None:
43
43
 
44
44
  async def test_request_singleton() -> None:
45
45
  with Container(scope=Scope.APP) as app_container:
46
- with app_container.build_child_container() as request_container:
46
+ with app_container.build_child_container(scope=Scope.REQUEST) as request_container:
47
47
  instance1 = request_singleton.sync_resolve(request_container)
48
48
  instance2 = request_singleton.sync_resolve(request_container)
49
49
  assert instance1 is instance2
50
50
 
51
- async with app_container.build_child_container() as request_container:
51
+ async with app_container.build_child_container(scope=Scope.REQUEST) as request_container:
52
52
  instance3 = await request_singleton.async_resolve(request_container)
53
53
  instance4 = await request_singleton.async_resolve(request_container)
54
54
  assert instance3 is instance4
@@ -0,0 +1,46 @@
1
+ import pytest
2
+
3
+ from modern_di import Container, Scope, providers
4
+
5
+
6
+ def test_container_not_opened() -> None:
7
+ container = Container(scope=Scope.APP)
8
+ with pytest.raises(RuntimeError, match="Enter the context first"):
9
+ container.fetch_provider_state("some_id")
10
+
11
+
12
+ def test_container_scope_skipped() -> None:
13
+ app_factory = providers.Factory(Scope.APP, lambda: "test")
14
+ with Container(scope=Scope.REQUEST) as container, pytest.raises(RuntimeError, match="Scope APP is skipped"):
15
+ app_factory.sync_resolve(container)
16
+
17
+
18
+ async def test_container_build_child_async() -> None:
19
+ async with (
20
+ Container(scope=Scope.APP) as app_container,
21
+ app_container.build_child_container(scope=Scope.REQUEST) as request_container,
22
+ ):
23
+ assert request_container.scope == Scope.REQUEST
24
+ assert app_container.scope == Scope.APP
25
+
26
+
27
+ def test_container_build_child_sync() -> None:
28
+ with (
29
+ Container(scope=Scope.APP) as app_container,
30
+ app_container.build_child_container(scope=Scope.REQUEST) as request_container,
31
+ ):
32
+ assert request_container.scope == Scope.REQUEST
33
+ assert app_container.scope == Scope.APP
34
+
35
+
36
+ def test_container_scope_limit_reached() -> None:
37
+ with Container(scope=Scope.STEP) as app_container, pytest.raises(RuntimeError, match="Max scope is reached, STEP"):
38
+ app_container.build_child_container()
39
+
40
+
41
+ async def test_container_build_child_wrong_scope() -> None:
42
+ with (
43
+ Container(scope=Scope.APP) as app_container,
44
+ pytest.raises(RuntimeError, match="Scope of child container must be more than current scope"),
45
+ ):
46
+ app_container.build_child_container(scope=Scope.APP)
@@ -1,9 +0,0 @@
1
- from modern_di_fastapi.depends import FromDI, setup_modern_di
2
- from modern_di_fastapi.middleware import ContainerMiddleware
3
-
4
-
5
- __all__ = [
6
- "ContainerMiddleware",
7
- "FromDI",
8
- "setup_modern_di",
9
- ]
@@ -1,24 +0,0 @@
1
- import dataclasses
2
- import typing
3
-
4
- import fastapi
5
- from modern_di import Container, providers
6
-
7
-
8
- T_co = typing.TypeVar("T_co", covariant=True)
9
-
10
-
11
- @dataclasses.dataclass(slots=True, frozen=True)
12
- class Dependency(typing.Generic[T_co]):
13
- dependency: providers.AbstractProvider[T_co]
14
-
15
- async def __call__(self, request: fastapi.Request) -> T_co:
16
- return await self.dependency.async_resolve(request.state.modern_di_container)
17
-
18
-
19
- def FromDI(dependency: providers.AbstractProvider[T_co], *, use_cache: bool = True) -> T_co: # noqa: N802
20
- return typing.cast(T_co, fastapi.Depends(dependency=Dependency(dependency), use_cache=use_cache))
21
-
22
-
23
- def setup_modern_di(container: Container, app: fastapi.FastAPI) -> None:
24
- app.state.modern_di_container = container
@@ -1,27 +0,0 @@
1
- import typing
2
-
3
- import modern_di
4
- from starlette.requests import Request
5
- from starlette.types import ASGIApp, Receive, Scope, Send
6
-
7
-
8
- class ContainerMiddleware:
9
- def __init__(self, app: ASGIApp) -> None:
10
- self.app = app
11
-
12
- async def __call__(
13
- self,
14
- scope: Scope,
15
- receive: Receive,
16
- send: Send,
17
- ) -> None:
18
- if scope["type"] != "http":
19
- return await self.app(scope, receive, send)
20
-
21
- request = Request(scope, receive=receive, send=send)
22
- context: dict[str, typing.Any] = {"request": request}
23
-
24
- container: modern_di.Container = request.app.state.modern_di_container
25
- async with container.build_child_container(context=context) as request_container:
26
- request.state.modern_di_container = request_container
27
- return await self.app(scope, receive, send)
@@ -1,69 +0,0 @@
1
- import contextlib
2
- import dataclasses
3
- import typing
4
-
5
- import fastapi
6
- import httpx
7
- import modern_di
8
- import pytest
9
- from asgi_lifespan import LifespanManager
10
- from modern_di import Scope, providers
11
- from starlette import status
12
- from starlette.requests import Request
13
-
14
- import modern_di_fastapi
15
- from modern_di_fastapi import ContainerMiddleware, FromDI
16
-
17
-
18
- @contextlib.asynccontextmanager
19
- async def lifespan(app_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
20
- di_container = modern_di.Container(scope=modern_di.Scope.APP)
21
- modern_di_fastapi.setup_modern_di(container=di_container, app=app_)
22
- async with di_container:
23
- yield
24
-
25
-
26
- app = fastapi.FastAPI(lifespan=lifespan)
27
- app.add_middleware(ContainerMiddleware)
28
-
29
-
30
- @dataclasses.dataclass(kw_only=True, slots=True)
31
- class SimpleCreator:
32
- dep1: str
33
-
34
-
35
- @dataclasses.dataclass(kw_only=True, slots=True)
36
- class DependentCreator:
37
- dep1: SimpleCreator
38
-
39
-
40
- def context_adapter_function(*, request: Request, **_: object) -> str:
41
- return request.method
42
-
43
-
44
- app_factory = providers.Factory(Scope.APP, SimpleCreator, dep1="original")
45
- request_factory = providers.Factory(Scope.REQUEST, DependentCreator, dep1=app_factory.cast)
46
- context_adapter = providers.ContextAdapter(Scope.REQUEST, context_adapter_function)
47
-
48
-
49
- @app.get("/")
50
- async def read_root(
51
- app_factory_instance: typing.Annotated[SimpleCreator, FromDI(app_factory)],
52
- request_factory_instance: typing.Annotated[DependentCreator, FromDI(request_factory)],
53
- method: typing.Annotated[str, FromDI(context_adapter)],
54
- ) -> str:
55
- assert isinstance(app_factory_instance, SimpleCreator)
56
- assert isinstance(request_factory_instance, DependentCreator)
57
- return method
58
-
59
-
60
- @pytest.fixture(scope="session")
61
- async def client() -> typing.AsyncIterator[httpx.AsyncClient]:
62
- async with LifespanManager(app):
63
- yield httpx.AsyncClient(app=app, base_url="http://test")
64
-
65
-
66
- async def test_read_main(client: httpx.AsyncClient) -> None:
67
- response = await client.get("/")
68
- assert response.status_code == status.HTTP_200_OK
69
- assert response.json() == "GET"
@@ -1,8 +0,0 @@
1
- import enum
2
-
3
-
4
- class Scope(enum.IntEnum):
5
- APP = 1
6
- REQUEST = 2
7
- ACTION = 3
8
- STEP = 4
@@ -1,41 +0,0 @@
1
- import enum
2
-
3
- import pytest
4
-
5
- from modern_di import Container, Scope
6
-
7
-
8
- def test_container_wrong_init() -> None:
9
- with pytest.raises(RuntimeError, match="Only first scope can be used without parent_container"):
10
- Container(scope=Scope.REQUEST)
11
-
12
-
13
- def test_container_not_opened() -> None:
14
- container = Container(scope=Scope.APP)
15
- with pytest.raises(RuntimeError, match="Enter the context first"):
16
- container.fetch_provider_state("some_id")
17
-
18
-
19
- async def test_container_build_child_async() -> None:
20
- async with Container(scope=Scope.APP) as app_container, app_container.build_child_container() as request_container:
21
- assert request_container.scope == Scope.REQUEST
22
- assert app_container.scope == Scope.APP
23
-
24
-
25
- def test_container_build_child_sync() -> None:
26
- with Container(scope=Scope.APP) as app_container, app_container.build_child_container() as request_container:
27
- assert request_container.scope == Scope.REQUEST
28
- assert app_container.scope == Scope.APP
29
-
30
-
31
- def test_container_scope_limit_reached() -> None:
32
- class CustomScope(enum.IntEnum):
33
- APP = 1
34
- REQUEST = 2
35
-
36
- with Container(scope=CustomScope.APP) as app_container, app_container.build_child_container() as request_container:
37
- assert request_container.scope == CustomScope.REQUEST
38
- assert app_container.scope == CustomScope.APP
39
-
40
- with pytest.raises(RuntimeError, match="Max scope is reached, REQUEST"):
41
- request_container.build_child_container()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes