fastapi-injected 0.4.0__tar.gz → 0.4.2__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.
Files changed (76) hide show
  1. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/.github/workflows/test.yml +1 -1
  2. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/PKG-INFO +3 -2
  3. fastapi_injected-0.4.2/fastapi_injected/_body.py +90 -0
  4. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_cache.py +1 -1
  5. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_calls.py +1 -1
  6. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/ctx.py +8 -8
  7. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/fastapi.py +35 -6
  8. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/inject.py +1 -1
  9. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/pyproject.toml +3 -2
  10. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/bind.py +1 -1
  11. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/ctx.py +1 -1
  12. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/resolve.py +1 -1
  13. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_body.py +23 -13
  14. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_body_reads.py +3 -10
  15. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_dependant_cache.py +1 -1
  16. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_fastapi.py +4 -1
  17. fastapi_injected-0.4.2/uv.lock +839 -0
  18. fastapi_injected-0.4.0/fastapi_injected/_body.py +0 -108
  19. fastapi_injected-0.4.0/uv.lock +0 -819
  20. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/.github/dependabot.yml +0 -0
  21. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/.github/workflows/automerge.yml +0 -0
  22. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/.github/workflows/lint.yml +0 -0
  23. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/.github/workflows/publish.yml +0 -0
  24. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/.gitignore +0 -0
  25. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/.pre-commit-config.yaml +0 -0
  26. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/LICENSE +0 -0
  27. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/README.md +0 -0
  28. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/__init__.py +0 -0
  29. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_bind.py +0 -0
  30. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_dataclass.py +0 -0
  31. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_deps_tp.py +0 -0
  32. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_given.py +0 -0
  33. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_injected.py +0 -0
  34. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_overrides.py +0 -0
  35. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/_rlock.py +0 -0
  36. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/deps.py +0 -0
  37. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/ext.py +0 -0
  38. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/overrides.py +0 -0
  39. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/reflect/__init__.py +0 -0
  40. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/reflect/_dependant.py +0 -0
  41. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/reflect/_openapi.py +0 -0
  42. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/reflect/_routes.py +0 -0
  43. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/resolve.py +0 -0
  44. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/signature.py +0 -0
  45. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/fastapi_injected/types.py +0 -0
  46. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/__init__.py +0 -0
  47. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/__init__.py +0 -0
  48. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/annotations.py +0 -0
  49. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/arg.py +0 -0
  50. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/dataclass.py +0 -0
  51. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/deps.py +0 -0
  52. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/errors.py +0 -0
  53. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/given.py +0 -0
  54. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/inject.py +0 -0
  55. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/injected.py +0 -0
  56. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/integration.py +0 -0
  57. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/markers.py +0 -0
  58. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/_typing/overrides.py +0 -0
  59. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/deps.py +0 -0
  60. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/ext/__init__.py +0 -0
  61. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/ext/test_pydantic_ai.py +0 -0
  62. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_bind.py +0 -0
  63. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_cache.py +0 -0
  64. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_calls.py +0 -0
  65. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_concurrency.py +0 -0
  66. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_ctx.py +0 -0
  67. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_dataclass.py +0 -0
  68. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_errors.py +0 -0
  69. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_given.py +0 -0
  70. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_inject.py +0 -0
  71. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_injected.py +0 -0
  72. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_overrides.py +0 -0
  73. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_reflect.py +0 -0
  74. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_request_params.py +0 -0
  75. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_resolve.py +0 -0
  76. {fastapi_injected-0.4.0 → fastapi_injected-0.4.2}/tests/test_rlock.py +0 -0
@@ -15,7 +15,7 @@ jobs:
15
15
  strategy:
16
16
  fail-fast: false
17
17
  matrix:
18
- python-version: ["3.12", "3.13", "3.14"]
18
+ python-version: ["3.12", "3.13", "3.14", "3.15"]
19
19
 
20
20
  steps:
21
21
  - uses: actions/checkout@v7
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: fastapi-injected
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: Yet another library to reuse fastapi dependency injection
5
5
  Project-URL: Repository, https://github.com/uriyyo/fastapi-injected
6
6
  Author-email: Yurii Karabas <1998uriyyo@gmail.com>
@@ -13,8 +13,9 @@ Classifier: Programming Language :: Python :: 3 :: Only
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Classifier: Programming Language :: Python :: 3.13
15
15
  Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
16
17
  Requires-Python: >=3.12
17
- Requires-Dist: fastapi>=0.141.0
18
+ Requires-Dist: fastapi>=0.158.0
18
19
  Requires-Dist: typing-extensions>=4.16.0
19
20
  Requires-Dist: typing-inspection>=0.4.4
