Coverage for tests/brokers/base/publish_command.py: 98%

60 statements  

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

1from collections import Counter 

2from collections.abc import Awaitable, Callable, Sequence 

3from typing import Any 

4 

5import pytest 

6 

7from faststream import BaseMiddleware, Context, Response 

8from faststream.response import ensure_response 

9from faststream.response.response import ( 

10 BatchPublishCommand, 

11 PublishCommand, 

12) 

13 

14from .basic import BaseTestcaseConfig 

15 

16 

17class BasePublishCommandTestcase: 

18 publish_command_cls: type[PublishCommand] 

19 

20 def test_simple_response(self) -> None: 

21 response = ensure_response(1) 

22 cmd = self.publish_command_cls.from_cmd(response.as_publish_command()) 

23 assert cmd.body == 1 

24 

25 def test_base_response_class(self) -> None: 

26 response = ensure_response(Response(body=1, headers={"1": 1})) 

27 cmd = self.publish_command_cls.from_cmd(response.as_publish_command()) 

28 assert cmd.body == 1 

29 assert cmd.headers == {"1": 1} 

30 

31 

32class BatchPublishCommandTestcase(BasePublishCommandTestcase): 

33 publish_command_cls: type[BatchPublishCommand] 

34 

35 @pytest.mark.parametrize( 

36 ("data", "expected_body"), 

37 ( 

38 pytest.param(None, (), id="None Response"), 

39 pytest.param((), (), id="Empty Sequence"), 

40 pytest.param("123", ("123",), id="String Response"), 

41 pytest.param("", ("",), id="Empty String Response"), 

42 pytest.param(b"", (b"",), id="Empty Bytes Response"), 

43 pytest.param([1, 2, 3], (1, 2, 3), id="Sequence Data"), 

44 pytest.param( 

45 [0, 1, 2], 

46 (0, 1, 2), 

47 id="Sequence Data with False first element", 

48 ), 

49 ), 

50 ) 

51 def test_batch_response(self, data: Any, expected_body: Any) -> None: 

52 response = ensure_response(data) 

53 cmd = self.publish_command_cls.from_cmd( 

54 response.as_publish_command(), 

55 batch=True, 

56 ) 

57 assert cmd.batch_bodies == expected_body 

58 

59 def test_batch_bodies_setter(self) -> None: 

60 response = ensure_response(None) 

61 cmd = self.publish_command_cls.from_cmd( 

62 response.as_publish_command(), 

63 batch=True, 

64 ) 

65 cmd.batch_bodies = (1, 2, 3) 

66 

67 assert cmd.batch_bodies == (1, 2, 3) 

68 assert cmd.body == 1 

69 assert cmd.extra_bodies == (2, 3) 

70 

71 def test_batch_bodies_empty_setter(self) -> None: 

72 response = ensure_response((1, 2, 3)) 

73 cmd = self.publish_command_cls.from_cmd( 

74 response.as_publish_command(), 

75 batch=True, 

76 ) 

77 cmd.batch_bodies = () 

78 

79 assert cmd.batch_bodies == () 

80 assert cmd.body is None 

81 assert cmd.extra_bodies == () 

82 

83 

84BODY_A, BODY_B, BODY_C = "body-A", "body-B", "body-C" 

85 

86 

87def reverse(bodies: Sequence[Any]) -> tuple[Any, ...]: 

88 return tuple(reversed(bodies)) 

89 

90 

91def drop_first(bodies: Sequence[Any]) -> tuple[Any, ...]: 

92 return tuple(bodies[1:]) 

93 

94 

95def keep(bodies: Sequence[Any]) -> tuple[Any, ...]: 

96 return tuple(bodies) 

97 

98 

99def dedup(bodies: Sequence[Any]) -> tuple[Any, ...]: 

100 return tuple(dict.fromkeys(bodies)) 

101 

102 

103SHUFFLED = ( 

104 (BODY_A, b"1"), 

105 (BODY_C, b"2"), 

106 (BODY_B, b"3"), 

107 (BODY_A, b"4"), 

108 (BODY_B, b"5"), 

109 (BODY_A, b"6"), 

110 (BODY_A, b"7"), 

111) 

112 

113# (original (body, key) pairs, batch_bodies mutation, expected (body, key) pairs) 

