Coverage for tests/asgi/multibroker/test_try_it_out.py: 98%

107 statements  

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

1import subprocess 

2import sys 

3from typing import Any 

4from unittest.mock import MagicMock 

5 

6import pytest 

7from starlette.testclient import TestClient 

8 

9from faststream.asgi import AsgiFastStream, AsyncAPIRoute 

10from faststream.asgi.factories.asyncapi.try_it_out import ( 

11 TryItOutProcessor, 

12 _iter_broker_channels, 

13 _iter_broker_destinations, 

14) 

15from faststream.kafka import KafkaBroker, TestKafkaBroker 

16from tests.marks import ( 

17 require_aiokafka, 

18 require_aiopika, 

19 require_confluent, 

20 require_mqtt, 

21 require_nats, 

22 require_redis, 

23) 

24 

25 

26def _payload(channel: str, body: Any) -> dict[str, Any]: 

27 return { 

28 "channelName": channel, 

29 "message": { 

30 "operation_id": "op", 

31 "operation_type": "subscribe", 

32 "message": body, 

33 }, 

34 "options": {"sendToRealBroker": False}, 

35 } 

36 

37 

38class TestIterDestinations: 

39 def test_kafka_subscriber_destinations(self) -> None: 

40 broker = KafkaBroker() 

41 

42 @broker.subscriber("topic-a") 

43 async def handler_a(msg: Any) -> None: ... 

44 

45 @broker.subscriber("topic-b") 

46 async def handler_b(msg: Any) -> None: ... 

47 

48 destinations = _iter_broker_destinations(broker) 

49 assert "topic-a" in destinations 

50 assert "topic-b" in destinations 

51 

52 def test_kafka_subscriber_channels(self) -> None: 

53 broker = KafkaBroker() 

54 

55 @broker.subscriber("topic-a") 

56 async def handler_a(msg: Any) -> None: ... 

57 

58 channels = _iter_broker_channels(broker) 

59 assert "topic-a:HandlerA" in channels 

60 

61 

62class TestMultiBrokerDispatch: 

63 @pytest.mark.asyncio() 

64 async def test_routes_to_correct_broker_by_channel(self) -> None: 

65 kafka_1 = KafkaBroker() 

66 kafka_2 = KafkaBroker() 

67 

68 kafka_1_mock = MagicMock() 

69 kafka_2_mock = MagicMock() 

70 

71 @kafka_1.subscriber("kafka-1-only") 

72 async def kh1(msg: Any) -> None: 

73 kafka_1_mock(msg) 

74 

75 @kafka_2.subscriber("kafka-2-only") 

76 async def kh2(msg: Any) -> None: 

77 kafka_2_mock(msg) 

78 

79 app = AsgiFastStream( 

80 kafka_1, 

81 kafka_2, 

82 asyncapi_path=AsyncAPIRoute("/asyncapi"), 

83 ) 

84 

85 async with TestKafkaBroker(kafka_1, kafka_2): 

86 with TestClient(app) as client: 

87 r = client.post("/asyncapi/try", json=_payload("kafka-1-only", "x")) 

88 assert r.status_code == 200, r.json() 

89 r = client.post("/asyncapi/try", json=_payload("kafka-2-only", "y")) 

90 assert r.status_code == 200, r.json() 

91 

92 kafka_1_mock.assert_called_once_with("x") 

93 kafka_2_mock.assert_called_once_with("y") 

94 

95 @pytest.mark.asyncio() 

96 async def test_collision_short_channel_first_match_wins(self) -> None: 

97 """Short channel names keep first-match compatibility.""" 

98 kafka_1 = KafkaBroker() 

99 kafka_2 = KafkaBroker() 

100 

101 kafka_1_mock = MagicMock() 

102 kafka_2_mock = MagicMock() 

103 

104 @kafka_1.subscriber("shared") 

105 async def kh1(msg: Any) -> None: 

106 kafka_1_mock(msg) 

107 

108 @kafka_2.subscriber("shared") 

109 async def kh2(msg: Any) -> None: 

110 kafka_2_mock(msg) 

111 

112 app = AsgiFastStream( 

113 kafka_1, 

114 kafka_2, 

115 asyncapi_path=AsyncAPIRoute("/asyncapi"), 

116 ) 

117 

118 async with TestKafkaBroker(kafka_1, kafka_2): 

119 with TestClient(app) as client: 

120 r = client.post("/asyncapi/try", json=_payload("shared", "hi")) 

121 assert r.status_code == 200, r.json() 

122 

123 kafka_1_mock.assert_called_once_with("hi") 

124 kafka_2_mock.assert_not_called() 

125 

126 @pytest.mark.asyncio() 

127 async def test_collision_full_channel_routes_to_exact_broker(self) -> None: 

128 kafka_1 = KafkaBroker() 

129 kafka_2 = KafkaBroker() 

130 

131 kafka_1_mock = MagicMock() 

132 kafka_2_mock = MagicMock() 

133 

134 @kafka_1.subscriber("shared") 

135 async def kh1(msg: Any) -> None: 

