Debian Codegraph @

tests/test_web_client.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import base64
4 from collections.abc import Awaitable, Callable
5 from typing import Any, cast
6
7 import aiohttp
8 import pytest
9 from aiohttp import ClientSession, web
10 from aiohttp.test_utils import TestClient, TestServer
11
12 from rtsp_to_webrtc.exceptions import ResponseError
13 from rtsp_to_webrtc.web_client import WebClient
14
15 OFFER_SDP = "v=0\r\no=carol 28908764872 28908764872 IN IP4 100.3.6.6\r\n..."
16 ANSWER_SDP = "v=0\r\no=bob 2890844730 2890844730 IN IP4 h.example.com\r\n..."
17 ANSWER_PAYLOAD = base64.b64encode(ANSWER_SDP.encode("utf-8")).decode("utf-8")
18 RTSP_URL = "rtsp://example"
19 STREAM_1 = {
20 "name": "test video",
21 "channels": {
22 "0": {
23 "name": "ch1",
24 "url": RTSP_URL,
25 },
26 "1": {
27 "name": "ch2",
28 "url": RTSP_URL,
29 },
30 },
31 }
32 STREAM_2 = {
33 "name": "test video #2",
34 "channels": {
35 "0": {
36 "name": "ch1",
37 "url": "rtsp://example.com",
38 },
39 "1": {
40 "name": "ch2",
41 "url": "rtsp://example.biz",
42 },
43 },
44 }
45 CHANNEL = {
46 "name": "ch1",
47 "url": "rtsp://example",
48 "on_demand": False,
49 "debug": False,
50 "status": 0,
51 }
52
53 SUCCESS_RESPONSE = {
54 "status": 1,
55 "payload": "success",
56 }
57
58
59 @pytest.fixture(autouse=True)
60 def setup_handler(
61 app: web.Application,
62 request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
63 ) -> None:
64 app.router.add_get("/streams", request_handler)
65 app.router.add_post("/stream/{stream_id}/add", request_handler)
66 app.router.add_post("/stream/{stream_id}/edit", request_handler)
67 app.router.add_get("/stream/{stream_id}/reload", request_handler)
68 app.router.add_get("/stream/{stream_id}/info", request_handler)
69 app.router.add_get("/stream/{stream_id}/delete", request_handler)
70 app.router.add_post("/stream/{stream_id}/channel/{channel_id}/add", request_handler)
71 app.router.add_post(
72 "/stream/{stream_id}/channel/{channel_id}/edit", request_handler
73 )
74 app.router.add_get(
75 "/stream/{stream_id}/channel/{channel_id}/reload", request_handler
76 )
77 app.router.add_get("/stream/{stream_id}/channel/{channel_id}/info", request_handler)
78 app.router.add_get(
79 "/stream/{stream_id}/channel/{channel_id}/codec", request_handler
80 )
81 app.router.add_get(
82 "/stream/{stream_id}/channel/{channel_id}/delete", request_handler
83 )
84 app.router.add_post(
85 "/stream/{stream_id}/channel/{channel_id}/webrtc", request_handler
86 )
87
88
89 @pytest.fixture
90 def cli(
91 loop: Any,
92 app: web.Application,
93 aiohttp_client: Callable[[web.Application], Awaitable[TestClient]],
94 ) -> TestClient:
95 """Creates a fake aiohttp client."""
96 client = loop.run_until_complete(aiohttp_client(app))
97 return cast(TestClient, client)
98
99
100 async def test_list_streams(
101 cli: TestClient,
102 request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
103 ) -> None:
104 """Test List Streams calls."""
105 assert isinstance(cli.server, TestServer)
106 cli.server.app["response"].append(
107 aiohttp.web.json_response(
108 {
109 "status": 1,
110 "payload": {
111 "demo1": STREAM_1,
112 "demo2": STREAM_2,
113 },
114 }
115 )
116 )
117
118 client = WebClient(cast(ClientSession, cli))
119 streams = await client.list_streams()
120 assert len(streams) == 2
121 assert streams == {
122 "demo1": STREAM_1,
123 "demo2": STREAM_2,
124 }
125 requests = cli.server.app["request"]
126 assert requests == ["/streams"]
127
128
129 async def test_list_streams_failure(
130 cli: TestClient,
131 request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
132 ) -> None:
133 """Test List Streams calls."""
134 assert isinstance(cli.server, TestServer)
135 cli.server.app["response"].append(aiohttp.web.Response(status=502))
136
137 client = WebClient(cast(ClientSession, cli))
138 with pytest.raises(ResponseError, match=r"server failure.*"):
139 await client.list_streams()
140
141
142 async def test_list_streams_status_failure(cli: TestClient) -> None:
143 """Test failure response from RTSPtoWebRTC server."""
144 assert isinstance(cli.server, TestServer)
145 cli.server.app["response"].append(
146 aiohttp.web.json_response({"status": 0, "payload": "a message"})
147 )
148
149 client = WebClient(cast(ClientSession, cli))
150 with pytest.raises(ResponseError, match=r"server failure:.*a message.*"):
151 await client.list_streams()
152
153
154 async def test_list_streams_missing_payload(cli: TestClient) -> None:
155 """Test failure response from RTSPtoWebRTC server."""
156 assert isinstance(cli.server, TestServer)
157 cli.server.app["response"].append(aiohttp.web.json_response({"status": 1}))
158
159 client = WebClient(cast(ClientSession, cli))
160 with pytest.raises(ResponseError, match=r"server missing payload.*"):
161 await client.list_streams()
162
163
164 async def test_list_streams_malformed_payload(cli: TestClient) -> None:
165 """Test failure response from RTSPtoWebRTC server."""
166 assert isinstance(cli.server, TestServer)
167 cli.server.app["response"].append(
168 aiohttp.web.json_response({"status": 1, "payload": ["list"]})
169 )
170
171 client = WebClient(cast(ClientSession, cli))
172 with pytest.raises(ResponseError, match=r"malformed payload.*"):
173 await client.list_streams()
174
175
176 async def test_add_stream(cli: TestClient) -> None:
177 """Test Add Streams calls."""
178 assert isinstance(cli.server, TestServer)
179 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
180
181 client = WebClient(cast(ClientSession, cli))
182 await client.add_stream("demo1", data=STREAM_1)
183 requests = cli.server.app["request"]
184 assert requests == ["/stream/demo1/add"]
185
186
187 async def test_update_stream(cli: TestClient) -> None:
188 """Test Update Streams calls."""
189 assert isinstance(cli.server, TestServer)
190 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
191
192 client = WebClient(cast(ClientSession, cli))
193 await client.update_stream("demo1", data=STREAM_1)
194 requests = cli.server.app["request"]
195 assert requests == ["/stream/demo1/edit"]
196
197
198 async def test_reload_stream(cli: TestClient) -> None:
199 """Test Reload Streams calls."""
200 assert isinstance(cli.server, TestServer)
201 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
202
203 client = WebClient(cast(ClientSession, cli))
204 await client.reload_stream("demo1")
205 requests = cli.server.app["request"]
206 assert requests == ["/stream/demo1/reload"]
207
208
209 async def test_get_stream_info(
210 cli: TestClient,
211 request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
212 ) -> None:
213 """Test Get Stream Info calls."""
214 assert isinstance(cli.server, TestServer)
215 cli.server.app["response"].append(
216 aiohttp.web.json_response(
217 {
218 "status": 1,
219 "payload": STREAM_1,
220 }
221 )
222 )
223
224 client = WebClient(cast(ClientSession, cli))
225 data = await client.get_stream_info("demo1")
226 assert data == STREAM_1
227 requests = cli.server.app["request"]
228 assert requests == ["/stream/demo1/info"]
229
230
231 async def test_delete_stream(cli: TestClient) -> None:
232 """Test Delete Streams calls."""
233 assert isinstance(cli.server, TestServer)
234 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
235
236 client = WebClient(cast(ClientSession, cli))
237 await client.delete_stream("demo1")
238 requests = cli.server.app["request"]
239 assert requests == ["/stream/demo1/delete"]
240
241
242 async def test_add_channel(cli: TestClient) -> None:
243 """Test Add channel calls."""
244 assert isinstance(cli.server, TestServer)
245 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
246
247 client = WebClient(cast(ClientSession, cli))
248 await client.add_channel("demo1", "0", CHANNEL)
249 requests = cli.server.app["request"]
250 assert len(requests) == 1
251
252
253 async def test_update_channel(cli: TestClient) -> None:
254 """Test Update channel calls."""
255 assert isinstance(cli.server, TestServer)
256 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
257
258 client = WebClient(cast(ClientSession, cli))
259 await client.update_channel("demo1", "0", CHANNEL)
260 requests = cli.server.app["request"]
261 assert len(requests) == 1
262
263
264 async def test_reload_channel(cli: TestClient) -> None:
265 """Test Reload channel calls."""
266 assert isinstance(cli.server, TestServer)
267 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
268
269 client = WebClient(cast(ClientSession, cli))
270 await client.reload_channel("demo1", "0")
271 requests = cli.server.app["request"]
272 assert len(requests) == 1
273
274
275 async def test_get_channel_info(
276 cli: TestClient,
277 request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
278 ) -> None:
279 """Test Get Stream Info calls."""
280 assert isinstance(cli.server, TestServer)
281 cli.server.app["response"].append(
282 aiohttp.web.json_response(
283 {
284 "status": 1,
285 "payload": CHANNEL,
286 }
287 )
288 )
289
290 client = WebClient(cast(ClientSession, cli))
291 data = await client.get_channel_info("demo1", "0")
292 assert data == CHANNEL
293
294
295 async def test_delete_channel(cli: TestClient) -> None:
296 """Test Reload channel calls."""
297 assert isinstance(cli.server, TestServer)
298 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
299
300 client = WebClient(cast(ClientSession, cli))
301 await client.delete_channel("demo1", "0")
302 requests = cli.server.app["request"]
303 assert len(requests) == 1
304
305
306 async def test_webrtc(cli: TestClient) -> None:
307 """Test List Streams calls."""
308 assert isinstance(cli.server, TestServer)
309 cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))
310
311 client = WebClient(cast(ClientSession, cli))
312 answer = await client.webrtc("demo1", "0", OFFER_SDP)
313 assert answer == ANSWER_SDP
314 requests = cli.server.app["request"]
315 assert len(requests) == 1
316
317
318 async def test_webrtc_failure(cli: TestClient) -> None:
319 """Test a failure talking to RTSPtoWebRTC server."""
320 assert isinstance(cli.server, TestServer)
321 cli.server.app["response"].append(aiohttp.web.Response(status=502))
322
323 client = WebClient(cast(ClientSession, cli))
324 with pytest.raises(ResponseError, match=r"server failure.*"):
325 await client.webrtc("demo1", "0", OFFER_SDP)
326
327
328 async def test_server_failure_with_error(cli: TestClient) -> None:
329 """Test invalid response from RTSPtoWebRTC server."""
330 assert isinstance(cli.server, TestServer)
331 cli.server.app["response"].append(
332 aiohttp.web.json_response({"status": 1, "payload": "a message"}, status=502)
333 )
334
335 client = WebClient(cast(ClientSession, cli))
336 with pytest.raises(ResponseError, match=r"server failure:.*a message.*"):
337 await client.webrtc("demo1", "0", OFFER_SDP)
338
339
340 async def test_heartbeat(cli: TestClient) -> None:
341 """Test successful response from RTSPtoWebRTC server."""
342 assert isinstance(cli.server, TestServer)
343 cli.server.app["response"].extend(
344 [
345 aiohttp.web.Response(status=200),
346 aiohttp.web.Response(status=502),
347 aiohttp.web.Response(status=404),
348 aiohttp.web.Response(status=200),
349 ]
350 )
351
352 client = WebClient(cast(ClientSession, cli))
353
354 await client.heartbeat()
355
356 with pytest.raises(ResponseError):
357 await client.heartbeat()
358
359 with pytest.raises(ResponseError):
360 await client.heartbeat()
361
362 await client.heartbeat()
363
364
365 async def test_offer(cli: TestClient) -> None:
366 """Test Offer call."""
367 assert isinstance(cli.server, TestServer)
368 # List call
369 cli.server.app["response"].append(
370 aiohttp.web.json_response(
371 {
372 "status": 1,
373 "payload": {},
374 }
375 )
376 )
377 # Add stream
378 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
379 # Offer
380 cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))
381
382 client = WebClient(cast(ClientSession, cli))
383
384 answer_sdp = await client.offer(OFFER_SDP, RTSP_URL)
385 assert answer_sdp == ANSWER_SDP
386 requests = cli.server.app["request"]
387 assert requests == [
388 "/streams",
389 "/stream/Y7L7SZDOZXHIYFHESPL7YPKXHI======/add",
390 "/stream/Y7L7SZDOZXHIYFHESPL7YPKXHI======/channel/0/webrtc",
391 ]
392
393
394 async def test_offer_update_stream(cli: TestClient) -> None:
395 """Test Offer updates an existing stream."""
396 assert isinstance(cli.server, TestServer)
397 # List call
398 cli.server.app["response"].append(
399 aiohttp.web.json_response(
400 {
401 "status": 1,
402 "payload": {
403 "demo1": STREAM_1,
404 },
405 }
406 )
407 )
408 # Edit stream
409 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
410 # Offer
411 cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))
412
413 client = WebClient(cast(ClientSession, cli))
414
415 answer_sdp = await client.offer_stream_id("demo1", OFFER_SDP, f"{RTSP_URL}?example")
416 assert answer_sdp == ANSWER_SDP
417 requests = cli.server.app["request"]
418 assert requests == [
419 "/streams",
420 "/stream/demo1/edit",
421 "/stream/demo1/channel/0/webrtc",
422 ]
423
424
425 async def test_offer_channel_data(cli: TestClient) -> None:
426 """Test Offer updates an existing stream."""
427 assert isinstance(cli.server, TestServer)
428 # List call
429 cli.server.app["response"].append(
430 aiohttp.web.json_response(
431 {
432 "status": 1,
433 "payload": {},
434 }
435 )
436 )
437 # Add stream
438 cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
439 # Offer
440 cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))
441
442 client = WebClient(cast(ClientSession, cli))
443
444 answer_sdp = await client.offer_stream_id(
445 "demo1", OFFER_SDP, RTSP_URL, channel_data={"insecure_skip_verify": True}
446 )
447 assert answer_sdp == ANSWER_SDP
448 requests = cli.server.app["request"]
449 assert requests == [
450 "/streams",
451 "/stream/demo1/add",
452 "/stream/demo1/channel/0/webrtc",
453 ]
454 assert cli.server.app["request-json"] == [
455 {
456 "channels": {
457 "0": {
458 "insecure_skip_verify": True,
459 "name": "ch1",
460 "url": "rtsp://example",
461 }
462 },
463 "name": "demo1",
464 }
465 ]
466
467
468 async def test_offer_update_no_op(cli: TestClient) -> None:
469 """Test that an offer is a no-up when stream matches."""
470 assert isinstance(cli.server, TestServer)
471 # List call
472 cli.server.app["response"].append(
473 aiohttp.web.json_response(
474 {
475 "status": 1,
476 "payload": {
477 "demo1": STREAM_1,
478 },
479 }
480 )
481 )
482 # Offer
483 cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))
484
485 client = WebClient(cast(ClientSession, cli))
486
487 answer_sdp = await client.offer_stream_id("demo1", OFFER_SDP, RTSP_URL)
488 assert answer_sdp == ANSWER_SDP
489 requests = cli.server.app["request"]
490 assert requests == [
491 "/streams",
492 "/stream/demo1/channel/0/webrtc",
493 ]
494
495
496