20
21
  Description-Content-Type: text/markdown
@@ -0,0 +1,90 @@
1
+ import email.message
2
+ import json
3
+ from typing import Any
4
+
5
+ from fastapi import Request, params
6
+ from fastapi._compat import Undefined
7
+ from fastapi.dependencies.models import Dependant
8
+ from fastapi.dependencies.utils import _get_flat_body_params, _should_embed_body_fields
9
+ from fastapi.routing import APIRoute
10
+
11
+ from .types import BoundConnection
12
+
13
+ type RequestBody = tuple[Any, bool]
14
+
15
+ BODY_CACHE_KEY = "fastapi_injected_body"
16
+
17
+
18
+ class InvalidBodyError(ValueError):
19
+ def __init__(self, errors: list[Any], /) -> None:
20
+ super().__init__(errors)
21
+ self.errors = errors
22
+
23
+
24
+ def _is_json_content_type(content_type: str, /) -> bool:
25
+ message = email.message.Message()
26
+ message["content-type"] = content_type
27
+ subtype = message.get_content_subtype()
28
+
29
+ return message.get_content_maintype() == "application" and (subtype == "json" or subtype.endswith("+json"))
30
+
31
+
32
+ async def _read_body(request: Request, *, is_form: bool) -> Any:
33
+ if is_form:
34
+ form = await request.form()
35
+ # closing a form twice is harmless
36
+ request.scope["fastapi_middleware_astack"].push_async_callback(form.close)
37
+
38
+ return form
39
+
40
+ if not (body := await request.body()):
41
+ return Undefined
42
+
43
+ if not _is_json_content_type(request.headers.get("content-type", "")):
44
+ return body
45
+
46
+ try:
47
+ return await request.json()
48
+ except json.JSONDecodeError as exc:
49
+ raise InvalidBodyError(
50
+ [
51
+ {
52
+ "type": "json_invalid",
53
+ "loc": ("body", exc.pos),
54
+ "msg": "JSON decode error",
55
+ "input": {},
56
+ "ctx": {"error": exc.msg},
57
+ },
58
+ ],
59
+ ) from exc
60
+
61
+
62
+ def _route_embeds(request: Request, /) -> bool:
63
+ match request.scope.get("route"):
64
+ case APIRoute(_embed_body_fields=embed):
65
+ return embed
66
+
67
+ return False
68
+
69
+
70
+ async def request_body(request: BoundConnection, dependant: Dependant, /) -> RequestBody:
71
+ if not isinstance(request, Request) or not (fields := _get_flat_body_params(dependant)):
72
+ return Undefined, False
73
+
74
+ is_form = any(isinstance(field.field_info, params.Form) for field in fields)
75
+
76
+ # parsed once per request
77
+ cache: dict[bool, Any] = request.scope[BODY_CACHE_KEY]
78
+
79
+ if is_form not in cache:
80
+ cache[is_form] = await _read_body(request, is_form=is_form)
81
+
82
+ # read the body the way the route does
83
+ return cache[is_form], _route_embeds(request) or _should_embed_body_fields(fields)
84
+
85
+
86
+ __all__ = [
87
+ "BODY_CACHE_KEY",
88
+ "InvalidBodyError",
89
+ "request_body",
90
+ ]
@@ -37,7 +37,7 @@ def _cache_key(key: DependencyCacheKey, /) -> DependencyCacheKey:
37
37
  # done, the entry has to stay reachable for the rest of the context
38
38
  call, *rest = key
39
39
 
40
- return (unwrap_proxy(call), *rest) # type: ignore[ty:invalid-return-type]
40
+ return (unwrap_proxy(call), *rest) # type: ignore[ty:invalid-explicit-return]
41
41
 
42
42
 
43
43
  class ContextCache(MakeDataclass, MutableMapping[DependencyCacheKey, Any]):
@@ -14,7 +14,7 @@ from ._deps_tp import unwrap_tp
14
14
  def annotated(tp: Any, /, *metadata: Any) -> Any:
15
15
  # `Annotated[...]` goes through typing's own cache, which holds on to the last
16
16
  # aliases it built - and with them whatever value a runtime marker carries
17
- return typing._AnnotatedAlias(tp, metadata) # type: ignore[ty:unresolved-attribute] # noqa: SLF001
17
+ return typing._AnnotatedAlias(tp, metadata) # type: ignore[ty:missing-attribute] # noqa: SLF001
18
18
 
19
19
 
20
20
  def is_static_call(call: Any, /) -> bool:
@@ -12,6 +12,7 @@ from dataclasses import field, replace
12
12
  from typing import Any, Self, cast
