Coverage for faststream/_internal/testing/broker.py: 98%

115 statements  

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

1import warnings 

2from abc import abstractmethod 

3from collections.abc import AsyncGenerator, Generator 

4from contextlib import ( 

5 AsyncExitStack, 

6 asynccontextmanager, 

7 contextmanager, 

8) 

9from functools import partial 

10from typing import ( 

11 TYPE_CHECKING, 

12 Any, 

13 Generic, 

14 Optional, 

15 Protocol, 

16 TypeVar, 

17 cast, 

18) 

19from unittest import mock 

20from unittest.mock import MagicMock 

21 

22from typing_extensions import TypeVar as TypeVar313 

23 

24from faststream._internal.broker import BrokerUsecase 

25from faststream._internal.logger.logger_proxy import RealLoggerObject 

26from faststream._internal.testing.app import TestApp 

27from faststream._internal.testing.ast import is_contains_context_name 

28 

29if TYPE_CHECKING: 

30 from types import TracebackType 

31 

32 from faststream._internal.endpoint.subscriber import SubscriberUsecase 

33 

34 

35Broker = TypeVar("Broker", bound=BrokerUsecase[Any, Any, Any]) 

36 

37# ``__aenter__`` return type. Each concrete ``TestBroker`` subclass binds it to a 

38# single broker or a ``tuple`` of brokers via its overloaded ``__init__``. 

39EnterType = TypeVar313("EnterType", default=Any) 

40 

41 

42class _ProducerContains(Protocol): 

43 producer: Any 

44 

45 

46@contextmanager 

47def change_producer( 

48 config: _ProducerContains, 

49 producer: Any, 

50) -> Generator[None, None, None]: 

51 old_producer, config.producer = config.producer, producer 

52 try: 

53 yield 

54 finally: 

55 config.producer = old_producer 

56 

57 

58class TestBroker(Generic[Broker, EnterType]): 

59 """A class to represent a test broker.""" 

60 

61 # This is set so pytest ignores this class 

62 __test__ = False 

63 

64 def __init_subclass__( 

65 cls, 

66 broker: type[BrokerUsecase[Any, Any, Any]] | None = None, 

67 **kwargs: Any, 

68 ) -> None: 

69 super().__init_subclass__(**kwargs) 

70 if broker is not None: 70 ↛ exitline 70 didn't return from function '__init_subclass__' because the condition on line 70 was always true

71 _TEST_BROKERS[broker] = cls 

72 

73 def __init__( 

74 self, 

75 *brokers: Broker, 

76 with_real: bool = False, 

77 connect_only: bool | None = None, 

78 ) -> None: 

79 self.with_real = with_real 

80 self.brokers = brokers 

81 

82 if connect_only is None: 

83 try: 

84 connect_only = is_contains_context_name( 

85 self.__class__.__name__, 

86 TestApp.__name__, 

87 ) 

88 except Exception: # pragma: no cover 

89 warnings.warn( 

90 ( 

91 "\nError `{e!r}` occurred at `{self.__class__.__name__}` AST parsing." 

92 "\n`connect_only` is set to `False` by default." 

93 ), 

94 category=RuntimeWarning, 

95 stacklevel=1, 

96 ) 

97 

98 connect_only = False 

99 

100 self.connect_only = connect_only 

101 self._fake_subscribers: list[SubscriberUsecase[Any]] = [] 

102 

103 async def __aenter__(self) -> EnterType: 

104 self._ctx = self._create_ctx() 

105 brokers = await self._ctx.__aenter__() 

106 if len(brokers) == 1: 

107 return cast("EnterType", brokers[0]) 

108 return cast("EnterType", brokers) 

109 

110 async def __aexit__( 

111 self, 

112 exc_type: type[BaseException] | None = None, 

113 exc_val: BaseException | None = None, 

114 exc_tb: Optional["TracebackType"] = None, 

115 ) -> None: 

116 await self._ctx.__aexit__(exc_type, exc_val, exc_tb) 

117 

118 @asynccontextmanager 

119 async def _create_ctx(self) -> AsyncGenerator[list[Broker], None]: 

120 async with AsyncExitStack() as stack: 

121 saved_running = {} 

122 started_brokers = [] 

123 

124 for broker in self.brokers: 

125 if self.with_real: 

126 self._fake_start(broker) 

127 else: 

128 stack.enter_context(self._patch_broker(broker)) 

129 

130 await stack.enter_async_context(broker) 

131 

132 for sub in broker.subscribers: 

133 saved_running[sub] = sub.running 

134 

135 started_brokers.append( 

136 await stack.enter_async_context(self._do_start(broker)) 

137 ) 

138 

139 try: 

140 yield started_brokers 

141 finally: 

142 for sub, was_running in saved_running.items(): 

143 sub.running = was_running 

144 

145 @asynccontextmanager 

146 async def _do_start(self, broker: Broker) -> AsyncGenerator[Broker, None]: 

147 try: 

148 if not self.connect_only: 

149 await broker.start() 

150 

151 yield broker 

152 

153 finally: 

154 if self.with_real: 

