anydi 0.55.1__py3-none-any.whl → 0.57.0__py3-none-any.whl
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.
- anydi/__init__.py +4 -2
- anydi/_container.py +67 -110
- anydi/_injector.py +132 -0
- anydi/_resolver.py +225 -122
- anydi/_scanner.py +52 -44
- anydi/_types.py +48 -7
- anydi/ext/fastapi.py +31 -33
- anydi/ext/faststream.py +25 -31
- anydi/ext/pydantic_settings.py +2 -1
- anydi/ext/pytest_plugin.py +380 -50
- anydi/testing.py +34 -113
- anydi-0.57.0.dist-info/METADATA +266 -0
- anydi-0.57.0.dist-info/RECORD +25 -0
- anydi-0.55.1.dist-info/METADATA +0 -193
- anydi-0.55.1.dist-info/RECORD +0 -24
- {anydi-0.55.1.dist-info → anydi-0.57.0.dist-info}/WHEEL +0 -0
- {anydi-0.55.1.dist-info → anydi-0.57.0.dist-info}/entry_points.txt +0 -0
anydi/ext/pytest_plugin.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import importlib.util
|
|
3
4
|
import inspect
|
|
4
5
|
import logging
|
|
5
6
|
from collections.abc import Callable, Iterator
|
|
@@ -9,47 +10,199 @@ import pytest
|
|
|
9
10
|
from anyio.pytest_plugin import extract_backend_and_options, get_runner
|
|
10
11
|
from typing_extensions import get_annotations
|
|
11
12
|
|
|
12
|
-
from anydi import Container
|
|
13
|
+
from anydi import Container, import_container
|
|
13
14
|
|
|
14
15
|
logger = logging.getLogger(__name__)
|
|
15
16
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
config.addinivalue_line(
|
|
19
|
-
"markers",
|
|
20
|
-
"inject: mark test as needing dependency injection",
|
|
21
|
-
)
|
|
17
|
+
# Storage for fixtures with inject markers
|
|
18
|
+
_INJECTED_FIXTURES: dict[str, dict[str, Any]] = {}
|
|
22
19
|
|
|
23
20
|
|
|
24
21
|
def pytest_addoption(parser: pytest.Parser) -> None:
|
|
22
|
+
parser.addini(
|
|
23
|
+
"anydi_autoinject",
|
|
24
|
+
help="Automatically inject dependencies into all test functions",
|
|
25
|
+
type="bool",
|
|
26
|
+
default=False,
|
|
27
|
+
)
|
|
25
28
|
parser.addini(
|
|
26
29
|
"anydi_inject_all",
|
|
27
|
-
help="
|
|
30
|
+
help="Deprecated: use 'anydi_autoinject' instead",
|
|
31
|
+
type="bool",
|
|
32
|
+
default=False,
|
|
33
|
+
)
|
|
34
|
+
parser.addini(
|
|
35
|
+
"anydi_container",
|
|
36
|
+
help=(
|
|
37
|
+
"Path to container instance or factory "
|
|
38
|
+
"(e.g., 'myapp.container:container' or 'myapp.container.container')"
|
|
39
|
+
),
|
|
40
|
+
type="string",
|
|
41
|
+
default=None,
|
|
42
|
+
)
|
|
43
|
+
parser.addini(
|
|
44
|
+
"anydi_fixture_inject_enabled",
|
|
45
|
+
help=(
|
|
46
|
+
"Enable dependency injection into fixtures marked with @pytest.mark.inject"
|
|
47
|
+
),
|
|
28
48
|
type="bool",
|
|
29
49
|
default=False,
|
|
30
50
|
)
|
|
31
51
|
|
|
32
52
|
|
|
33
|
-
|
|
53
|
+
def pytest_configure(config: pytest.Config) -> None:
|
|
54
|
+
config.addinivalue_line(
|
|
55
|
+
"markers",
|
|
56
|
+
"inject: mark test as needing dependency injection",
|
|
57
|
+
)
|
|
34
58
|
|
|
59
|
+
# Enable fixture injection if configured
|
|
60
|
+
inject_fixtures_enabled = cast(bool, config.getini("anydi_fixture_inject_enabled"))
|
|
61
|
+
if inject_fixtures_enabled:
|
|
62
|
+
autoinject = cast(bool, config.getini("anydi_autoinject"))
|
|
63
|
+
inject_all = cast(bool, config.getini("anydi_inject_all"))
|
|
64
|
+
_patch_pytest_fixtures(autoinject=autoinject or inject_all)
|
|
65
|
+
logger.debug(
|
|
66
|
+
"Fixture injection enabled via anydi_fixture_inject_enabled config"
|
|
67
|
+
)
|
|
35
68
|
|
|
36
|
-
|
|
37
|
-
|
|
69
|
+
|
|
70
|
+
@pytest.hookimpl(hookwrapper=True)
|
|
71
|
+
def pytest_fixture_setup( # noqa: C901
|
|
72
|
+
fixturedef: pytest.FixtureDef[Any],
|
|
73
|
+
request: pytest.FixtureRequest,
|
|
74
|
+
) -> Iterator[None]:
|
|
75
|
+
"""Inject dependencies into fixtures marked with @pytest.mark.inject."""
|
|
76
|
+
# Check if this fixture has injection metadata
|
|
77
|
+
fixture_name = fixturedef.argname
|
|
78
|
+
if fixture_name not in _INJECTED_FIXTURES:
|
|
79
|
+
yield
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
# Get the metadata
|
|
83
|
+
fixture_info = _INJECTED_FIXTURES[fixture_name]
|
|
84
|
+
original_func = fixture_info["func"]
|
|
85
|
+
parameters: list[tuple[str, Any]] = fixture_info["parameters"]
|
|
86
|
+
|
|
87
|
+
# Get the container
|
|
38
88
|
try:
|
|
39
|
-
|
|
40
|
-
except pytest.FixtureLookupError
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
89
|
+
container = cast(Container, request.getfixturevalue("container"))
|
|
90
|
+
except pytest.FixtureLookupError:
|
|
91
|
+
yield
|
|
92
|
+
return
|
|
93
|
+
|
|
94
|
+
resolvable_params = _select_resolvable_parameters(container, parameters)
|
|
95
|
+
|
|
96
|
+
if not resolvable_params:
|
|
97
|
+
yield
|
|
98
|
+
return
|
|
99
|
+
|
|
100
|
+
target_name = f"fixture '{fixture_name}'"
|
|
101
|
+
|
|
102
|
+
def _prepare_sync_call_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
103
|
+
combined_kwargs = dict(kwargs)
|
|
104
|
+
combined_kwargs.update(
|
|
105
|
+
_resolve_dependencies_sync(container, resolvable_params, target=target_name)
|
|
44
106
|
)
|
|
45
|
-
|
|
107
|
+
return combined_kwargs
|
|
108
|
+
|
|
109
|
+
async def _prepare_async_call_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
110
|
+
combined_kwargs = dict(kwargs)
|
|
111
|
+
combined_kwargs.update(
|
|
112
|
+
await _resolve_dependencies_async(
|
|
113
|
+
container, resolvable_params, target=target_name
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
return combined_kwargs
|
|
117
|
+
|
|
118
|
+
def _ensure_anyio_backend() -> tuple[str, dict[str, Any]]:
|
|
119
|
+
try:
|
|
120
|
+
backend = request.getfixturevalue("anyio_backend")
|
|
121
|
+
except pytest.FixtureLookupError as exc: # pragma: no cover - defensive
|
|
122
|
+
msg = (
|
|
123
|
+
"To run async fixtures with AnyDI, please configure the `anyio` pytest "
|
|
124
|
+
"plugin (provide the `anyio_backend` fixture)."
|
|
125
|
+
)
|
|
126
|
+
pytest.fail(msg, pytrace=False)
|
|
127
|
+
raise RuntimeError from exc # Unreachable but satisfies type checkers
|
|
128
|
+
|
|
129
|
+
return extract_backend_and_options(backend)
|
|
130
|
+
|
|
131
|
+
# Replace the fixture function with one that mirrors the original's type and
|
|
132
|
+
# injects dependencies before delegating to the user-defined function.
|
|
133
|
+
original_fixture_func = fixturedef.func
|
|
134
|
+
|
|
135
|
+
if inspect.isasyncgenfunction(original_func):
|
|
136
|
+
|
|
137
|
+
def asyncgen_wrapper(*args: Any, **kwargs: Any) -> Iterator[Any]:
|
|
138
|
+
backend_name, backend_options = _ensure_anyio_backend()
|
|
139
|
+
|
|
140
|
+
async def _fixture() -> Any:
|
|
141
|
+
call_kwargs = await _prepare_async_call_kwargs(kwargs)
|
|
142
|
+
async for value in original_func(**call_kwargs):
|
|
143
|
+
yield value
|
|
144
|
+
|
|
145
|
+
with get_runner(backend_name, backend_options) as runner:
|
|
146
|
+
yield from runner.run_asyncgen_fixture(_fixture, {}) # type: ignore
|
|
147
|
+
|
|
148
|
+
fixturedef.func = asyncgen_wrapper # type: ignore[misc]
|
|
149
|
+
elif inspect.iscoroutinefunction(original_func):
|
|
150
|
+
|
|
151
|
+
def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
152
|
+
backend_name, backend_options = _ensure_anyio_backend()
|
|
153
|
+
|
|
154
|
+
async def _fixture() -> Any:
|
|
155
|
+
call_kwargs = await _prepare_async_call_kwargs(kwargs)
|
|
156
|
+
return await original_func(**call_kwargs)
|
|
157
|
+
|
|
158
|
+
with get_runner(backend_name, backend_options) as runner:
|
|
159
|
+
return runner.run_fixture(_fixture, {})
|
|
160
|
+
|
|
161
|
+
fixturedef.func = async_wrapper # type: ignore[misc]
|
|
162
|
+
elif inspect.isgeneratorfunction(original_func):
|
|
163
|
+
|
|
164
|
+
def generator_wrapper(*args: Any, **kwargs: Any) -> Iterator[Any]:
|
|
165
|
+
call_kwargs = _prepare_sync_call_kwargs(kwargs)
|
|
166
|
+
yield from original_func(**call_kwargs)
|
|
167
|
+
|
|
168
|
+
fixturedef.func = generator_wrapper # type: ignore[misc]
|
|
169
|
+
else:
|
|
170
|
+
|
|
171
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
172
|
+
call_kwargs = _prepare_sync_call_kwargs(kwargs)
|
|
173
|
+
return original_func(**call_kwargs)
|
|
174
|
+
|
|
175
|
+
fixturedef.func = sync_wrapper # type: ignore[misc]
|
|
176
|
+
|
|
177
|
+
# Let pytest execute the modified fixture
|
|
178
|
+
yield
|
|
179
|
+
|
|
180
|
+
# Restore the original function
|
|
181
|
+
fixturedef.func = original_fixture_func # type: ignore[misc]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@pytest.fixture(scope="session")
|
|
185
|
+
def container(request: pytest.FixtureRequest) -> Container:
|
|
186
|
+
"""Container fixture."""
|
|
187
|
+
return _find_container(request)
|
|
46
188
|
|
|
47
189
|
|
|
48
190
|
@pytest.fixture
|
|
49
191
|
def _anydi_should_inject(request: pytest.FixtureRequest) -> bool:
|
|
50
192
|
marker = request.node.get_closest_marker("inject")
|
|
193
|
+
|
|
194
|
+
# Check new config option first
|
|
195
|
+
autoinject = cast(bool, request.config.getini("anydi_autoinject"))
|
|
196
|
+
|
|
197
|
+
# Check deprecated option for backward compatibility
|
|
51
198
|
inject_all = cast(bool, request.config.getini("anydi_inject_all"))
|
|
52
|
-
|
|
199
|
+
if inject_all:
|
|
200
|
+
logger.warning(
|
|
201
|
+
"Configuration option 'anydi_inject_all' is deprecated. "
|
|
202
|
+
"Please use 'anydi_autoinject' instead."
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
return marker is not None or autoinject or inject_all
|
|
53
206
|
|
|
54
207
|
|
|
55
208
|
@pytest.fixture
|
|
@@ -60,12 +213,8 @@ def _anydi_injected_parameter_iterator(
|
|
|
60
213
|
request.node._fixtureinfo.name2fixturedefs.keys()
|
|
61
214
|
)
|
|
62
215
|
|
|
63
|
-
def _iterator() -> Iterator[tuple[str,
|
|
64
|
-
for name, annotation in
|
|
65
|
-
request.function, eval_str=True
|
|
66
|
-
).items():
|
|
67
|
-
if name == "return":
|
|
68
|
-
continue
|
|
216
|
+
def _iterator() -> Iterator[tuple[str, Any]]:
|
|
217
|
+
for name, annotation in _iter_injectable_parameters(request.function):
|
|
69
218
|
if name not in fixturenames:
|
|
70
219
|
continue
|
|
71
220
|
yield name, annotation
|
|
@@ -84,20 +233,20 @@ def _anydi_inject(
|
|
|
84
233
|
if inspect.iscoroutinefunction(request.function) or not _anydi_should_inject:
|
|
85
234
|
return
|
|
86
235
|
|
|
87
|
-
|
|
88
|
-
|
|
236
|
+
parameters = list(_anydi_injected_parameter_iterator())
|
|
237
|
+
if not parameters:
|
|
238
|
+
return
|
|
89
239
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
240
|
+
container = cast(Container, request.getfixturevalue("container"))
|
|
241
|
+
resolvable = _select_resolvable_parameters(container, parameters)
|
|
242
|
+
if not resolvable:
|
|
243
|
+
return
|
|
94
244
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
)
|
|
245
|
+
resolved = _resolve_dependencies_sync(
|
|
246
|
+
container, resolvable, target=request.node.nodeid
|
|
247
|
+
)
|
|
248
|
+
for argname, value in resolved.items():
|
|
249
|
+
request.node.funcargs[argname] = value
|
|
101
250
|
|
|
102
251
|
|
|
103
252
|
@pytest.fixture(autouse=True)
|
|
@@ -123,25 +272,206 @@ def _anydi_ainject(
|
|
|
123
272
|
)
|
|
124
273
|
pytest.fail(msg, pytrace=False)
|
|
125
274
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
275
|
+
parameters = list(_anydi_injected_parameter_iterator())
|
|
276
|
+
if not parameters:
|
|
277
|
+
return
|
|
129
278
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
279
|
+
container = cast(Container, request.getfixturevalue("container"))
|
|
280
|
+
resolvable = _select_resolvable_parameters(container, parameters)
|
|
281
|
+
if not resolvable:
|
|
282
|
+
return
|
|
134
283
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
)
|
|
284
|
+
async def _awrapper() -> None:
|
|
285
|
+
resolved = await _resolve_dependencies_async(
|
|
286
|
+
container, resolvable, target=request.node.nodeid
|
|
287
|
+
)
|
|
288
|
+
for argname, value in resolved.items():
|
|
289
|
+
request.node.funcargs[argname] = value
|
|
142
290
|
|
|
143
291
|
anyio_backend = request.getfixturevalue("anyio_backend")
|
|
144
292
|
backend_name, backend_options = extract_backend_and_options(anyio_backend)
|
|
145
293
|
|
|
146
294
|
with get_runner(backend_name, backend_options) as runner:
|
|
147
295
|
runner.run_fixture(_awrapper, {})
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _find_container(request: pytest.FixtureRequest) -> Container:
|
|
299
|
+
"""Find container."""
|
|
300
|
+
|
|
301
|
+
# Look for 'anydi_container' defined in pytest.ini (highest priority)
|
|
302
|
+
container_path = cast(str | None, request.config.getini("anydi_container"))
|
|
303
|
+
if container_path:
|
|
304
|
+
try:
|
|
305
|
+
return import_container(container_path)
|
|
306
|
+
except ImportError as exc:
|
|
307
|
+
raise RuntimeError(
|
|
308
|
+
f"Failed to load container from config "
|
|
309
|
+
f"'anydi_container={container_path}': {exc}"
|
|
310
|
+
) from exc
|
|
311
|
+
|
|
312
|
+
# Detect pytest-django + anydi_django availability
|
|
313
|
+
pluginmanager = request.config.pluginmanager
|
|
314
|
+
if pluginmanager.hasplugin("django") and importlib.util.find_spec("anydi_django"):
|
|
315
|
+
return import_container("anydi_django.container")
|
|
316
|
+
|
|
317
|
+
# Neither fixture nor config found
|
|
318
|
+
raise pytest.FixtureLookupError(
|
|
319
|
+
None,
|
|
320
|
+
request,
|
|
321
|
+
"`container` fixture is not found and 'anydi_container' config is not set. "
|
|
322
|
+
"Either define a `container` fixture in your test module "
|
|
323
|
+
"or set 'anydi_container' in pytest.ini.",
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _patch_pytest_fixtures(*, autoinject: bool) -> None: # noqa: C901
|
|
328
|
+
"""Patch pytest.fixture decorator to intercept fixtures with inject markers."""
|
|
329
|
+
from _pytest.fixtures import fixture as original_fixture_decorator
|
|
330
|
+
|
|
331
|
+
def patched_fixture(*args: Any, **kwargs: Any) -> Any: # noqa: C901
|
|
332
|
+
"""Patched fixture decorator that handles inject markers."""
|
|
333
|
+
|
|
334
|
+
def should_process(func: Callable[..., Any]) -> bool:
|
|
335
|
+
has_inject_marker = False
|
|
336
|
+
if hasattr(func, "pytestmark"):
|
|
337
|
+
markers = getattr(func, "pytestmark", [])
|
|
338
|
+
if not isinstance(markers, list):
|
|
339
|
+
markers = [markers]
|
|
340
|
+
|
|
341
|
+
has_inject_marker = any(
|
|
342
|
+
marker.name == "inject"
|
|
343
|
+
for marker in markers
|
|
344
|
+
if hasattr(marker, "name")
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
return autoinject or has_inject_marker
|
|
348
|
+
|
|
349
|
+
def register_fixture(func: Callable[..., Any]) -> Callable[..., Any] | None:
|
|
350
|
+
if not should_process(func):
|
|
351
|
+
return None
|
|
352
|
+
|
|
353
|
+
parameters = list(_iter_injectable_parameters(func))
|
|
354
|
+
if not parameters:
|
|
355
|
+
return None
|
|
356
|
+
|
|
357
|
+
sig = inspect.signature(func, eval_str=True)
|
|
358
|
+
has_request_param = "request" in sig.parameters
|
|
359
|
+
|
|
360
|
+
if has_request_param:
|
|
361
|
+
|
|
362
|
+
def wrapper_with_request(request: Any) -> Any:
|
|
363
|
+
return func
|
|
364
|
+
|
|
365
|
+
wrapper_func = wrapper_with_request
|
|
366
|
+
else:
|
|
367
|
+
|
|
368
|
+
def wrapper_no_request() -> Any:
|
|
369
|
+
return func
|
|
370
|
+
|
|
371
|
+
wrapper_func = wrapper_no_request
|
|
372
|
+
|
|
373
|
+
wrapper_func.__name__ = func.__name__
|
|
374
|
+
wrapper_func.__annotations__ = {}
|
|
375
|
+
|
|
376
|
+
fixture_name = func.__name__
|
|
377
|
+
_INJECTED_FIXTURES[fixture_name] = {
|
|
378
|
+
"func": func,
|
|
379
|
+
"parameters": parameters,
|
|
380
|
+
}
|
|
381
|
+
logger.debug(
|
|
382
|
+
"Registered injectable fixture '%s' with params: %s",
|
|
383
|
+
fixture_name,
|
|
384
|
+
[name for name, _ in parameters],
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
return wrapper_func
|
|
388
|
+
|
|
389
|
+
# Handle both @pytest.fixture and @pytest.fixture() usage
|
|
390
|
+
if len(args) == 1 and callable(args[0]) and not kwargs:
|
|
391
|
+
func = args[0]
|
|
392
|
+
wrapper_func = register_fixture(func)
|
|
393
|
+
if wrapper_func:
|
|
394
|
+
return original_fixture_decorator(wrapper_func)
|
|
395
|
+
|
|
396
|
+
return original_fixture_decorator(func)
|
|
397
|
+
else:
|
|
398
|
+
|
|
399
|
+
def decorator(func: Callable[..., Any]) -> Any:
|
|
400
|
+
wrapper_func = register_fixture(func)
|
|
401
|
+
if wrapper_func:
|
|
402
|
+
return original_fixture_decorator(*args, **kwargs)(wrapper_func)
|
|
403
|
+
|
|
404
|
+
return original_fixture_decorator(*args, **kwargs)(func)
|
|
405
|
+
|
|
406
|
+
return decorator
|
|
407
|
+
|
|
408
|
+
# Replace pytest.fixture
|
|
409
|
+
pytest.fixture = patched_fixture # type: ignore[assignment]
|
|
410
|
+
# Also patch _pytest.fixtures.fixture
|
|
411
|
+
import _pytest.fixtures
|
|
412
|
+
|
|
413
|
+
_pytest.fixtures.fixture = patched_fixture # type: ignore[assignment]
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _iter_injectable_parameters(
|
|
417
|
+
func: Callable[..., Any], *, skip: tuple[str, ...] = ("request",)
|
|
418
|
+
) -> Iterator[tuple[str, Any]]:
|
|
419
|
+
annotations = get_annotations(func, eval_str=True)
|
|
420
|
+
skip_names = set(skip)
|
|
421
|
+
for name, annotation in annotations.items():
|
|
422
|
+
if name in skip_names or name == "return":
|
|
423
|
+
continue
|
|
424
|
+
yield name, annotation
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _select_resolvable_parameters(
|
|
428
|
+
container: Container,
|
|
429
|
+
parameters: Iterator[tuple[str, Any]] | list[tuple[str, Any]],
|
|
430
|
+
) -> list[tuple[str, Any]]:
|
|
431
|
+
return [
|
|
432
|
+
(name, annotation)
|
|
433
|
+
for name, annotation in parameters
|
|
434
|
+
if container.has_provider_for(annotation)
|
|
435
|
+
]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _resolve_dependencies_sync(
|
|
439
|
+
container: Container,
|
|
440
|
+
parameters: list[tuple[str, Any]],
|
|
441
|
+
*,
|
|
442
|
+
target: str,
|
|
443
|
+
) -> dict[str, Any]:
|
|
444
|
+
resolved: dict[str, Any] = {}
|
|
445
|
+
for param_name, annotation in parameters:
|
|
446
|
+
try:
|
|
447
|
+
resolved[param_name] = container.resolve(annotation)
|
|
448
|
+
logger.debug("Resolved %s=%s for %s", param_name, annotation, target)
|
|
449
|
+
except Exception as exc: # pragma: no cover - defensive logging
|
|
450
|
+
logger.warning(
|
|
451
|
+
"Failed to resolve dependency for '%s' on %s.",
|
|
452
|
+
param_name,
|
|
453
|
+
target,
|
|
454
|
+
exc_info=exc,
|
|
455
|
+
)
|
|
456
|
+
return resolved
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
async def _resolve_dependencies_async(
|
|
460
|
+
container: Container,
|
|
461
|
+
parameters: list[tuple[str, Any]],
|
|
462
|
+
*,
|
|
463
|
+
target: str,
|
|
464
|
+
) -> dict[str, Any]:
|
|
465
|
+
resolved: dict[str, Any] = {}
|
|
466
|
+
for param_name, annotation in parameters:
|
|
467
|
+
try:
|
|
468
|
+
resolved[param_name] = await container.aresolve(annotation)
|
|
469
|
+
logger.debug("Resolved %s=%s for async %s", param_name, annotation, target)
|
|
470
|
+
except Exception as exc: # pragma: no cover - defensive logging
|
|
471
|
+
logger.warning(
|
|
472
|
+
"Failed to resolve async dependency for '%s' on %s.",
|
|
473
|
+
param_name,
|
|
474
|
+
target,
|
|
475
|
+
exc_info=exc,
|
|
476
|
+
)
|
|
477
|
+
return resolved
|
anydi/testing.py
CHANGED
|
@@ -1,125 +1,46 @@
|
|
|
1
|
-
|
|
2
|
-
import logging
|
|
3
|
-
from collections.abc import Iterable, Iterator, Sequence
|
|
4
|
-
from typing import Any
|
|
1
|
+
"""Testing utilities for AnyDI.
|
|
5
2
|
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
.. deprecated:: 0.56.0
|
|
4
|
+
TestContainer is deprecated. Use Container with override() instead.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import warnings
|
|
8
10
|
|
|
9
11
|
from ._container import Container
|
|
10
|
-
from ._module import ModuleDef
|
|
11
|
-
from ._provider import ProviderDef
|
|
12
|
-
from ._types import NOT_SET
|
|
13
12
|
|
|
14
13
|
|
|
15
14
|
class TestContainer(Container):
|
|
15
|
+
"""Test container for dependency injection.
|
|
16
|
+
|
|
17
|
+
.. deprecated:: 0.56.0
|
|
18
|
+
TestContainer is deprecated and will be removed in a future version.
|
|
19
|
+
Use regular Container with override() method instead.
|
|
20
|
+
"""
|
|
21
|
+
|
|
16
22
|
__test__ = False
|
|
17
23
|
|
|
18
|
-
def __init__(
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
super().__init__(
|
|
26
|
-
self._override_instances: dict[Any, Any] = {}
|
|
27
|
-
self._revisions: dict[Any, int] = {}
|
|
24
|
+
def __init__(self, *args, **kwargs): # type: ignore
|
|
25
|
+
warnings.warn(
|
|
26
|
+
"TestContainer is deprecated and will be removed in a future version. "
|
|
27
|
+
"Use regular Container with override() method instead.",
|
|
28
|
+
DeprecationWarning,
|
|
29
|
+
stacklevel=2,
|
|
30
|
+
)
|
|
31
|
+
super().__init__(*args, **kwargs)
|
|
28
32
|
|
|
29
33
|
@classmethod
|
|
30
|
-
def from_container(cls, container: Container) ->
|
|
31
|
-
|
|
32
|
-
providers=[
|
|
33
|
-
ProviderDef(
|
|
34
|
-
interface=provider.interface,
|
|
35
|
-
call=provider.call,
|
|
36
|
-
scope=provider.scope,
|
|
37
|
-
)
|
|
38
|
-
for provider in container.providers.values()
|
|
39
|
-
],
|
|
40
|
-
logger=container.logger,
|
|
41
|
-
)
|
|
34
|
+
def from_container(cls, container: Container) -> Container:
|
|
35
|
+
"""Create a test container from an existing container.
|
|
42
36
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
"""
|
|
46
|
-
Override the provider for the specified interface with a specific instance.
|
|
37
|
+
.. deprecated:: 0.56.0
|
|
38
|
+
This method is deprecated. Just use the container directly.
|
|
47
39
|
"""
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
yield
|
|
56
|
-
finally:
|
|
57
|
-
self._override_instances.pop(interface, None)
|
|
58
|
-
self._touch_revision(interface)
|
|
59
|
-
|
|
60
|
-
def _touch_revision(self, interface: Any) -> None:
|
|
61
|
-
self._revisions[interface] = self._revisions.get(interface, 0) + 1
|
|
62
|
-
|
|
63
|
-
def _hook_override_for(self, interface: Any) -> Any:
|
|
64
|
-
return self._override_instances.get(interface, NOT_SET)
|
|
65
|
-
|
|
66
|
-
def _hook_wrap_dependency(self, annotation: Any, value: Any) -> Any:
|
|
67
|
-
return InstanceProxy(value, interface=annotation)
|
|
68
|
-
|
|
69
|
-
def _hook_post_resolve(self, interface: Any, instance: Any) -> Any: # noqa: C901
|
|
70
|
-
"""Patch the test resolver for the instance."""
|
|
71
|
-
if interface in self._override_instances:
|
|
72
|
-
return self._override_instances[interface]
|
|
73
|
-
|
|
74
|
-
if not hasattr(instance, "__dict__") or hasattr(
|
|
75
|
-
instance, "__resolver_getter__"
|
|
76
|
-
):
|
|
77
|
-
return instance
|
|
78
|
-
|
|
79
|
-
wrapped = {
|
|
80
|
-
name: value.interface
|
|
81
|
-
for name, value in instance.__dict__.items()
|
|
82
|
-
if isinstance(value, InstanceProxy)
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
def __resolver_getter__(name: str) -> Any:
|
|
86
|
-
if name in wrapped:
|
|
87
|
-
_interface = wrapped[name]
|
|
88
|
-
# Resolve the dependency if it's wrapped
|
|
89
|
-
return self.resolve(_interface)
|
|
90
|
-
raise LookupError
|
|
91
|
-
|
|
92
|
-
# Attach the resolver getter to the instance
|
|
93
|
-
instance.__resolver_getter__ = __resolver_getter__
|
|
94
|
-
|
|
95
|
-
if not hasattr(instance.__class__, "__getattribute_patched__"):
|
|
96
|
-
|
|
97
|
-
def __getattribute__(_self: Any, name: str) -> Any:
|
|
98
|
-
# Skip the resolver getter
|
|
99
|
-
if name in {"__resolver_getter__", "__class__"}:
|
|
100
|
-
return object.__getattribute__(_self, name)
|
|
101
|
-
|
|
102
|
-
if hasattr(_self, "__resolver_getter__"):
|
|
103
|
-
try:
|
|
104
|
-
return _self.__resolver_getter__(name)
|
|
105
|
-
except LookupError:
|
|
106
|
-
pass
|
|
107
|
-
|
|
108
|
-
# Fall back to default behavior
|
|
109
|
-
return object.__getattribute__(_self, name)
|
|
110
|
-
|
|
111
|
-
# Apply the patched resolver if wrapped attributes exist
|
|
112
|
-
instance.__class__.__getattribute__ = __getattribute__
|
|
113
|
-
instance.__class__.__getattribute_patched__ = True
|
|
114
|
-
|
|
115
|
-
return instance
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
class InstanceProxy(wrapt.ObjectProxy): # type: ignore
|
|
119
|
-
def __init__(self, wrapped: Any, *, interface: type[Any]) -> None:
|
|
120
|
-
super().__init__(wrapped) # type: ignore
|
|
121
|
-
self._self_interface = interface
|
|
122
|
-
|
|
123
|
-
@property
|
|
124
|
-
def interface(self) -> type[Any]:
|
|
125
|
-
return self._self_interface
|
|
40
|
+
warnings.warn(
|
|
41
|
+
"TestContainer.from_container() is deprecated. "
|
|
42
|
+
"Use the container directly with override() method.",
|
|
43
|
+
DeprecationWarning,
|
|
44
|
+
stacklevel=2,
|
|
45
|
+
)
|
|
46
|
+
return container
|