13
13
  from urllib.parse import urlencode
14
14
 
15
+ from anyio import CancelScope
15
16
  from fastapi import FastAPI, Request, WebSocket
16
17
  from fastapi.dependencies.models import Dependant
17
18
  from fastapi.encoders import jsonable_encoder
@@ -21,6 +22,7 @@ from starlette.requests import HTTPConnection
21
22
  from starlette.types import Message, Scope
22
23
  from starlette.websockets import WebSocketState
23
24
 
25
+ from ._body import BODY_CACHE_KEY
24
26
  from ._cache import ContextCache, overridden_calls
25
27
  from ._dataclass import MakeDataclass
26
28
  from ._overrides import Overrides, normalize_overrides
@@ -110,6 +112,7 @@ def _dummy_request(
110
112
  pass
111
113
 
112
114
  scope = _dummy_scope()
115
+ scope[BODY_CACHE_KEY] = {}
113
116
 
114
117
  if app is not None:
115
118
  scope["app"] = app
@@ -168,14 +171,6 @@ class _ReboundRequest(Request):
168
171
  async def _get_form(self, **kwargs: Any) -> FormData:
169
172
  return await self._origin._get_form(**kwargs) # noqa: SLF001
170
173
 
171
- @property
172
- def _form(self) -> FormData | None:
173
- return self._origin._form # noqa: SLF001
174
-
175
- @_form.setter
176
- def _form(self, _: FormData | None) -> None:
177
- pass
178
-
179
174
  async def close(self) -> None:
180
175
  await self._origin.close()
181
176
 
@@ -208,6 +203,9 @@ def _rebind_request(
208
203
  *,
209
204
  extra_scope: Scope,
210
205
  ) -> BoundConnection:
206
+ # shared by every context of the request
207
+ request.scope.setdefault(BODY_CACHE_KEY, {})
208
+
211
209
  scope = {**request.scope, **extra_scope}
212
210
 
213
211
  if isinstance(request, WebSocket):
@@ -346,6 +344,8 @@ async def injection_ctx(
346
344
  extra_scope: Scope = {
347
345
  "fastapi_inner_astack": stack,
348
346
  "fastapi_function_astack": stack,
347
+ # entered here, not by fastapi inside a task group
348
+ "fastapi_async_cleanup_scopes": {stack: stack.enter_context(CancelScope())},
349
349
  }
350
350
 
351
351
  request = (
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any
6
6
  from fastapi import Depends, FastAPI, Request, WebSocket, routing
7
7
  from fastapi.dependencies import utils
8
8
  from starlette.requests import HTTPConnection
9
- from starlette.types import ASGIApp, Receive, Scope, Send
9
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
10
10
 
11
11
  from ._cache import ContextCache
12
12
  from .ctx import injection_ctx
@@ -19,6 +19,19 @@ class MissingDependencyCacheError(Exception):
19
19
  pass
20
20
 
21
21
 
22
+ class ConnectionNotAvailableError(Exception):
23
+ def __init__(self) -> None:
24
+ super().__init__("The connection can not be received from or sent to outside of a route")
25
+
26
+
27
+ async def _unavailable_receive() -> Message:
28
+ raise ConnectionNotAvailableError
29
+
30
+
31
+ async def _unavailable_send(_: Message) -> None:
32
+ raise ConnectionNotAvailableError
33
+
34
+
22
35
  if not TYPE_CHECKING:
23
36
  _base_solve_dependencies = utils.solve_dependencies
24
37
 
@@ -91,9 +104,9 @@ class InjectionMiddleware:
91
104
 
92
105
  match scope["type"]:
93
106
  case "http":
94
- connection = Request(scope, receive, send)
107
+ connection = Request(scope, _unavailable_receive, _unavailable_send)
95
108
  case "websocket":
96
- connection = WebSocket(scope, receive, send)
109
+ connection = WebSocket(scope, _unavailable_receive, _unavailable_send)
97
110
  case _:
98
111
  await self.app(scope, receive, send)
99
112
  return
@@ -103,23 +116,39 @@ class InjectionMiddleware:
103
116
  async with injection_ctx(
104
117
  dependency_cache=cache,
105
118
  request=connection,
106
- provider=scope.get("app"),
119
+ provider=_get_overrides_provider(connection),
107
120
  ):
108
121
  await self.app(scope, receive, send)
109
122
 
110
123
 
124
+ def _wrap_build_middleware_stack(app: FastAPI) -> None:
125
+ _build_middleware_stack = app.build_middleware_stack
126
+
127
+ @wraps(_build_middleware_stack)
128
+ def _build_middleware_stack_wrapper() -> ASGIApp:
129
+ return InjectionMiddleware(_build_middleware_stack())
130
+
131
+ app.build_middleware_stack = _build_middleware_stack_wrapper
132
+ app.build_middleware_stack.__patched__ = True # type: ignore[ty:missing-attribute]
133
+
134
+
135
+ def _is_build_middleware_stack_patched(app: FastAPI) -> bool:
136
+ return getattr(app.build_middleware_stack, "__patched__", False)
137
+
138
+
111
139
  def add_injection(
112
140
  app: FastAPI,
113
141
  /,
114
142
  ) -> None:
115
- if not any(middleware.cls is InjectionMiddleware for middleware in app.user_middleware):
116
- app.add_middleware(InjectionMiddleware)
143
+ if not _is_build_middleware_stack_patched(app):
144
+ _wrap_build_middleware_stack(app)
117
145
 
118
146
  if not any(dep.dependency is bind_injection_ctx for dep in app.router.dependencies):
119
147
  app.router.dependencies.insert(0, Depends(bind_injection_ctx))
120
148
 
121
149
 
122
150
  __all__ = [
151
+ "ConnectionNotAvailableError",
123
152
  "InjectionMiddleware",
124
153
  "MissingDependencyCacheError",
125
154
  "add_injection",
@@ -31,7 +31,7 @@ def inject[**P, R](
31
31
  new_ctx: bool = False,
32
32
  ) -> AsyncFunc[P, R] | AsyncDecorator[P, R]:
33
33
  if func is None:
34
- return partial(inject, new_ctx=new_ctx) # type: ignore[ty:invalid-return-type]
34
+ return partial(inject, new_ctx=new_ctx) # type: ignore[ty:invalid-explicit-return]
35
35
 
36
36
  dependant = create_dependant(func)
37
37
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fastapi-injected"
3
- version = "0.4.0"
3
+ version = "0.4.2"
4
4
  description = "Yet another library to reuse fastapi dependency injection"
5
5
  authors = [
6
6
  { name = "Yurii Karabas", email = "1998uriyyo@gmail.com" },
@@ -15,10 +15,11 @@ classifiers = [
15
15
  "Programming Language :: Python :: 3.12",
16
16
  "Programming Language :: Python :: 3.13",
17
17
  "Programming Language :: Python :: 3.14",
18
+ "Programming Language :: Python :: 3.15",
18
19
  "Programming Language :: Python :: 3 :: Only",
19
20
  ]
20
21
  dependencies = [
21
- "fastapi>=0.141.0",
22
+ "fastapi>=0.158.0",
22
23
  "typing-extensions>=4.16.0",
23
24
  "typing-inspection>=0.4.4",
24
25
  ]
@@ -97,7 +97,7 @@ async def _negatives_on_what_is_left() -> None:
97
97
 
98
98
  def _negatives() -> None:
99
99
  bind_deps() # type: ignore[ty:no-matching-overload]
100
- bind_deps(_describe, 42) # type: ignore[ty:invalid-type-form]
100
+ bind_deps(_describe, 42)
101
101
 
102
102
  # the call is awaited, so it has to be one that can be
103
103
  bind_deps(_sync_describe) # type: ignore[ty:no-matching-overload]
@@ -61,7 +61,7 @@ async def _negatives() -> None:
61
61
  async with injection_ctx(dependency_cache=[]): # type: ignore[ty:invalid-argument-type]
62
62
  pass
63
63
 
64
- _ = InjectionContext.current().dependency_cache # type: ignore[ty:unresolved-attribute]
64
+ _ = InjectionContext.current().dependency_cache # type: ignore[ty:missing-union-attribute]
65
65
 
66
66
  async with injection_ctx(request=object()): # type: ignore[ty:invalid-argument-type]
67
67
  pass
@@ -59,7 +59,7 @@ async def _negatives() -> None:
59
59
  await resolve() # type: ignore[ty:no-matching-overload]
60
60
 
61
61
  # what `resolve` returns is the dependency, not the marker
62
- _ = (await resolve(Container)).unknown # type: ignore[ty:unresolved-attribute]
62
+ _ = (await resolve(Container)).unknown # type: ignore[ty:missing-attribute]
63
63
 
64
64
 
65
65
  class CallableDep:
@@ -1,4 +1,4 @@
1
- from typing import Annotated
1
+ from typing import Annotated, Any
2
2
 
3
3
  import pytest
4
4
  from fastapi import (
@@ -30,6 +30,7 @@ from fastapi_injected import (
30
30
  resolve,
31
31
  synthetic_request,
32
32
  )
33
+ from fastapi_injected.fastapi import ConnectionNotAvailableError
33
34
 
34
35
 
35
36
  class Item(BaseModel):
@@ -427,19 +428,8 @@ async def ws(websocket: WebSocket) -> None:
427
428
  await websocket.close()
428
429
 
429
430
 
430
- def test_form_the_route_read_is_resolved(monkeypatch: pytest.MonkeyPatch) -> None:
431
- closed = 0
432
- close = FormData.close
433
-
434
- async def _counting_close(self: FormData) -> None:
435
- nonlocal closed
436
- closed += 1
437
- await close(self)
438
-
439
- monkeypatch.setattr(FormData, "close", _counting_close)
440
-
431
+ def test_form_the_route_read_is_resolved() -> None:
441
432
  assert client.post("/route-form", data={"name": "m"}).json() == ["m", "m"]
442
- assert closed == 1
443
433
 
444
434
 
445
435
  def test_upload_the_route_read_is_resolved() -> None:
@@ -522,3 +512,23 @@ async def test_header_with_an_alias_on_a_synthetic_request():
522
512
  [error] = exc_info.value.errors
523
513
 
524
514
  assert (error["type"], error["loc"]) == ("missing", ("header", "X-Api-Key"))
515
+
516
+
517
+ def test_body_can_not_be_read_in_a_middleware() -> None:
518
+ middleware_app = FastAPI()
519
+
520
+ @middleware_app.middleware("http")
521
+ async def _read_body(request: Request, call_next: Any) -> Any:
522
+ with pytest.raises(ConnectionNotAvailableError):
523
+ await resolve(ItemDep)
524
+
525
+ return await call_next(request)
526
+
527
+ @middleware_app.post("/")
528
+ async def _route(item: Item) -> str:
529
+ # the route still gets the body the middleware could not take
530
+ return item.name
531
+
532
+ add_injection(middleware_app)
533
+
534
+ assert TestClient(middleware_app).post("/", json={"name": "g"}).json() == "g"
@@ -131,15 +131,8 @@ async def route_then_nested(item: Item, request: Request) -> list[str]:
131
131
  async def _fresh(*, fresh: ItemDep = Injected) -> str:
132
132
  return fresh.name
133
133
 
134
- # the route took the whole body as the item, so a field embedded under a name is not there
135
- try:
136
- await resolve(Name)
137
- except DependencyResolutionError as exc:
138
- mismatch = [error["type"] for error in exc.errors]
139
- else: # pragma: no cover
140
- mismatch = []
141
-
142
- return [item.name, await _fresh(), (await request.json())["name"], *mismatch]
134
+ # fastapi decides embedding per dependency
135
+ return [item.name, await _fresh(), (await request.json())["name"], await resolve(Name)]
143
136
 
144
137
 
145
138
  @app.post("/form-model")
@@ -205,7 +198,7 @@ def test_concurrent_resolves_share_one_read() -> None:
205
198
 
206
199
 
207
200
  def test_route_body_is_not_read_again_by_a_fresh_ctx() -> None:
208
- assert client.post("/route-then-nested", json={"name": "d"}).json() == ["d", "d", "d", "string_type"]
201
+ assert client.post("/route-then-nested", json={"name": "d"}).json() == ["d", "d", "d", "d"]
209
202
  assert counting.reads == [1]
210
203
 
211
204
 
@@ -192,7 +192,7 @@ async def test_values_resolved_at_runtime_are_not_cached(make: Callable[[Payload
192
192
 
193
193
 
194
194
  class Opened(Resolver):
195
- async def __call__(self, foo: Annotated[Foo, Depends(foo_dep)]) -> AsyncIterator[list[Payload]]: # ty: ignore[invalid-method-override]
195
+ async def __call__(self, foo: Annotated[Foo, Depends(foo_dep)]) -> AsyncIterator[list[Payload]]: # ty: ignore[incompatible-method-override]
196
196
  opened = [self.payload]
197
197
  yield opened
198
198
  opened.clear()
@@ -136,7 +136,10 @@ def test_add_injection_is_idempotent() -> None:
136
136
  add_injection(other_app)
137
137
  add_injection(other_app)
138
138
 
139
- assert [middleware.cls for middleware in other_app.user_middleware] == [InjectionMiddleware, GZipMiddleware]
139
+ stack = other_app.build_middleware_stack()
140
+ assert isinstance(stack, InjectionMiddleware)
141
+ assert not isinstance(stack.app, InjectionMiddleware)
142
+ assert [middleware.cls for middleware in other_app.user_middleware] == [GZipMiddleware]
140
143
  assert [dep.dependency for dep in other_app.router.dependencies] == [bind_injection_ctx, _item_id_dep]
141
144
 
142
145