Coverage for faststream/_internal/endpoint/publisher/fake.py: 88%

14 statements  

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

1from abc import abstractmethod 

2from collections.abc import Iterable 

3from functools import partial 

4from typing import TYPE_CHECKING, Any 

5 

6from faststream._internal.basic_types import SendableMessage 

7from faststream.response.publish_type import PublishType 

8 

9from .proto import PublisherProto 

10 

11if TYPE_CHECKING: 

12 from faststream._internal.basic_types import AsyncFunc 

13 from faststream._internal.producer import ProducerProto 

14 from faststream._internal.types import PublisherMiddleware 

15 from faststream.response.response import PublishCommand 

16 

17 

18class FakePublisher(PublisherProto): 

19 """Publisher Interface implementation to use as RPC or REPLY TO answer publisher.""" 

20 

21 __slots__ = ("_producer",) 

22 

23 def __init__( 

24 self, 

25 *, 

26 producer: "ProducerProto[Any]", 

27 ) -> None: 

28 """Initialize an object.""" 

29 self._producer = producer 

30 

31 @abstractmethod 

32 def patch_command(self, cmd: "PublishCommand") -> "PublishCommand": 

33 cmd.publish_type = PublishType.REPLY 

34 return cmd 

35 

36 async def _publish( 

37 self, 

38 cmd: "PublishCommand", 

39 *, 

40 _extra_middlewares: Iterable["PublisherMiddleware"], 

41 ) -> Any: 

42 """This method should be called in subscriber flow only.""" 

43 cmd = self.patch_command(cmd) 

44 

45 call: AsyncFunc = self._producer.publish 

46 for m in _extra_middlewares: 

47 call = partial(m, call) 

48 

49 return await call(cmd) 

50 

51 async def publish( 

52 self, 

53 message: SendableMessage, 

54 /, 

55 *, 

56 correlation_id: str | None = None, 

57 ) -> Any | None: 

58 msg = ( 

59 f"`{self.__class__.__name__}` can be used only to publish " 

60 "a response for `reply-to` or `RPC` messages." 

61 ) 

62 raise NotImplementedError(msg) 

63 

64 async def request( 

65 self, 

66 message: "SendableMessage", 

67 /, 

68 *, 

69 correlation_id: str | None = None, 

70 ) -> Any: 

71 msg = ( 

72 f"`{self.__class__.__name__}` can be used only to publish " 

73 "a response for `reply-to` or `RPC` messages." 

74 ) 

75 raise NotImplementedError(msg)