Coverage for faststream/_internal/endpoint/call_wrapper.py: 96%

60 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1import asyncio 

2from collections.abc import Awaitable, Callable, Reversible, Sequence 

3from typing import ( 

4 TYPE_CHECKING, 

5 Any, 

6 Generic, 

7 Optional, 

8 cast, 

9) 

10 

11import anyio 

12 

13from faststream._internal.configs import BrokerConfig 

14from faststream._internal.testing.calls import CallAssertions, CallRecorder 

15from faststream._internal.types import P_HandlerParams, T_HandlerReturn 

16from faststream.exceptions import SetupError 

17 

18if TYPE_CHECKING: 

19 from fast_depends.core import CallModel 

20 from fast_depends.dependencies import Dependant 

21 

22 from faststream._internal.basic_types import Decorator 

23 from faststream._internal.di import FastDependsConfig 

24 from faststream._internal.endpoint.publisher import PublisherProto 

25 from faststream._internal.endpoint.subscriber import SubscriberUsecase 

26 from faststream.message import StreamMessage 

27 

28 

29def ensure_call_wrapper( 

30 call: Callable[P_HandlerParams, T_HandlerReturn], 

31 outer_config: BrokerConfig, 

32 wrapper_class: "type[HandlerCallWrapper[..., Any]]", 

33) -> "HandlerCallWrapper[P_HandlerParams, T_HandlerReturn]": 

34 # An already wrapped handler keeps its class: the first decorator decides it 

35 if isinstance(call, HandlerCallWrapper): 

36 return call 

37 

38 return cast( 

39 "HandlerCallWrapper[P_HandlerParams, T_HandlerReturn]", 

40 wrapper_class(call, outer_config), 

41 ) 

42 

43 

44class HandlerCallWrapper(CallAssertions, Generic[P_HandlerParams, T_HandlerReturn]): 

45 """A generic class to wrap handler calls.""" 

46 

47 future: Optional["asyncio.Future[Any]"] 

48 _wrapped_call: Callable[..., Awaitable[Any]] | None 

49 # The handler as it was written, kept as written so that composing it again 

50 # from an unchanged declaration produces an unchanged result. 

51 _declared_call: Callable[P_HandlerParams, T_HandlerReturn] 

52 # What the last composition made of it, decorators applied. 

53 _composed_call: Callable[P_HandlerParams, T_HandlerReturn] 

54 

55 _publishers: list["PublisherProto[Any]"] 

56 

57 # we have to store subscribers here 

58 # to protect them from garbage collection 

59 _subscribers: list["SubscriberUsecase[Any]"] 

60 

61 __slots__ = ( 

62 "_composed_call", 

63 "_declared_call", 

64 "_publishers", 

65 "_recorder", 

66 "_subscribers", 

67 "_wrapped_call", 

68 "future", 

69 "is_test", 

70 ) 

71 

72 def __init__( 

73 self, 

74 call: Callable[P_HandlerParams, T_HandlerReturn], 

75 outer_config: BrokerConfig, 

76 ) -> None: 

77 """Initialize a handler.""" 

78 self._declared_call = call 

79 self._composed_call = call 

80 self._wrapped_call = None 

81 

82 self._publishers = [] 

83 self._subscribers = [] 

84 

85 self._recorder = CallRecorder( 

86 getattr(call, "__name__", repr(call)), 

87 outer_config, 

88 ) 

89 self.future = None 

90 self.is_test = False 

91 

92 def __call__( 

93 self, 

94 *args: P_HandlerParams.args, 

95 **kwargs: P_HandlerParams.kwargs, 

96 ) -> T_HandlerReturn: 

97 """Calls the object as a function.""" 

98 return self._composed_call(*args, **kwargs) 

99 

100 @property 

101 def _original_call(self) -> Callable[P_HandlerParams, T_HandlerReturn]: 

102 """The composed call, under the name it had before the two were kept apart.""" 

103 return self._composed_call 

104 

105 async def call_wrapped(self, message: "StreamMessage[Any]") -> Any: 

106 """Calls the wrapped function with the given message.""" 

107 assert self._wrapped_call, "You should use `set_wrapped` first" 

108 if self.is_test: 

109 await self._recorder.record(message) 

110 return await self._wrapped_call(message) 

111 

112 def set_wrapped( 

113 self, 

114 *, 

115 dependencies: Sequence["Dependant"], 

116 _call_decorators: Reversible["Decorator"], 

117 config: "FastDependsConfig", 

118 ) -> "CallModel": 

119 # Composed from the declaration rather than from the last composition: 

120 # `build_call` answers with the call it decorated, so reading that back 

121 # as the input would decorate it again, one more layer per build. 

122 dependent = config.build_call( 

123 self._declared_call, 

124 dependencies=dependencies, 

125 call_decorators=_call_decorators, 

126 ) 

127 self._composed_call = dependent.original_call 

128 self._wrapped_call = dependent.wrapped_call 

129 return dependent.dependent 

130 

131 async def wait_call(self, timeout: float | None = None) -> None: 

132 """Waits for a call with an optional timeout.""" 

133 assert self.future is not None, "You can use this method only with TestClient" 

134 with anyio.fail_after(timeout): 

135 await self.future 

136 

137 def set_test(self) -> None: 

138 self.is_test = True 

139 self.refresh(with_mock=True) 

140 

141 def reset_test(self) -> None: 

142 self.is_test = False 

143 self._recorder.reset() 

144 self._recorder.stop_mirroring() 

145 self.future = None 

146 

147 def trigger( 

148 self, 

149 result: Any = None, 

150 error: BaseException | None = None, 

151 ) -> None: 

152 if not self.is_test: 

153 return 

154 

155 if self.future is None: 155 ↛ 156line 155 didn't jump to line 156 because the condition on line 155 was never true

156 msg = "You can use this method only with TestClient" 

157 raise SetupError(msg) 

158 

159 if self.future.done(): 

160 self.future = asyncio.Future() 

161 

162 if error: 

163 self.future.set_exception(error) 

164 # Mark the mirrored error as retrieved to avoid unhandled-future reports. 

165 self.future.exception() 

166 

167 else: 

168 self.future.set_result(result) 

169 

170 def refresh(self, with_mock: bool = False) -> None: 

171 if asyncio.events._get_running_loop() is not None: 

172 self.future = asyncio.Future() 

173 

174 if with_mock: 

175 self._recorder.reset()