Coverage for faststream/rabbit/testing.py: 99%
111 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1from collections.abc import Generator, Iterable, Mapping, Sequence
2from contextlib import ExitStack, contextmanager
3from typing import TYPE_CHECKING, Any, Optional, Union, cast, overload
4from unittest import mock
5from unittest.mock import AsyncMock
7import aiormq
8import anyio
9from aio_pika.message import IncomingMessage, encode_expiration
10from pamqp import commands as spec
11from pamqp.header import ContentHeader
12from typing_extensions import override
14from faststream._internal.endpoint.utils import ParserComposition
15from faststream._internal.parser import DefaultCodec
16from faststream._internal.testing.broker import (
17 EnterType,
18 TestBroker,
19 change_producer,
20)
21from faststream._internal.types import IdGenerator
22from faststream.exceptions import SubscriberNotFound
23from faststream.message import gen_cor_id
24from faststream.rabbit.broker.broker import RabbitBroker
25from faststream.rabbit.parser import AioPikaParser
26from faststream.rabbit.publisher.producer import AioPikaFastProducer
27from faststream.rabbit.schemas import (
28 ExchangeType,
29 RabbitExchange,
30 RabbitQueue,
31)
33if TYPE_CHECKING:
34 from aio_pika.abc import DateType, HeadersType
35 from fast_depends.library.serializer import SerializerProto
37 from faststream._internal.endpoint.subscriber import SubscriberUsecase
38 from faststream._internal.parser import CodecProto
39 from faststream.rabbit.publisher import RabbitPublisher
40 from faststream.rabbit.response import RabbitPublishCommand
41 from faststream.rabbit.subscriber import RabbitSubscriber
42 from faststream.rabbit.types import AioPikaSendableMessage
44__all__ = ("TestRabbitBroker",)
47class TestRabbitBroker(
48 TestBroker[RabbitBroker, EnterType],
49 broker=RabbitBroker,
50):
51 """A class to test RabbitMQ brokers."""
53 @overload
54 def __init__(
55 self: "TestRabbitBroker[RabbitBroker]",
56 broker: RabbitBroker,
57 /,
58 *,
59 with_real: bool = False,
60 connect_only: bool | None = None,
61 ) -> None: ...
63 @overload
64 def __init__(
65 self: "TestRabbitBroker[tuple[RabbitBroker, ...]]",
66 *brokers: RabbitBroker,
67 with_real: bool = False,
68 connect_only: bool | None = None,
69 ) -> None: ...
71 def __init__(
72 self,
73 *brokers: RabbitBroker,
74 with_real: bool = False,
75 connect_only: bool | None = None,
76 ) -> None:
77 super().__init__(
78 *brokers,
79 with_real=with_real,
80 connect_only=connect_only,
81 )
83 @contextmanager
84 def _patch_broker(self, broker: "RabbitBroker") -> Generator[None, None, None]:
85 with (
86 mock.patch.object(
87 broker,
88 "_channel",
89 new_callable=AsyncMock,
90 ),
91 mock.patch.object(
92 broker.config,
93 "declarer",
94 new_callable=AsyncMock,
95 ),
96 super()._patch_broker(broker),
97 ):
98 yield
100 @contextmanager
101 def _patch_producer(self, broker: RabbitBroker) -> Generator[None, None, None]:
102 fake_producer = FakeProducer(broker, self.brokers)
104 with ExitStack() as es:
105 es.enter_context(
106 change_producer(broker.config.broker_config, fake_producer),
107 )
108 yield
110 @staticmethod
111 async def _fake_connect(broker: "RabbitBroker", *args: Any, **kwargs: Any) -> None:
112 pass
114 def create_publisher_fake_subscriber(
115 self,
116 broker: "RabbitBroker",
117 publisher: "RabbitPublisher",
118 ) -> tuple["RabbitSubscriber", bool]:
119 sub: RabbitSubscriber | None = None
120 for handler in (s for b in self.brokers for s in b.subscribers):
121 handler = cast("RabbitSubscriber", handler)
122 if _is_handler_matches(
123 handler,
124 publisher.routing(),
125 {},
126 publisher.exchange,
127 ):
128 sub = handler
129 break
131 if sub is None:
132 is_real = False
133 sub = broker.subscriber(
134 queue=publisher.routing(),
135 exchange=publisher.exchange,
136 persistent=False,
137 )
138 else:
139 is_real = True
141 return sub, is_real
144class PatchedMessage(IncomingMessage):
145 """Patched message class for testing purposes.
147 This class extends aio_pika's IncomingMessage class and is used to simulate RabbitMQ message handling during tests.
148 """
150 routing_key: str
152 async def ack(self, multiple: bool = False) -> None:
153 """Asynchronously acknowledge a message."""
155 async def nack(self, multiple: bool = False, requeue: bool = True) -> None:
156 """Nack the message."""
158 async def reject(self, requeue: bool = False) -> None:
159 """Rejects a task."""
162async def build_message(
163 message: "AioPikaSendableMessage" = "",
164 queue: Union["RabbitQueue", str] = "",
165 exchange: Union["RabbitExchange", str, None] = None,
166 *,
167 routing_key: str = "",
168 persist: bool = False,
169 reply_to: str | None = None,
170 headers: Optional["HeadersType"] = None,
171 content_type: str | None = None,
172 content_encoding: str | None = None,
173 priority: int | None = None,
174 correlation_id: str | None = None,
175 expiration: Optional["DateType"] = None,
176 message_id: str | None = None,
177 timestamp: Optional["DateType"] = None,
178 message_type: str | None = None,
179 user_id: str | None = None,
180 app_id: str | None = None,
181 serializer: Optional["SerializerProto"] = None,
182 codec: Optional["CodecProto"] = None,
183 id_generator: IdGenerator = gen_cor_id,
184) -> PatchedMessage:
185 """Build a patched RabbitMQ message for testing."""
186 que = RabbitQueue.validate(queue)
187 exch = RabbitExchange.validate(exchange)
189 routing = routing_key or que.routing()
191 correlation_id = correlation_id or id_generator()
192 msg = await AioPikaParser.encode_message(
193 message=message,
194 persist=persist,
195 reply_to=reply_to,
196 headers=headers,
197 content_type=content_type,
198 content_encoding=content_encoding,
199 priority=priority,
200 correlation_id=correlation_id,
201 expiration=expiration,
202 message_id=message_id or correlation_id,
203 timestamp=timestamp,
204 message_type=message_type,
205 user_id=user_id,
206 app_id=app_id,
207 serializer=serializer,
208 codec=codec,
209 )
211 return PatchedMessage(
212 aiormq.abc.DeliveredMessage(
213 delivery=spec.Basic.Deliver(
214 exchange=getattr(exch, "name", ""),
215 routing_key=routing,
216 ),
217 header=ContentHeader(
218 properties=spec.Basic.Properties(
219 content_type=msg.content_type,
220 headers=msg.headers,
221 reply_to=msg.reply_to,
222 content_encoding=msg.content_encoding,
223 priority=msg.priority,
224 correlation_id=msg.correlation_id,
225 expiration=encode_expiration(msg.expiration),
226 message_id=msg.message_id,
227 timestamp=msg.timestamp,
228 message_type=message_type,
229 user_id=msg.user_id,
230 app_id=msg.app_id,
231 ),
232 ),
233 body=msg.body,
234 channel=AsyncMock(),
235 ),
236 )
239class FakeProducer(AioPikaFastProducer):
240 """A fake RabbitMQ producer for testing purposes.
242 This class extends AioPikaFastProducer and is used to simulate RabbitMQ message publishing during tests.
243 """
245 def __init__(
246 self,
247 broker: RabbitBroker,
248 brokers: Sequence[RabbitBroker],
249 ) -> None:
250 self.broker = broker
251 self.brokers = brokers
253 default_parser = AioPikaParser()
254 self._parser = ParserComposition(broker._parser, default_parser.parse_message)
255 self._decoder = ParserComposition(
256 broker._decoder,
257 default_parser.decode_message,
258 )
259 self.codec = broker.config.broker_codec or DefaultCodec()
261 @property
262 def subscribers(self) -> Iterable["SubscriberUsecase[Any]"]:
263 return (s for b in self.brokers for s in b.subscribers)
265 @override
266 async def publish(
267 self,
268 cmd: "RabbitPublishCommand",
269 ) -> None:
270 """Publish a message to a RabbitMQ queue or exchange."""
271 incoming = await build_message(
272 message=cmd.body,
273 exchange=cmd.exchange,
274 routing_key=cmd.destination,
275 correlation_id=cmd.correlation_id,
276 headers=cmd.headers,
277 reply_to=cmd.reply_to,
278 serializer=self.broker.config.fd_config._serializer,
279 codec=self.codec,
280 id_generator=self.broker.config.id_generator,
281 **cmd.message_options,
282 )
284 called = False
285 for handler in self.subscribers: # pragma: no branch
286 handler = cast("RabbitSubscriber", handler)
287 if _is_handler_matches(
288 handler,
289 incoming.routing_key,
290 incoming.headers,
291 cmd.exchange,
292 ):
293 called = True
294 await self._execute_handler(incoming, handler)
296 if not called:
297 raise SubscriberNotFound
299 @override
300 async def request(
301 self,
302 cmd: "RabbitPublishCommand",
303 ) -> "PatchedMessage":
304 """Make a synchronous request to RabbitMQ."""
305 incoming = await build_message(
306 message=cmd.body,
307 exchange=cmd.exchange,
308 routing_key=cmd.destination,
309 correlation_id=cmd.correlation_id,
310 headers=cmd.headers,
311 serializer=self.broker.config.fd_config._serializer,
312 codec=self.codec,
313 id_generator=self.broker.config.id_generator,
314 **cmd.message_options,
315 )
317 for handler in self.subscribers: # pragma: no branch
318 handler = cast("RabbitSubscriber", handler)
319 if _is_handler_matches(
320 handler,
321 incoming.routing_key,
322 incoming.headers,
323 cmd.exchange,
324 ):
325 with anyio.fail_after(cmd.timeout):
326 return await self._execute_handler(incoming, handler)
328 raise SubscriberNotFound
330 async def _execute_handler(
331 self,
332 msg: PatchedMessage,
333 handler: "RabbitSubscriber",
334 ) -> "PatchedMessage":
335 result = await handler.process_message(msg)
336 return await build_message(
337 routing_key=msg.routing_key,
338 message=result.body,
339 headers=result.headers,
340 correlation_id=result.correlation_id,
341 serializer=self.broker.config.fd_config._serializer,
342 codec=self.codec,
343 id_generator=self.broker.config.id_generator,
344 )
347def _is_handler_matches(
348 handler: "RabbitSubscriber",
349 routing_key: str,
350 headers: Optional["Mapping[Any, Any]"] = None,
351 exchange: Optional["RabbitExchange"] = None,
352) -> bool:
353 headers = headers or {}
354 exchange = RabbitExchange.validate(exchange)
356 if handler.exchange.name != exchange.name:
357 return False
359 if handler.exchange.type == ExchangeType.DIRECT:
360 return handler.routing() == routing_key
362 if handler.exchange.type == ExchangeType.FANOUT:
363 return True
365 if handler.exchange.type == ExchangeType.TOPIC:
366 return apply_pattern(handler.routing(), routing_key)
368 if handler.exchange.type == ExchangeType.HEADERS:
369 queue_headers = (handler.queue.bind_arguments or {}).copy()
371 if not queue_headers: 371 ↛ 372line 371 didn't jump to line 372 because the condition on line 371 was never true
372 return True
374 match_rule = queue_headers.pop("x-match", "all")
376 full_match = True
377 is_headers_empty = True
378 for k, v in queue_headers.items():
379 if headers.get(k) != v:
380 full_match = False
381 else:
382 is_headers_empty = False
384 if is_headers_empty:
385 return False
387 return full_match or (match_rule == "any")
389 raise AssertionError
392def apply_pattern(pattern: str, current: str) -> bool:
393 """Apply a pattern to a routing key."""
394 words = current.split(".") if current else []
395 pattern_words = pattern.split(".") if pattern else []
397 # matched[i] - the pattern words seen so far match the first i routing key words
398 matched = [True] + [False] * len(words)
399 for pattern_word in pattern_words:
400 if pattern_word == "#":
401 # `#` takes zero or more words, so it keeps every prefix matched before it
402 for i in range(1, len(matched)):
403 matched[i] = matched[i] or matched[i - 1]
405 else:
406 for i in range(len(words), 0, -1):
407 matched[i] = matched[i - 1] and pattern_word in {"*", words[i - 1]}
408 matched[0] = False
410 return matched[-1]