155 # The real `broker.start()` started the fakes, and `_fake_close` hides 

156 # them from `broker.stop()` (see #3046): stop them here or they leak. 

157 for sub in self._fake_subscribers: 

158 await sub.stop() 

159 

160 self._fake_close(broker) 

161 

162 @contextmanager 

163 def _patch_producer(self, broker: Broker) -> Generator[None, None, None]: 

164 raise NotImplementedError 

165 

166 @contextmanager 

167 def _patch_broker(self, broker: Broker) -> Generator[None, None, None]: 

168 with ( 

169 mock.patch.object( 

170 broker, 

171 "start", 

172 wraps=partial(self._fake_start, broker), 

173 ), 

174 mock.patch.object( 

175 broker, 

176 "_connect", 

177 wraps=partial(self._fake_connect, broker), 

178 ), 

179 mock.patch.object( 

180 broker, 

181 "stop", 

182 ), 

183 mock.patch.object( 

184 broker, 

185 "_connection", 

186 new=None, 

187 ), 

188 self._patch_producer(broker), 

189 _patch_logger(broker), 

190 mock.patch.object( 

191 broker, 

192 "ping", 

193 return_value=True, 

194 ), 

195 ): 

196 yield 

197 

198 def _fake_start(self, broker: Broker, *args: Any, **kwargs: Any) -> None: 

199 for publisher in broker.publishers: 

200 if getattr(publisher, "_fake_handler", None): 

201 continue 

202 

203 sub, is_real = self.create_publisher_fake_subscriber(broker, publisher) 

204 

205 if not is_real: 

206 self._fake_subscribers.append(sub) 

207 

208 if not sub.calls: 

209 

210 @sub 

211 async def publisher_response_subscriber(msg: Any) -> None: 

212 pass 

213 

214 if is_real: 

215 # A real subscriber keeps its own record; the publisher gets a copy 

216 publisher.set_test(with_fake=False) 

217 for h in sub.calls: 

218 h.handler.set_test() 

219 h.handler._recorder.mirror_to(publisher._recorder) 

220 

221 else: 

222 handler = sub.calls[0].handler 

223 handler.set_test() 

224 publisher.set_test(recorder=handler._recorder, with_fake=True) 

225 

226 patch_broker_calls(broker) 

227 

228 for subscriber in broker.subscribers: 

229 subscriber._post_start() 

230 

231 def _fake_close( 

232 self, 

233 broker: Broker, 

234 exc_type: type[BaseException] | None = None, 

235 exc_val: BaseException | None = None, 

236 exc_tb: Optional["TracebackType"] = None, 

237 ) -> None: 

238 for p in broker.publishers: 

239 p.reset_test() 

240 

241 # Fakes are registered with `persistent=False`, so the broker holds them weakly 

242 # and they outlive us until the next collection (see issue #2990). 

243 for sub in self._fake_subscribers: 

244 broker._subscribers.discard(sub) 

245 

246 self._fake_subscribers.clear() 

247 

248 for sub in broker.subscribers: 

249 sub.running = False 

250 for call in sub.calls: 

251 call.handler.reset_test() 

252 

253 @abstractmethod 

254 def create_publisher_fake_subscriber( 

255 self, 

256 broker: Broker, 

257 publisher: Any, 

258 ) -> tuple["SubscriberUsecase[Any]", bool]: 

259 raise NotImplementedError 

260 

261 @abstractmethod 

262 async def _fake_connect(self, broker: Broker, *args: Any, **kwargs: Any) -> None: 

263 raise NotImplementedError 

264 

265 

266def find_test_broker( 

267 broker: BrokerUsecase[Any, Any, Any], 

268) -> type[TestBroker[Any, Any]] | None: 

269 """Return the TestBroker registered for the broker's class, if any.""" 

270 # the closest class wins: a broker subclass may register a TestBroker of its own 

271 for broker_cls in type(broker).__mro__: 271 ↛ 274line 271 didn't jump to line 274 because the loop on line 271 didn't complete

272 if test_broker_cls := _TEST_BROKERS.get(broker_cls): 

273 return test_broker_cls 

274 return None 

275 

276 

277def patch_broker_calls(broker: "BrokerUsecase[Any, Any, Any]") -> None: 

278 """Patch broker calls.""" 

279 for sub in broker.subscribers: 

280 sub._build_fastdepends_model() 

281 

282 for h in sub.calls: 

283 h.handler.set_test() 

284 

285 

286@contextmanager 

287def _patch_logger( 

288 broker: "BrokerUsecase[Any, Any, Any]", 

289) -> Generator[None, None, None]: 

290 broker._setup_logger() 

291 

292 logger_state = broker.config.logger 

293 

294 old_log_object, logger_state.logger = ( 

295 logger_state.logger, 

296 RealLoggerObject(MagicMock()), 

297 ) 

298 

299 try: 

300 yield 

301 

302 finally: 

303 logger_state.logger = old_log_object 

304 

305 

306_TEST_BROKERS: dict[type[BrokerUsecase[Any, Any, Any]], type[TestBroker[Any, Any]]] = {}