modern-di 0.1.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.
- modern_di-0.1.0/.github/workflows/ci.yml +51 -0
- modern_di-0.1.0/.github/workflows/publish.yml +20 -0
- modern_di-0.1.0/.gitignore +22 -0
- modern_di-0.1.0/Justfile +23 -0
- modern_di-0.1.0/LICENSE +21 -0
- modern_di-0.1.0/PKG-INFO +38 -0
- modern_di-0.1.0/README.md +19 -0
- modern_di-0.1.0/docs/conf.py +34 -0
- modern_di-0.1.0/docs/dev/contributing.md +19 -0
- modern_di-0.1.0/docs/dev/development-notes.md +25 -0
- modern_di-0.1.0/docs/index.md +11 -0
- modern_di-0.1.0/docs/requirements.txt +4 -0
- modern_di-0.1.0/modern_di/__init__.py +11 -0
- modern_di-0.1.0/modern_di/container.py +109 -0
- modern_di-0.1.0/modern_di/graph.py +39 -0
- modern_di-0.1.0/modern_di/py.typed +0 -0
- modern_di-0.1.0/modern_di/resolver_state.py +38 -0
- modern_di-0.1.0/modern_di/resolvers/__init__.py +11 -0
- modern_di-0.1.0/modern_di/resolvers/base.py +88 -0
- modern_di-0.1.0/modern_di/resolvers/factory.py +46 -0
- modern_di-0.1.0/modern_di/resolvers/resource.py +95 -0
- modern_di-0.1.0/modern_di/scope.py +8 -0
- modern_di-0.1.0/pyproject.toml +80 -0
- modern_di-0.1.0/tests/__init__.py +0 -0
- modern_di-0.1.0/tests/creators.py +22 -0
- modern_di-0.1.0/tests/resolvers/__init__.py +0 -0
- modern_di-0.1.0/tests/resolvers/test_factory.py +115 -0
- modern_di-0.1.0/tests/resolvers/test_resource.py +119 -0
- modern_di-0.1.0/tests/test_container.py +41 -0
- modern_di-0.1.0/tests/test_graph.py +39 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
name: main
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches:
|
|
6
|
+
- main
|
|
7
|
+
pull_request: {}
|
|
8
|
+
|
|
9
|
+
concurrency:
|
|
10
|
+
group: ${{ github.head_ref || github.run_id }}
|
|
11
|
+
cancel-in-progress: true
|
|
12
|
+
|
|
13
|
+
jobs:
|
|
14
|
+
lint:
|
|
15
|
+
runs-on: ubuntu-latest
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
- uses: extractions/setup-just@v2
|
|
19
|
+
- uses: astral-sh/setup-uv@v3
|
|
20
|
+
with:
|
|
21
|
+
enable-cache: true
|
|
22
|
+
cache-dependency-glob: "**/pyproject.toml"
|
|
23
|
+
- run: uv python install 3.10
|
|
24
|
+
- run: just install lint-ci
|
|
25
|
+
|
|
26
|
+
pytest:
|
|
27
|
+
runs-on: ubuntu-latest
|
|
28
|
+
strategy:
|
|
29
|
+
fail-fast: false
|
|
30
|
+
matrix:
|
|
31
|
+
python-version:
|
|
32
|
+
- "3.10"
|
|
33
|
+
- "3.11"
|
|
34
|
+
- "3.12"
|
|
35
|
+
- "3.13"
|
|
36
|
+
steps:
|
|
37
|
+
- uses: actions/checkout@v4
|
|
38
|
+
- uses: extractions/setup-just@v2
|
|
39
|
+
- uses: astral-sh/setup-uv@v3
|
|
40
|
+
with:
|
|
41
|
+
enable-cache: true
|
|
42
|
+
cache-dependency-glob: "**/pyproject.toml"
|
|
43
|
+
- run: uv python install ${{ matrix.python-version }}
|
|
44
|
+
- run: just install test . --cov=. --cov-report xml
|
|
45
|
+
- uses: codecov/codecov-action@v4.0.1
|
|
46
|
+
env:
|
|
47
|
+
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
|
48
|
+
with:
|
|
49
|
+
files: ./coverage.xml
|
|
50
|
+
flags: unittests
|
|
51
|
+
name: codecov-${{ matrix.python-version }}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: Publish Package
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types:
|
|
6
|
+
- published
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
publish:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
- uses: extractions/setup-just@v2
|
|
14
|
+
- uses: astral-sh/setup-uv@v3
|
|
15
|
+
with:
|
|
16
|
+
enable-cache: true
|
|
17
|
+
cache-dependency-glob: "**/pyproject.toml"
|
|
18
|
+
- run: just publish
|
|
19
|
+
env:
|
|
20
|
+
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Generic things
|
|
2
|
+
*.pyc
|
|
3
|
+
*~
|
|
4
|
+
__pycache__/*
|
|
5
|
+
*.swp
|
|
6
|
+
*.sqlite3
|
|
7
|
+
*.map
|
|
8
|
+
.vscode
|
|
9
|
+
.idea
|
|
10
|
+
.DS_Store
|
|
11
|
+
.env
|
|
12
|
+
.mypy_cache
|
|
13
|
+
.pytest_cache
|
|
14
|
+
.ruff_cache
|
|
15
|
+
.coverage
|
|
16
|
+
htmlcov/
|
|
17
|
+
coverage.xml
|
|
18
|
+
pytest.xml
|
|
19
|
+
dist/
|
|
20
|
+
.python-version
|
|
21
|
+
.venv
|
|
22
|
+
uv.lock
|
modern_di-0.1.0/Justfile
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
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 }}
|
|
19
|
+
|
|
20
|
+
publish:
|
|
21
|
+
rm -rf dist
|
|
22
|
+
uv build
|
|
23
|
+
uv publish --token $PYPI_TOKEN
|
modern_di-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 modern-python
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
modern_di-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: modern-di
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simple Dependency Injection framework
|
|
5
|
+
Project-URL: repository, https://github.com/modern-python/that-depends
|
|
6
|
+
Project-URL: docs, https://that-depends.readthedocs.io
|
|
7
|
+
Author-email: Artur Shiriev <me@shiriev.ru>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: dependency injector,di,ioc-container,mocks,python
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: <4,>=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
"Modern-DI"
|
|
21
|
+
==
|
|
22
|
+
[](https://codecov.io/gh/modern-python/modern-di)
|
|
23
|
+
[](https://mypy.readthedocs.io/en/stable/getting_started.html#strict-mode-and-configuration)
|
|
24
|
+
[](https://pypi.python.org/pypi/modern-di)
|
|
25
|
+
[](https://pypistats.org/packages/modern-di)
|
|
26
|
+
[](https://github.com/modern-python/modern-di/stargazers)
|
|
27
|
+
|
|
28
|
+
Dependency injection framework for Python inspired by `dependency-injector` and `dishka`.
|
|
29
|
+
|
|
30
|
+
It is production-ready and gives you the following:
|
|
31
|
+
- Simple DI framework with IOC-container.
|
|
32
|
+
- Async and sync resolving.
|
|
33
|
+
- Python 3.10-3.13 support.
|
|
34
|
+
- Full coverage by types annotations (mypy in strict mode).
|
|
35
|
+
- Overriding dependencies for tests.
|
|
36
|
+
- Package with zero dependencies.
|
|
37
|
+
|
|
38
|
+
📚 [Documentation](https://modern-di.readthedocs.io)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"Modern-DI"
|
|
2
|
+
==
|
|
3
|
+
[](https://codecov.io/gh/modern-python/modern-di)
|
|
4
|
+
[](https://mypy.readthedocs.io/en/stable/getting_started.html#strict-mode-and-configuration)
|
|
5
|
+
[](https://pypi.python.org/pypi/modern-di)
|
|
6
|
+
[](https://pypistats.org/packages/modern-di)
|
|
7
|
+
[](https://github.com/modern-python/modern-di/stargazers)
|
|
8
|
+
|
|
9
|
+
Dependency injection framework for Python inspired by `dependency-injector` and `dishka`.
|
|
10
|
+
|
|
11
|
+
It is production-ready and gives you the following:
|
|
12
|
+
- Simple DI framework with IOC-container.
|
|
13
|
+
- Async and sync resolving.
|
|
14
|
+
- Python 3.10-3.13 support.
|
|
15
|
+
- Full coverage by types annotations (mypy in strict mode).
|
|
16
|
+
- Overriding dependencies for tests.
|
|
17
|
+
- Package with zero dependencies.
|
|
18
|
+
|
|
19
|
+
📚 [Documentation](https://modern-di.readthedocs.io)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Configuration file for the Sphinx documentation builder.
|
|
2
|
+
|
|
3
|
+
# -- Project information
|
|
4
|
+
project = "modern-di"
|
|
5
|
+
copyright = "2024, Modern Python"
|
|
6
|
+
author = "Modern Python Community"
|
|
7
|
+
|
|
8
|
+
release = ""
|
|
9
|
+
version = ""
|
|
10
|
+
|
|
11
|
+
# -- General configuration
|
|
12
|
+
extensions = [
|
|
13
|
+
"sphinx_copybutton",
|
|
14
|
+
"sphinx.ext.duration",
|
|
15
|
+
"sphinx.ext.doctest",
|
|
16
|
+
"sphinx.ext.autodoc",
|
|
17
|
+
"sphinx.ext.autosummary",
|
|
18
|
+
"sphinx.ext.intersphinx",
|
|
19
|
+
"myst_parser",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
intersphinx_mapping = {
|
|
23
|
+
"python": ("https://docs.python.org/3/", None),
|
|
24
|
+
"sphinx": ("https://www.sphinx-doc.org/en/master/", None),
|
|
25
|
+
}
|
|
26
|
+
intersphinx_disabled_domains = ["std"]
|
|
27
|
+
|
|
28
|
+
templates_path = ["_templates"]
|
|
29
|
+
|
|
30
|
+
# -- Options for HTML output
|
|
31
|
+
html_theme = "sphinx_rtd_theme"
|
|
32
|
+
|
|
33
|
+
# -- Options for EPUB output
|
|
34
|
+
epub_show_urls = "footnote"
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
This is an opensource project, and we are opened to new contributors.
|
|
3
|
+
|
|
4
|
+
## Getting started
|
|
5
|
+
1. Make sure that you have [uv](https://docs.astral.sh/uv/) and [just](https://just.systems/) installed.
|
|
6
|
+
2. Clone project:
|
|
7
|
+
```
|
|
8
|
+
git@github.com:modern-python/modern-di.git
|
|
9
|
+
cd modern-di
|
|
10
|
+
```
|
|
11
|
+
3. Install dependencies running `just install`
|
|
12
|
+
|
|
13
|
+
## Running linters
|
|
14
|
+
`Ruff` and `mypy` are used for static analysis.
|
|
15
|
+
|
|
16
|
+
Run all checks by command `just lint`
|
|
17
|
+
|
|
18
|
+
## Running tests
|
|
19
|
+
Run all tests by command `just test`
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Development Notes
|
|
2
|
+
## Base parts
|
|
3
|
+
### Scope
|
|
4
|
+
- any int enum, starting from 1 with step 1
|
|
5
|
+
|
|
6
|
+
### Container
|
|
7
|
+
- all states live in containers:
|
|
8
|
+
- resolved dependencies
|
|
9
|
+
- context stacks for resources
|
|
10
|
+
- overrides
|
|
11
|
+
|
|
12
|
+
### Resolvers
|
|
13
|
+
- completely stateless
|
|
14
|
+
- if dependency is already saved or overridden in `Container`, returns it
|
|
15
|
+
- otherwise build dependency and save it to `Container`
|
|
16
|
+
- can have dependencies only the same or lower scope, check in init
|
|
17
|
+
|
|
18
|
+
### Graph
|
|
19
|
+
- Cannot be instantiated
|
|
20
|
+
- Contains graph of `Resolvers`
|
|
21
|
+
- Can initialize its resources and factories to container
|
|
22
|
+
|
|
23
|
+
### Questions
|
|
24
|
+
1. Thread-safety
|
|
25
|
+
2. Configuration without global object
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import enum
|
|
3
|
+
import types
|
|
4
|
+
import typing
|
|
5
|
+
|
|
6
|
+
from modern_di.resolver_state import ResolverState
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
if typing.TYPE_CHECKING:
|
|
10
|
+
import typing_extensions
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
T_co = typing.TypeVar("T_co", covariant=True)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Container(contextlib.AbstractAsyncContextManager["Container"]):
|
|
17
|
+
__slots__ = "scope", "parent_container", "_is_async", "_resolver_states", "_overrides"
|
|
18
|
+
|
|
19
|
+
def __init__(self, *, scope: enum.IntEnum, parent_container: typing.Optional["Container"] = None) -> None:
|
|
20
|
+
if scope.value != 1 and parent_container is None:
|
|
21
|
+
msg = "Only first scope can be used without parent_container"
|
|
22
|
+
raise RuntimeError(msg)
|
|
23
|
+
|
|
24
|
+
self.scope = scope
|
|
25
|
+
self.parent_container = parent_container
|
|
26
|
+
self._is_async: bool | None = None
|
|
27
|
+
self._resolver_states: dict[str, ResolverState[typing.Any]] = {}
|
|
28
|
+
self._overrides: dict[str, typing.Any] = {}
|
|
29
|
+
|
|
30
|
+
def _exit(self) -> None:
|
|
31
|
+
self._is_async = None
|
|
32
|
+
self._resolver_states = {}
|
|
33
|
+
|
|
34
|
+
def _check_entered(self) -> None:
|
|
35
|
+
if self._is_async is None:
|
|
36
|
+
msg = "Enter the context first"
|
|
37
|
+
raise RuntimeError(msg)
|
|
38
|
+
|
|
39
|
+
def build_child_container(self) -> "typing_extensions.Self":
|
|
40
|
+
self._check_entered()
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
new_scope = self.scope.__class__(self.scope.value + 1)
|
|
44
|
+
except ValueError as exc:
|
|
45
|
+
msg = f"Max scope is reached, {self.scope.name}"
|
|
46
|
+
raise RuntimeError(msg) from exc
|
|
47
|
+
|
|
48
|
+
return self.__class__(scope=new_scope, parent_container=self)
|
|
49
|
+
|
|
50
|
+
def find_container(self, scope: enum.IntEnum) -> "typing_extensions.Self":
|
|
51
|
+
container = self
|
|
52
|
+
while container.scope > scope and container.parent_container:
|
|
53
|
+
container = typing.cast("typing_extensions.Self", container.parent_container)
|
|
54
|
+
return container
|
|
55
|
+
|
|
56
|
+
def fetch_resolver_state(
|
|
57
|
+
self, resolver_id: str, is_async_resource: bool = False, is_lock_required: bool = False
|
|
58
|
+
) -> ResolverState[typing.Any]:
|
|
59
|
+
self._check_entered()
|
|
60
|
+
if is_async_resource and self._is_async is False:
|
|
61
|
+
msg = "Resolving async resource in sync container is not allowed"
|
|
62
|
+
raise RuntimeError(msg)
|
|
63
|
+
|
|
64
|
+
if resolver_id not in self._resolver_states:
|
|
65
|
+
self._resolver_states[resolver_id] = ResolverState(is_lock_required=is_lock_required)
|
|
66
|
+
|
|
67
|
+
return self._resolver_states[resolver_id]
|
|
68
|
+
|
|
69
|
+
def override(self, resolver_id: str, override_object: object) -> None:
|
|
70
|
+
self._overrides[resolver_id] = override_object
|
|
71
|
+
|
|
72
|
+
def fetch_override(self, resolver_id: str) -> object | None:
|
|
73
|
+
return self._overrides.get(resolver_id)
|
|
74
|
+
|
|
75
|
+
def reset_override(self, resolver_id: str | None = None) -> None:
|
|
76
|
+
if resolver_id is None:
|
|
77
|
+
self._overrides = {}
|
|
78
|
+
else:
|
|
79
|
+
self._overrides.pop(resolver_id, None)
|
|
80
|
+
|
|
81
|
+
async def __aenter__(self) -> "Container":
|
|
82
|
+
self._is_async = True
|
|
83
|
+
return self
|
|
84
|
+
|
|
85
|
+
async def __aexit__(
|
|
86
|
+
self,
|
|
87
|
+
exc_type: type[BaseException] | None,
|
|
88
|
+
exc_val: BaseException | None,
|
|
89
|
+
traceback: types.TracebackType | None,
|
|
90
|
+
) -> None:
|
|
91
|
+
self._check_entered()
|
|
92
|
+
for resolver_state in reversed(self._resolver_states.values()):
|
|
93
|
+
await resolver_state.async_tear_down()
|
|
94
|
+
self._exit()
|
|
95
|
+
|
|
96
|
+
def __enter__(self) -> "Container":
|
|
97
|
+
self._is_async = False
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
def __exit__(
|
|
101
|
+
self,
|
|
102
|
+
exc_type: type[BaseException] | None,
|
|
103
|
+
exc_value: BaseException | None,
|
|
104
|
+
traceback: types.TracebackType | None,
|
|
105
|
+
) -> None:
|
|
106
|
+
self._check_entered()
|
|
107
|
+
for resolver_state in reversed(self._resolver_states.values()):
|
|
108
|
+
resolver_state.sync_tear_down()
|
|
109
|
+
self._exit()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
|
|
3
|
+
from modern_di import Container
|
|
4
|
+
from modern_di.resolvers import AbstractResolver, BaseCreatorResolver
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
if typing.TYPE_CHECKING:
|
|
8
|
+
import typing_extensions
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
T = typing.TypeVar("T")
|
|
12
|
+
P = typing.ParamSpec("P")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BaseGraph:
|
|
16
|
+
resolvers: dict[str, AbstractResolver[typing.Any]]
|
|
17
|
+
|
|
18
|
+
def __new__(cls, *_: typing.Any, **__: typing.Any) -> "typing_extensions.Self": # noqa: ANN401
|
|
19
|
+
msg = f"{cls.__name__} cannot not be instantiated"
|
|
20
|
+
raise RuntimeError(msg)
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def get_resolvers(cls) -> dict[str, AbstractResolver[typing.Any]]:
|
|
24
|
+
if not hasattr(cls, "resolvers"):
|
|
25
|
+
cls.resolvers = {k: v for k, v in cls.__dict__.items() if isinstance(v, AbstractResolver)}
|
|
26
|
+
|
|
27
|
+
return cls.resolvers
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
async def async_resolve_creators(cls, container: Container) -> None:
|
|
31
|
+
for resolver in cls.get_resolvers().values():
|
|
32
|
+
if isinstance(resolver, BaseCreatorResolver) and resolver.scope == container.scope:
|
|
33
|
+
await resolver.async_resolve(container)
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def sync_resolve_creators(cls, container: Container) -> None:
|
|
37
|
+
for resolver in cls.get_resolvers().values():
|
|
38
|
+
if isinstance(resolver, BaseCreatorResolver) and resolver.scope == container.scope:
|
|
39
|
+
resolver.sync_resolve(container)
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import contextlib
|
|
3
|
+
import typing
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
T_co = typing.TypeVar("T_co", covariant=True)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ResolverState(typing.Generic[T_co]):
|
|
10
|
+
__slots__ = "context_stack", "instance", "resolver_lock"
|
|
11
|
+
|
|
12
|
+
def __init__(self, is_lock_required: bool) -> None:
|
|
13
|
+
self.context_stack: contextlib.AsyncExitStack | contextlib.ExitStack | None = None
|
|
14
|
+
self.instance: T_co | None = None
|
|
15
|
+
self.resolver_lock: typing.Final = asyncio.Lock() if is_lock_required else None
|
|
16
|
+
|
|
17
|
+
async def async_tear_down(self) -> None:
|
|
18
|
+
if self.context_stack is None:
|
|
19
|
+
return
|
|
20
|
+
|
|
21
|
+
if isinstance(self.context_stack, contextlib.AsyncExitStack):
|
|
22
|
+
await self.context_stack.aclose()
|
|
23
|
+
else:
|
|
24
|
+
self.context_stack.close()
|
|
25
|
+
self.context_stack = None
|
|
26
|
+
self.instance = None
|
|
27
|
+
|
|
28
|
+
def sync_tear_down(self) -> None:
|
|
29
|
+
if self.context_stack is None:
|
|
30
|
+
return
|
|
31
|
+
|
|
32
|
+
if isinstance(self.context_stack, contextlib.AsyncExitStack):
|
|
33
|
+
msg = "Cannot tear down async context in `sync_tear_down`"
|
|
34
|
+
raise RuntimeError(msg) # noqa: TRY004
|
|
35
|
+
|
|
36
|
+
self.context_stack.close()
|
|
37
|
+
self.context_stack = None
|
|
38
|
+
self.instance = None
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from modern_di.resolvers.base import AbstractResolver, BaseCreatorResolver
|
|
2
|
+
from modern_di.resolvers.factory import Factory
|
|
3
|
+
from modern_di.resolvers.resource import Resource
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"AbstractResolver",
|
|
8
|
+
"BaseCreatorResolver",
|
|
9
|
+
"Factory",
|
|
10
|
+
"Resource",
|
|
11
|
+
]
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import enum
|
|
3
|
+
import itertools
|
|
4
|
+
import typing
|
|
5
|
+
import uuid
|
|
6
|
+
|
|
7
|
+
from modern_di import Container
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
T_co = typing.TypeVar("T_co", covariant=True)
|
|
11
|
+
R = typing.TypeVar("R")
|
|
12
|
+
P = typing.ParamSpec("P")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AbstractResolver(typing.Generic[T_co], abc.ABC):
|
|
16
|
+
BASE_SLOTS: typing.ClassVar = ["scope", "resolver_id"]
|
|
17
|
+
|
|
18
|
+
def __init__(self, scope: enum.IntEnum) -> None:
|
|
19
|
+
self.scope = scope
|
|
20
|
+
self.resolver_id: typing.Final = str(uuid.uuid4())
|
|
21
|
+
|
|
22
|
+
@abc.abstractmethod
|
|
23
|
+
async def async_resolve(self, container: Container) -> T_co:
|
|
24
|
+
"""Resolve dependency asynchronously."""
|
|
25
|
+
|
|
26
|
+
@abc.abstractmethod
|
|
27
|
+
def sync_resolve(self, container: Container) -> T_co:
|
|
28
|
+
"""Resolve dependency synchronously."""
|
|
29
|
+
|
|
30
|
+
def override(self, override_object: object, container: Container) -> None:
|
|
31
|
+
container.override(self.resolver_id, override_object)
|
|
32
|
+
|
|
33
|
+
def reset_override(self, container: Container) -> None:
|
|
34
|
+
container.reset_override(self.resolver_id)
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def cast(self) -> T_co:
|
|
38
|
+
return typing.cast(T_co, self)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BaseCreatorResolver(AbstractResolver[T_co], abc.ABC):
|
|
42
|
+
BASE_SLOTS: typing.ClassVar = [*AbstractResolver.BASE_SLOTS, "_args", "_kwargs", "_creator"]
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
scope: enum.IntEnum,
|
|
47
|
+
creator: typing.Callable[P, typing.Any],
|
|
48
|
+
*args: P.args,
|
|
49
|
+
**kwargs: P.kwargs,
|
|
50
|
+
) -> None:
|
|
51
|
+
super().__init__(scope)
|
|
52
|
+
|
|
53
|
+
if any(x.scope > self.scope for x in itertools.chain(args, kwargs.values()) if isinstance(x, AbstractResolver)):
|
|
54
|
+
msg = "Scope of dependency cannot be more than scope of dependent"
|
|
55
|
+
raise RuntimeError(msg)
|
|
56
|
+
|
|
57
|
+
self._creator: typing.Final = creator
|
|
58
|
+
self._args: typing.Final = args
|
|
59
|
+
self._kwargs: typing.Final = kwargs
|
|
60
|
+
|
|
61
|
+
def _sync_build_creator(self, container: Container) -> typing.Any: # noqa: ANN401
|
|
62
|
+
return self._creator(
|
|
63
|
+
*typing.cast(
|
|
64
|
+
P.args, [x.sync_resolve(container) if isinstance(x, AbstractResolver) else x for x in self._args]
|
|
65
|
+
),
|
|
66
|
+
**typing.cast(
|
|
67
|
+
P.kwargs,
|
|
68
|
+
{
|
|
69
|
+
k: v.sync_resolve(container) if isinstance(v, AbstractResolver) else v
|
|
70
|
+
for k, v in self._kwargs.items()
|
|
71
|
+
},
|
|
72
|
+
),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
async def _async_build_creator(self, container: Container) -> typing.Any: # noqa: ANN401
|
|
76
|
+
return self._creator(
|
|
77
|
+
*typing.cast(
|
|
78
|
+
P.args,
|
|
79
|
+
[await x.async_resolve(container) if isinstance(x, AbstractResolver) else x for x in self._args],
|
|
80
|
+
),
|
|
81
|
+
**typing.cast(
|
|
82
|
+
P.kwargs,
|
|
83
|
+
{
|
|
84
|
+
k: await v.async_resolve(container) if isinstance(v, AbstractResolver) else v
|
|
85
|
+
for k, v in self._kwargs.items()
|
|
86
|
+
},
|
|
87
|
+
),
|
|
88
|
+
)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import enum
|
|
2
|
+
import typing
|
|
3
|
+
|
|
4
|
+
from modern_di import Container
|
|
5
|
+
from modern_di.resolvers import BaseCreatorResolver
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
T_co = typing.TypeVar("T_co", covariant=True)
|
|
9
|
+
P = typing.ParamSpec("P")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Factory(BaseCreatorResolver[T_co]):
|
|
13
|
+
__slots__ = [*BaseCreatorResolver.BASE_SLOTS, "_creator"]
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
scope: enum.IntEnum,
|
|
18
|
+
creator: typing.Callable[P, T_co],
|
|
19
|
+
*args: P.args,
|
|
20
|
+
**kwargs: P.kwargs,
|
|
21
|
+
) -> None:
|
|
22
|
+
super().__init__(scope, creator, *args, **kwargs)
|
|
23
|
+
|
|
24
|
+
async def async_resolve(self, container: Container) -> T_co:
|
|
25
|
+
container = container.find_container(self.scope)
|
|
26
|
+
if (override := container.fetch_override(self.resolver_id)) is not None:
|
|
27
|
+
return typing.cast(T_co, override)
|
|
28
|
+
|
|
29
|
+
resolver_state = container.fetch_resolver_state(self.resolver_id)
|
|
30
|
+
if resolver_state.instance is not None:
|
|
31
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
32
|
+
|
|
33
|
+
resolver_state.instance = typing.cast(T_co, await self._async_build_creator(container))
|
|
34
|
+
return resolver_state.instance
|
|
35
|
+
|
|
36
|
+
def sync_resolve(self, container: Container) -> T_co:
|
|
37
|
+
container = container.find_container(self.scope)
|
|
38
|
+
if (override := container.fetch_override(self.resolver_id)) is not None:
|
|
39
|
+
return typing.cast(T_co, override)
|
|
40
|
+
|
|
41
|
+
resolver_state = container.fetch_resolver_state(self.resolver_id)
|
|
42
|
+
if resolver_state.instance is not None:
|
|
43
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
44
|
+
|
|
45
|
+
resolver_state.instance = self._sync_build_creator(container)
|
|
46
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import enum
|
|
3
|
+
import inspect
|
|
4
|
+
import typing
|
|
5
|
+
|
|
6
|
+
from modern_di import Container
|
|
7
|
+
from modern_di.resolvers import BaseCreatorResolver
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
T_co = typing.TypeVar("T_co", covariant=True)
|
|
11
|
+
P = typing.ParamSpec("P")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Resource(BaseCreatorResolver[T_co]):
|
|
15
|
+
__slots__ = [*BaseCreatorResolver.BASE_SLOTS, "_creator", "_args", "_kwargs", "_is_async"]
|
|
16
|
+
|
|
17
|
+
def _is_creator_async(
|
|
18
|
+
self,
|
|
19
|
+
_: contextlib.AbstractContextManager[T_co] | contextlib.AbstractAsyncContextManager[T_co],
|
|
20
|
+
) -> typing.TypeGuard[contextlib.AbstractAsyncContextManager[T_co]]:
|
|
21
|
+
return self._is_async
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
scope: enum.IntEnum,
|
|
26
|
+
creator: typing.Callable[P, typing.Iterator[T_co] | typing.AsyncIterator[T_co]],
|
|
27
|
+
*args: P.args,
|
|
28
|
+
**kwargs: P.kwargs,
|
|
29
|
+
) -> None:
|
|
30
|
+
new_creator: typing.Any
|
|
31
|
+
if inspect.isasyncgenfunction(creator):
|
|
32
|
+
self._is_async = True
|
|
33
|
+
new_creator = contextlib.asynccontextmanager(creator)
|
|
34
|
+
elif inspect.isgeneratorfunction(creator):
|
|
35
|
+
self._is_async = False
|
|
36
|
+
new_creator = contextlib.contextmanager(creator)
|
|
37
|
+
else:
|
|
38
|
+
msg = "Unsupported resource type"
|
|
39
|
+
raise RuntimeError(msg)
|
|
40
|
+
|
|
41
|
+
super().__init__(scope, new_creator, *args, **kwargs)
|
|
42
|
+
|
|
43
|
+
async def async_resolve(self, container: Container) -> T_co:
|
|
44
|
+
container = container.find_container(self.scope)
|
|
45
|
+
if (override := container.fetch_override(self.resolver_id)) is not None:
|
|
46
|
+
return typing.cast(T_co, override)
|
|
47
|
+
|
|
48
|
+
resolver_state = container.fetch_resolver_state(
|
|
49
|
+
self.resolver_id, is_async_resource=self._is_async, is_lock_required=self._is_async
|
|
50
|
+
)
|
|
51
|
+
if resolver_state.instance is not None:
|
|
52
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
53
|
+
|
|
54
|
+
if resolver_state.resolver_lock:
|
|
55
|
+
await resolver_state.resolver_lock.acquire()
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
if resolver_state.instance is not None:
|
|
59
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
60
|
+
|
|
61
|
+
_intermediate_ = await self._async_build_creator(container)
|
|
62
|
+
|
|
63
|
+
if self._is_creator_async(self._creator): # type: ignore[arg-type]
|
|
64
|
+
resolver_state.context_stack = contextlib.AsyncExitStack()
|
|
65
|
+
resolver_state.instance = await resolver_state.context_stack.enter_async_context(_intermediate_)
|
|
66
|
+
else:
|
|
67
|
+
resolver_state.context_stack = contextlib.ExitStack()
|
|
68
|
+
resolver_state.instance = resolver_state.context_stack.enter_context(_intermediate_)
|
|
69
|
+
finally:
|
|
70
|
+
if resolver_state.resolver_lock:
|
|
71
|
+
resolver_state.resolver_lock.release()
|
|
72
|
+
|
|
73
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
74
|
+
|
|
75
|
+
def sync_resolve(self, container: Container) -> T_co:
|
|
76
|
+
container = container.find_container(self.scope)
|
|
77
|
+
if (override := container.fetch_override(self.resolver_id)) is not None:
|
|
78
|
+
return typing.cast(T_co, override)
|
|
79
|
+
|
|
80
|
+
resolver_state = container.fetch_resolver_state(self.resolver_id)
|
|
81
|
+
if resolver_state.instance is not None:
|
|
82
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
83
|
+
|
|
84
|
+
if self._is_async:
|
|
85
|
+
msg = "Async resource cannot be resolved synchronously"
|
|
86
|
+
raise RuntimeError(msg)
|
|
87
|
+
|
|
88
|
+
_intermediate_ = self._sync_build_creator(container)
|
|
89
|
+
|
|
90
|
+
resolver_state.context_stack = contextlib.ExitStack()
|
|
91
|
+
resolver_state.instance = resolver_state.context_stack.enter_context(
|
|
92
|
+
typing.cast(contextlib.AbstractContextManager[typing.Any], _intermediate_)
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
return typing.cast(T_co, resolver_state.instance)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "modern-di"
|
|
3
|
+
description = "Simple Dependency Injection framework"
|
|
4
|
+
authors = [
|
|
5
|
+
{ name = "Artur Shiriev", email = "me@shiriev.ru" },
|
|
6
|
+
]
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
requires-python = ">=3.10,<4"
|
|
9
|
+
license = "MIT"
|
|
10
|
+
keywords = ["di", "dependency injector", "ioc-container", "mocks", "python"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Programming Language :: Python :: 3.10",
|
|
13
|
+
"Programming Language :: Python :: 3.11",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Programming Language :: Python :: 3.13",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
"Topic :: Software Development :: Libraries",
|
|
18
|
+
]
|
|
19
|
+
dynamic = ["version"]
|
|
20
|
+
packages = [
|
|
21
|
+
{ include = "modern_di" },
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
repository = "https://github.com/modern-python/that-depends"
|
|
26
|
+
docs = "https://that-depends.readthedocs.io"
|
|
27
|
+
|
|
28
|
+
[dependency-groups]
|
|
29
|
+
dev = [
|
|
30
|
+
"pytest",
|
|
31
|
+
"pytest-cov",
|
|
32
|
+
"pytest-asyncio",
|
|
33
|
+
"ruff",
|
|
34
|
+
"mypy",
|
|
35
|
+
"typing-extensions",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[build-system]
|
|
39
|
+
requires = ["hatchling", "hatch-vcs"]
|
|
40
|
+
build-backend = "hatchling.build"
|
|
41
|
+
|
|
42
|
+
[tool.hatch.version]
|
|
43
|
+
source = "vcs"
|
|
44
|
+
|
|
45
|
+
[tool.mypy]
|
|
46
|
+
python_version = "3.10"
|
|
47
|
+
strict = true
|
|
48
|
+
|
|
49
|
+
[tool.ruff]
|
|
50
|
+
fix = true
|
|
51
|
+
unsafe-fixes = true
|
|
52
|
+
line-length = 120
|
|
53
|
+
target-version = "py310"
|
|
54
|
+
extend-exclude = [
|
|
55
|
+
"docs",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["ALL"]
|
|
60
|
+
ignore = [
|
|
61
|
+
"D1", # allow missing docstrings
|
|
62
|
+
"S101", # allow asserts
|
|
63
|
+
"TCH", # ignore flake8-type-checking
|
|
64
|
+
"FBT", # allow boolean args
|
|
65
|
+
"ANN101", # missing-type-self
|
|
66
|
+
"ANN102", # missing-type-cls
|
|
67
|
+
"D203", # "one-blank-line-before-class" conflicting with D211
|
|
68
|
+
"D213", # "multi-line-summary-second-line" conflicting with D212
|
|
69
|
+
"COM812", # flake8-commas "Trailing comma missing"
|
|
70
|
+
"ISC001", # flake8-implicit-str-concat
|
|
71
|
+
]
|
|
72
|
+
isort.lines-after-imports = 2
|
|
73
|
+
isort.no-lines-before = ["standard-library", "local-folder"]
|
|
74
|
+
|
|
75
|
+
[tool.pytest.ini_options]
|
|
76
|
+
addopts = "--cov=. --cov-report term-missing"
|
|
77
|
+
asyncio_mode = "auto"
|
|
78
|
+
|
|
79
|
+
[tool.coverage.report]
|
|
80
|
+
exclude_also = ["if typing.TYPE_CHECKING:"]
|
|
File without changes
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
import logging
|
|
3
|
+
import typing
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def create_async_resource() -> typing.AsyncIterator[datetime.datetime]:
|
|
10
|
+
logger.debug("Async resource initiated")
|
|
11
|
+
try:
|
|
12
|
+
yield datetime.datetime.now(tz=datetime.timezone.utc)
|
|
13
|
+
finally:
|
|
14
|
+
logger.debug("Async resource destructed")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def create_sync_resource() -> typing.Iterator[datetime.datetime]:
|
|
18
|
+
logger.debug("Resource initiated")
|
|
19
|
+
try:
|
|
20
|
+
yield datetime.datetime.now(tz=datetime.timezone.utc)
|
|
21
|
+
finally:
|
|
22
|
+
logger.debug("Resource destructed")
|
|
File without changes
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import dataclasses
|
|
3
|
+
import typing
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from modern_di import Container, Scope, resolvers
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclasses.dataclass(kw_only=True, slots=True)
|
|
11
|
+
class SimpleFactory:
|
|
12
|
+
dep1: str
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclasses.dataclass(kw_only=True, slots=True)
|
|
16
|
+
class RequestFactory:
|
|
17
|
+
dep1: SimpleFactory
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
singleton = resolvers.Factory(Scope.APP, SimpleFactory, dep1="original")
|
|
21
|
+
request_factory = resolvers.Factory(Scope.REQUEST, RequestFactory, dep1=singleton.cast)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def test_factory() -> None:
|
|
25
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
26
|
+
singleton1 = await singleton.async_resolve(app_container)
|
|
27
|
+
singleton2 = await singleton.async_resolve(app_container)
|
|
28
|
+
assert singleton1 is singleton2
|
|
29
|
+
|
|
30
|
+
with Container(scope=Scope.APP) as app_container:
|
|
31
|
+
singleton3 = singleton.sync_resolve(app_container)
|
|
32
|
+
singleton4 = singleton.sync_resolve(app_container)
|
|
33
|
+
assert singleton3 is singleton4
|
|
34
|
+
assert singleton3 is not singleton1
|
|
35
|
+
|
|
36
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
37
|
+
singleton5 = await singleton.async_resolve(app_container)
|
|
38
|
+
singleton6 = await singleton.async_resolve(app_container)
|
|
39
|
+
assert singleton5 is singleton6
|
|
40
|
+
assert singleton5 is not singleton3
|
|
41
|
+
assert singleton5 is not singleton1
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def test_factory_in_request_scope() -> None:
|
|
45
|
+
with Container(scope=Scope.APP) as app_container:
|
|
46
|
+
with app_container.build_child_container() as request_container:
|
|
47
|
+
instance1 = request_factory.sync_resolve(request_container)
|
|
48
|
+
instance2 = request_factory.sync_resolve(request_container)
|
|
49
|
+
assert instance1 is instance2
|
|
50
|
+
|
|
51
|
+
async with app_container.build_child_container() as request_container:
|
|
52
|
+
instance3 = await request_factory.async_resolve(request_container)
|
|
53
|
+
instance4 = await request_factory.async_resolve(request_container)
|
|
54
|
+
assert instance3 is instance4
|
|
55
|
+
|
|
56
|
+
assert instance1 is not instance3
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def test_app_scoped_factory_in_request_scope() -> None:
|
|
60
|
+
with Container(scope=Scope.APP) as app_container:
|
|
61
|
+
with app_container.build_child_container():
|
|
62
|
+
singleton1 = await singleton.async_resolve(app_container)
|
|
63
|
+
|
|
64
|
+
async with app_container.build_child_container():
|
|
65
|
+
singleton2 = await singleton.async_resolve(app_container)
|
|
66
|
+
|
|
67
|
+
assert singleton1 is singleton2
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def test_factory_overridden() -> None:
|
|
71
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
72
|
+
singleton1 = singleton.sync_resolve(app_container)
|
|
73
|
+
|
|
74
|
+
singleton.override(SimpleFactory(dep1="override"), container=app_container)
|
|
75
|
+
|
|
76
|
+
singleton2 = singleton.sync_resolve(app_container)
|
|
77
|
+
singleton3 = await singleton.async_resolve(app_container)
|
|
78
|
+
|
|
79
|
+
singleton.reset_override(app_container)
|
|
80
|
+
|
|
81
|
+
singleton4 = singleton.sync_resolve(app_container)
|
|
82
|
+
|
|
83
|
+
assert singleton2 is not singleton1
|
|
84
|
+
assert singleton2 is singleton3
|
|
85
|
+
assert singleton4 is singleton1
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def test_factory_race_condition() -> None:
|
|
89
|
+
calls: int = 0
|
|
90
|
+
|
|
91
|
+
async def create_resource() -> typing.AsyncIterator[str]:
|
|
92
|
+
nonlocal calls
|
|
93
|
+
calls += 1
|
|
94
|
+
await asyncio.sleep(0)
|
|
95
|
+
yield ""
|
|
96
|
+
|
|
97
|
+
resource = resolvers.Resource(Scope.APP, create_resource)
|
|
98
|
+
factory_with_resource = resolvers.Factory(Scope.APP, SimpleFactory, dep1=resource.cast)
|
|
99
|
+
|
|
100
|
+
async def resolve_factory(container: Container) -> SimpleFactory:
|
|
101
|
+
return await factory_with_resource.async_resolve(container)
|
|
102
|
+
|
|
103
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
104
|
+
client1, client2 = await asyncio.gather(resolve_factory(app_container), resolve_factory(app_container))
|
|
105
|
+
|
|
106
|
+
assert client1 == client2
|
|
107
|
+
assert calls == 1
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def test_factory_wrong_dependency_scope() -> None:
|
|
111
|
+
def some_factory(_: SimpleFactory) -> None: ...
|
|
112
|
+
|
|
113
|
+
request_factory = resolvers.Factory(Scope.REQUEST, SimpleFactory, dep1="original")
|
|
114
|
+
with pytest.raises(RuntimeError, match="Scope of dependency cannot be more than scope of dependent"):
|
|
115
|
+
resolvers.Factory(Scope.APP, some_factory, request_factory.cast)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import typing
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from modern_di import Container, Scope, resolvers
|
|
7
|
+
from tests.creators import create_async_resource, create_sync_resource
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async_resource = resolvers.Resource(Scope.APP, create_async_resource)
|
|
11
|
+
sync_resource = resolvers.Resource(Scope.APP, create_sync_resource)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def test_async_resource() -> None:
|
|
15
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
16
|
+
async_resource1 = await async_resource.async_resolve(app_container)
|
|
17
|
+
async_resource2 = await async_resource.async_resolve(app_container)
|
|
18
|
+
assert async_resource1 is async_resource2
|
|
19
|
+
|
|
20
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
21
|
+
async_resource3 = await async_resource.async_resolve(app_container)
|
|
22
|
+
async_resource4 = async_resource.sync_resolve(app_container)
|
|
23
|
+
assert async_resource3 is async_resource4
|
|
24
|
+
assert async_resource3 is not async_resource1
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def test_async_resource_in_sync_container() -> None:
|
|
28
|
+
with (
|
|
29
|
+
Container(scope=Scope.APP) as app_container,
|
|
30
|
+
pytest.raises(RuntimeError, match="Resolving async resource in sync container is not allowed"),
|
|
31
|
+
):
|
|
32
|
+
await async_resource.async_resolve(app_container)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def test_async_resource_calling_sync_exit() -> None:
|
|
36
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
37
|
+
await async_resource.async_resolve(app_container)
|
|
38
|
+
with pytest.raises(RuntimeError, match="Cannot tear down async context in `sync_tear_down`"):
|
|
39
|
+
app_container.__exit__(None, None, None)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def test_sync_resource() -> None:
|
|
43
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
44
|
+
sync_resource1 = await sync_resource.async_resolve(app_container)
|
|
45
|
+
sync_resource2 = await sync_resource.async_resolve(app_container)
|
|
46
|
+
assert sync_resource1 is sync_resource2
|
|
47
|
+
|
|
48
|
+
with Container(scope=Scope.APP) as app_container:
|
|
49
|
+
sync_resource3 = sync_resource.sync_resolve(app_container)
|
|
50
|
+
sync_resource4 = sync_resource.sync_resolve(app_container)
|
|
51
|
+
assert sync_resource3 is sync_resource4
|
|
52
|
+
assert sync_resource3 is not sync_resource1
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def test_async_resource_overridden() -> None:
|
|
56
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
57
|
+
async_resource1 = await async_resource.async_resolve(app_container)
|
|
58
|
+
|
|
59
|
+
async_resource.override("override", container=app_container)
|
|
60
|
+
|
|
61
|
+
async_resource2 = async_resource.sync_resolve(app_container)
|
|
62
|
+
async_resource3 = await async_resource.async_resolve(app_container)
|
|
63
|
+
|
|
64
|
+
app_container.reset_override()
|
|
65
|
+
|
|
66
|
+
async_resource4 = async_resource.sync_resolve(app_container)
|
|
67
|
+
|
|
68
|
+
assert async_resource2 is not async_resource1
|
|
69
|
+
assert async_resource2 is async_resource3
|
|
70
|
+
assert async_resource4 is async_resource1
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def test_sync_resource_overridden() -> None:
|
|
74
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
75
|
+
sync_resource1 = await sync_resource.async_resolve(app_container)
|
|
76
|
+
|
|
77
|
+
sync_resource.override("override", container=app_container)
|
|
78
|
+
|
|
79
|
+
sync_resource2 = sync_resource.sync_resolve(app_container)
|
|
80
|
+
sync_resource3 = await sync_resource.async_resolve(app_container)
|
|
81
|
+
|
|
82
|
+
app_container.reset_override()
|
|
83
|
+
|
|
84
|
+
sync_resource4 = sync_resource.sync_resolve(app_container)
|
|
85
|
+
|
|
86
|
+
assert sync_resource2 is not sync_resource1
|
|
87
|
+
assert sync_resource2 is sync_resource3
|
|
88
|
+
assert sync_resource4 is sync_resource1
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def test_async_resource_race_condition() -> None:
|
|
92
|
+
calls: int = 0
|
|
93
|
+
|
|
94
|
+
async def create_resource() -> typing.AsyncIterator[str]:
|
|
95
|
+
nonlocal calls
|
|
96
|
+
calls += 1
|
|
97
|
+
await asyncio.sleep(0)
|
|
98
|
+
yield ""
|
|
99
|
+
|
|
100
|
+
resource = resolvers.Resource(Scope.APP, create_resource)
|
|
101
|
+
|
|
102
|
+
async def resolve_resource(container: Container) -> str:
|
|
103
|
+
return await resource.async_resolve(container)
|
|
104
|
+
|
|
105
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
106
|
+
await asyncio.gather(resolve_resource(app_container), resolve_resource(app_container))
|
|
107
|
+
|
|
108
|
+
assert calls == 1
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
async def test_resource_unsupported_creator() -> None:
|
|
112
|
+
with pytest.raises(RuntimeError, match="Unsupported resource type"):
|
|
113
|
+
resolvers.Resource(Scope.APP, None) # type: ignore[arg-type]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def test_async_resource_sync_resolve() -> None:
|
|
117
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
118
|
+
with pytest.raises(RuntimeError, match="Async resource cannot be resolved synchronously"):
|
|
119
|
+
async_resource.sync_resolve(app_container)
|
|
@@ -0,0 +1,41 @@
|
|
|
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_resolver_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()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from modern_di import BaseGraph, Container, Scope, resolvers
|
|
4
|
+
from tests.creators import create_async_resource, create_sync_resource
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
async_resource = resolvers.Resource(Scope.APP, create_async_resource)
|
|
8
|
+
sync_resource = resolvers.Resource(Scope.APP, create_sync_resource)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def test_graph_async_resolve_creators() -> None:
|
|
12
|
+
class DIGraph(BaseGraph):
|
|
13
|
+
async_resource = async_resource
|
|
14
|
+
sync_resource = sync_resource
|
|
15
|
+
|
|
16
|
+
async with Container(scope=Scope.APP) as app_container:
|
|
17
|
+
await DIGraph.async_resolve_creators(app_container)
|
|
18
|
+
|
|
19
|
+
assert len(app_container._resolver_states) == 2 # noqa: SLF001, PLR2004
|
|
20
|
+
assert len(app_container._resolver_states) == 0 # noqa: SLF001
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_graph_sync_resolve_creators() -> None:
|
|
24
|
+
class DIGraph(BaseGraph):
|
|
25
|
+
sync_resource = sync_resource
|
|
26
|
+
|
|
27
|
+
with Container(scope=Scope.APP) as app_container:
|
|
28
|
+
DIGraph.sync_resolve_creators(app_container)
|
|
29
|
+
|
|
30
|
+
assert len(app_container._resolver_states) == 1 # noqa: SLF001
|
|
31
|
+
assert len(app_container._resolver_states) == 0 # noqa: SLF001
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_graph_cannot_be_instantiated() -> None:
|
|
35
|
+
class DIGraph(BaseGraph):
|
|
36
|
+
sync_resource = sync_resource
|
|
37
|
+
|
|
38
|
+
with pytest.raises(RuntimeError, match="DIGraph cannot not be instantiated"):
|
|
39
|
+
DIGraph()
|