114KEY_ALIGNMENT_CASES = ( 

115 pytest.param( 

116 ((BODY_A, b"key-A"), (BODY_B, b"key-B")), 

117 reverse, 

118 ((BODY_B, b"key-B"), (BODY_A, b"key-A")), 

119 id="reversed", 

120 ), 

121 pytest.param( 

122 ((BODY_A, b"key-A"), (BODY_B, b"key-B"), (BODY_C, b"key-C")), 

123 drop_first, 

124 ((BODY_B, b"key-B"), (BODY_C, b"key-C")), 

125 id="first-dropped", 

126 ), 

127 pytest.param( 

128 ((BODY_A, b"key-A"), (BODY_B, b"key-B"), (BODY_B, b"key-B")), 

129 keep, 

130 ((BODY_A, b"key-A"), (BODY_B, b"key-B"), (BODY_B, b"key-B")), 

131 id="untouched-with-duplicates", 

132 ), 

133 pytest.param( 

134 ((BODY_A, b"key-A"), (BODY_B, b"key-B"), (BODY_B, b"key-B")), 

135 reverse, 

136 ((BODY_B, b"key-B"), (BODY_B, b"key-B"), (BODY_A, b"key-A")), 

137 id="reversed-with-duplicates", 

138 ), 

139 pytest.param( 

140 ((BODY_A, b"key-1"), (BODY_A, b"key-2"), (BODY_B, b"key-3")), 

141 dedup, 

142 ((BODY_A, b"key-1"), (BODY_B, b"key-3")), 

143 id="deduplicated", 

144 ), 

145 pytest.param( 

146 ((BODY_A, None), (BODY_B, b"key-B"), (BODY_B, None)), 

147 reverse, 

148 ((BODY_B, b""), (BODY_B, b"key-B"), (BODY_A, b"")), 

149 id="reversed-with-duplicates-and-none-keys", 

150 ), 

151 pytest.param(SHUFFLED, keep, SHUFFLED, id="untouched-shuffled"), 

152 # Every pair below is one of the original ones, but identical bodies keep their 

153 # keys in the original relative order instead of being reversed along with them -- 

154 # equal bodies are indistinguishable, so any of their keys is a valid match. 

155 pytest.param( 

156 SHUFFLED, 

157 reverse, 

158 ( 

159 (BODY_A, b"1"), 

160 (BODY_A, b"4"), 

161 (BODY_B, b"3"), 

162 (BODY_A, b"6"), 

163 (BODY_B, b"5"), 

164 (BODY_C, b"2"), 

165 (BODY_A, b"7"), 

166 ), 

167 id="reversed-shuffled", 

168 ), 

169 pytest.param( 

170 SHUFFLED, 

171 drop_first, 

172 SHUFFLED[1:], 

173 id="first-dropped-shuffled", 

174 marks=pytest.mark.xfail( 

175 reason="Identical bodies can't be traced back to their keys once a body is removed, since keys are not unique.", 

176 ), 

177 ), 

178) 

179 

180 

181class BatchKeysTestcase(BaseTestcaseConfig[Any]): 

182 """Per-message keys must keep following their bodies when `batch_bodies` is replaced. 

183 

184 Applies to Kafka-like brokers, where every batch element carries its own key. 

185 """ 

186 

187 publish_command_cls: type[BatchPublishCommand] 

188 publish_message_cls: type[Any] 

189 

190 @staticmethod 

191 def get_message_key(raw_message: Any) -> bytes: 

192 key: bytes = raw_message.key 

193 return key 

194 

195 @pytest.mark.asyncio() 

196 @pytest.mark.parametrize( 

197 ("pairs", "mutate", "expected"), 

198 KEY_ALIGNMENT_CASES, 

199 ) 

200 async def test_publish_middleware_keeps_keys_aligned( 

201 self, 

202 queue: str, 

203 pairs: Any, 

204 mutate: Any, 

205 expected: Any, 

206 ) -> None: 

207 publish_command_cls = self.publish_command_cls 

208 

209 class MutatingMiddleware(BaseMiddleware): 

210 async def publish_scope( 

211 self, call_next: Callable[[Any], Awaitable[Any]], cmd: Any 

212 ) -> Any: 

213 if isinstance(cmd, publish_command_cls): 213 ↛ 215line 213 didn't jump to line 215 because the condition on line 213 was always true

214 cmd.batch_bodies = mutate(cmd.batch_bodies) 

215 return await call_next(cmd) 

216 

217 broker = self.get_broker(apply_types=True, middlewares=(MutatingMiddleware,)) 

218 

219 received: list[Any] = [] 

220 

221 @broker.subscriber(queue, batch=True) 

222 async def handler(msgs: Any, raw: Any = Context("message")) -> None: 

223 received.extend( 

224 zip( 

225 msgs, 

226 (self.get_message_key(m) for m in raw.raw_message), 

227 strict=True, 

228 ), 

229 ) 

230 

231 async with self.patch_broker(broker) as br: 

232 await br.start() 

233 await br.publish_batch( 

234 *(self.publish_message_cls(body, key=key) for body, key in pairs), 

235 topic=queue, 

236 ) 

237 assert Counter(received) == Counter(expected)