136 kafka_1_mock(msg) 

137 

138 @kafka_2.subscriber("shared") 

139 async def kh2(msg: Any) -> None: 

140 kafka_2_mock(msg) 

141 

142 app = AsgiFastStream( 

143 kafka_1, 

144 kafka_2, 

145 asyncapi_path=AsyncAPIRoute("/asyncapi"), 

146 ) 

147 

148 async with TestKafkaBroker(kafka_1, kafka_2): 

149 with TestClient(app) as client: 

150 r = client.post("/asyncapi/try", json=_payload("shared:Kh2", "hi")) 

151 assert r.status_code == 200, r.json() 

152 

153 kafka_2_mock.assert_called_once_with("hi") 

154 kafka_1_mock.assert_not_called() 

155 

156 @pytest.mark.asyncio() 

157 async def test_channel_not_found_anywhere_returns_404(self) -> None: 

158 kafka_1 = KafkaBroker() 

159 kafka_2 = KafkaBroker() 

160 

161 app = AsgiFastStream( 

162 kafka_1, 

163 kafka_2, 

164 asyncapi_path=AsyncAPIRoute("/asyncapi"), 

165 ) 

166 

167 async with TestKafkaBroker(kafka_1, kafka_2): 

168 with TestClient(app) as client: 

169 r = client.post("/asyncapi/try", json=_payload("missing", "x")) 

170 

171 assert r.status_code == 404 

172 

173 @pytest.mark.asyncio() 

174 async def test_single_broker_backcompat(self) -> None: 

175 kafka = KafkaBroker() 

176 mock = MagicMock() 

177 

178 @kafka.subscriber("queue") 

179 async def h(msg: Any) -> None: 

180 mock(msg) 

181 

182 app = AsgiFastStream(kafka, asyncapi_path=AsyncAPIRoute("/asyncapi")) 

183 

184 async with TestKafkaBroker(kafka): 

185 with TestClient(app) as client: 

186 r = client.post("/asyncapi/try", json=_payload("queue", "hi")) 

187 assert r.status_code == 200, r.json() 

188 

189 mock.assert_called_once_with("hi") 

190 

191 

192class TestProcessorUnit: 

193 def test_empty_brokers_rejected(self) -> None: 

194 with pytest.raises(ValueError, match="at least one broker"): 

195 TryItOutProcessor() 

196 

197 

198@pytest.mark.parametrize( 

199 ("package", "broker"), 

200 ( 

201 pytest.param( 

202 "faststream.kafka", 

203 "KafkaBroker", 

204 marks=(pytest.mark.kafka(), require_aiokafka), 

205 ), 

206 pytest.param( 

207 "faststream.confluent", 

208 "KafkaBroker", 

209 marks=(pytest.mark.confluent(), require_confluent), 

210 ), 

211 pytest.param( 

212 "faststream.nats", 

213 "NatsBroker", 

214 marks=(pytest.mark.nats(), require_nats), 

215 ), 

216 pytest.param( 

217 "faststream.rabbit", 

218 "RabbitBroker", 

219 marks=(pytest.mark.rabbit(), require_aiopika), 

220 ), 

221 pytest.param( 

222 "faststream.redis", 

223 "RedisBroker", 

224 marks=(pytest.mark.redis(), require_redis), 

225 ), 

226 pytest.param( 

227 "faststream.mqtt", 

228 "MQTTBroker", 

229 marks=(pytest.mark.mqtt(), require_mqtt), 

230 ), 

231 ), 

232) 

233def test_test_broker_found_without_importing_it(package: str, broker: str) -> None: 

234 # a fresh interpreter: this session has imported every TestBroker already 

235 code = ( 

236 f"from {package} import {broker}\n" 

237 "from faststream._internal.testing.broker import find_test_broker\n" 

238 f"print(find_test_broker({broker}()).__module__)" 

239 ) 

240 

241 result = subprocess.run( 

242 [sys.executable, "-c", code], 

243 stdout=subprocess.PIPE, 

244 text=True, 

245 check=True, 

246 ) 

247 

248 assert result.stdout.strip() == f"{package}.testing" 

249 

250 

251@pytest.mark.kafka() 

252@require_aiokafka 

253def test_broker_subclass_finds_its_own_test_broker() -> None: 

254 # a fresh interpreter: the registry is global and outlives the test 

255 code = ( 

256 "from faststream.kafka import KafkaBroker, TestKafkaBroker\n" 

257 "from faststream._internal.testing.broker import find_test_broker\n" 

258 "class MyBroker(KafkaBroker): ...\n" 

259 "class TestMyBroker(TestKafkaBroker, broker=MyBroker): ...\n" 

260 "print(find_test_broker(MyBroker()).__name__)\n" 

261 "print(find_test_broker(KafkaBroker()).__name__)" 

262 ) 

263 

264 result = subprocess.run( 

265 [sys.executable, "-c", code], 

266 stdout=subprocess.PIPE, 

267 text=True, 

268 check=True, 

269 ) 

270 

271 assert result.stdout.split() == ["TestMyBroker", "TestKafkaBroker"]