File: test_web_client.py

package info (click to toggle)
rtsp-to-webrtc 0.6.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 240 kB
  • sloc: python: 1,126; makefile: 7; sh: 5
file content (496 lines) | stat: -rw-r--r-- 15,652 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
from __future__ import annotations

import base64
from collections.abc import Awaitable, Callable
from typing import Any, cast

import aiohttp
import pytest
from aiohttp import ClientSession, web
from aiohttp.test_utils import TestClient, TestServer

from rtsp_to_webrtc.exceptions import ResponseError
from rtsp_to_webrtc.web_client import WebClient

OFFER_SDP = "v=0\r\no=carol 28908764872 28908764872 IN IP4 100.3.6.6\r\n..."
ANSWER_SDP = "v=0\r\no=bob 2890844730 2890844730 IN IP4 h.example.com\r\n..."
ANSWER_PAYLOAD = base64.b64encode(ANSWER_SDP.encode("utf-8")).decode("utf-8")
RTSP_URL = "rtsp://example"
STREAM_1 = {
    "name": "test video",
    "channels": {
        "0": {
            "name": "ch1",
            "url": RTSP_URL,
        },
        "1": {
            "name": "ch2",
            "url": RTSP_URL,
        },
    },
}
STREAM_2 = {
    "name": "test video #2",
    "channels": {
        "0": {
            "name": "ch1",
            "url": "rtsp://example.com",
        },
        "1": {
            "name": "ch2",
            "url": "rtsp://example.biz",
        },
    },
}
CHANNEL = {
    "name": "ch1",
    "url": "rtsp://example",
    "on_demand": False,
    "debug": False,
    "status": 0,
}

SUCCESS_RESPONSE = {
    "status": 1,
    "payload": "success",
}


@pytest.fixture(autouse=True)
def setup_handler(
    app: web.Application,
    request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
) -> None:
    app.router.add_get("/streams", request_handler)
    app.router.add_post("/stream/{stream_id}/add", request_handler)
    app.router.add_post("/stream/{stream_id}/edit", request_handler)
    app.router.add_get("/stream/{stream_id}/reload", request_handler)
    app.router.add_get("/stream/{stream_id}/info", request_handler)
    app.router.add_get("/stream/{stream_id}/delete", request_handler)
    app.router.add_post("/stream/{stream_id}/channel/{channel_id}/add", request_handler)
    app.router.add_post(
        "/stream/{stream_id}/channel/{channel_id}/edit", request_handler
    )
    app.router.add_get(
        "/stream/{stream_id}/channel/{channel_id}/reload", request_handler
    )
    app.router.add_get("/stream/{stream_id}/channel/{channel_id}/info", request_handler)
    app.router.add_get(
        "/stream/{stream_id}/channel/{channel_id}/codec", request_handler
    )
    app.router.add_get(
        "/stream/{stream_id}/channel/{channel_id}/delete", request_handler
    )
    app.router.add_post(
        "/stream/{stream_id}/channel/{channel_id}/webrtc", request_handler
    )


@pytest.fixture
def cli(
    loop: Any,
    app: web.Application,
    aiohttp_client: Callable[[web.Application], Awaitable[TestClient]],
) -> TestClient:
    """Creates a fake aiohttp client."""
    client = loop.run_until_complete(aiohttp_client(app))
    return cast(TestClient, client)


async def test_list_streams(
    cli: TestClient,
    request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
) -> None:
    """Test List Streams calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(
        aiohttp.web.json_response(
            {
                "status": 1,
                "payload": {
                    "demo1": STREAM_1,
                    "demo2": STREAM_2,
                },
            }
        )
    )

    client = WebClient(cast(ClientSession, cli))
    streams = await client.list_streams()
    assert len(streams) == 2
    assert streams == {
        "demo1": STREAM_1,
        "demo2": STREAM_2,
    }
    requests = cli.server.app["request"]
    assert requests == ["/streams"]


async def test_list_streams_failure(
    cli: TestClient,
    request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
) -> None:
    """Test List Streams calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.Response(status=502))

    client = WebClient(cast(ClientSession, cli))
    with pytest.raises(ResponseError, match=r"server failure.*"):
        await client.list_streams()


async def test_list_streams_status_failure(cli: TestClient) -> None:
    """Test failure response from RTSPtoWebRTC server."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(
        aiohttp.web.json_response({"status": 0, "payload": "a message"})
    )

    client = WebClient(cast(ClientSession, cli))
    with pytest.raises(ResponseError, match=r"server failure:.*a message.*"):
        await client.list_streams()


async def test_list_streams_missing_payload(cli: TestClient) -> None:
    """Test failure response from RTSPtoWebRTC server."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response({"status": 1}))

    client = WebClient(cast(ClientSession, cli))
    with pytest.raises(ResponseError, match=r"server missing payload.*"):
        await client.list_streams()


async def test_list_streams_malformed_payload(cli: TestClient) -> None:
    """Test failure response from RTSPtoWebRTC server."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(
        aiohttp.web.json_response({"status": 1, "payload": ["list"]})
    )

    client = WebClient(cast(ClientSession, cli))
    with pytest.raises(ResponseError, match=r"malformed payload.*"):
        await client.list_streams()


async def test_add_stream(cli: TestClient) -> None:
    """Test Add Streams calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.add_stream("demo1", data=STREAM_1)
    requests = cli.server.app["request"]
    assert requests == ["/stream/demo1/add"]


async def test_update_stream(cli: TestClient) -> None:
    """Test Update Streams calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.update_stream("demo1", data=STREAM_1)
    requests = cli.server.app["request"]
    assert requests == ["/stream/demo1/edit"]


async def test_reload_stream(cli: TestClient) -> None:
    """Test Reload Streams calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.reload_stream("demo1")
    requests = cli.server.app["request"]
    assert requests == ["/stream/demo1/reload"]


async def test_get_stream_info(
    cli: TestClient,
    request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
) -> None:
    """Test Get Stream Info calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(
        aiohttp.web.json_response(
            {
                "status": 1,
                "payload": STREAM_1,
            }
        )
    )

    client = WebClient(cast(ClientSession, cli))
    data = await client.get_stream_info("demo1")
    assert data == STREAM_1
    requests = cli.server.app["request"]
    assert requests == ["/stream/demo1/info"]


async def test_delete_stream(cli: TestClient) -> None:
    """Test Delete Streams calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.delete_stream("demo1")
    requests = cli.server.app["request"]
    assert requests == ["/stream/demo1/delete"]


async def test_add_channel(cli: TestClient) -> None:
    """Test Add channel calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.add_channel("demo1", "0", CHANNEL)
    requests = cli.server.app["request"]
    assert len(requests) == 1


async def test_update_channel(cli: TestClient) -> None:
    """Test Update channel calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.update_channel("demo1", "0", CHANNEL)
    requests = cli.server.app["request"]
    assert len(requests) == 1


async def test_reload_channel(cli: TestClient) -> None:
    """Test Reload channel calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.reload_channel("demo1", "0")
    requests = cli.server.app["request"]
    assert len(requests) == 1


async def test_get_channel_info(
    cli: TestClient,
    request_handler: Callable[[aiohttp.web.Request], Awaitable[aiohttp.web.Response]],
) -> None:
    """Test Get Stream Info calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(
        aiohttp.web.json_response(
            {
                "status": 1,
                "payload": CHANNEL,
            }
        )
    )

    client = WebClient(cast(ClientSession, cli))
    data = await client.get_channel_info("demo1", "0")
    assert data == CHANNEL


async def test_delete_channel(cli: TestClient) -> None:
    """Test Reload channel calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))

    client = WebClient(cast(ClientSession, cli))
    await client.delete_channel("demo1", "0")
    requests = cli.server.app["request"]
    assert len(requests) == 1


async def test_webrtc(cli: TestClient) -> None:
    """Test List Streams calls."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))

    client = WebClient(cast(ClientSession, cli))
    answer = await client.webrtc("demo1", "0", OFFER_SDP)
    assert answer == ANSWER_SDP
    requests = cli.server.app["request"]
    assert len(requests) == 1


async def test_webrtc_failure(cli: TestClient) -> None:
    """Test a failure talking to RTSPtoWebRTC server."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(aiohttp.web.Response(status=502))

    client = WebClient(cast(ClientSession, cli))
    with pytest.raises(ResponseError, match=r"server failure.*"):
        await client.webrtc("demo1", "0", OFFER_SDP)


async def test_server_failure_with_error(cli: TestClient) -> None:
    """Test invalid response from RTSPtoWebRTC server."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].append(
        aiohttp.web.json_response({"status": 1, "payload": "a message"}, status=502)
    )

    client = WebClient(cast(ClientSession, cli))
    with pytest.raises(ResponseError, match=r"server failure:.*a message.*"):
        await client.webrtc("demo1", "0", OFFER_SDP)


async def test_heartbeat(cli: TestClient) -> None:
    """Test successful response from RTSPtoWebRTC server."""
    assert isinstance(cli.server, TestServer)
    cli.server.app["response"].extend(
        [
            aiohttp.web.Response(status=200),
            aiohttp.web.Response(status=502),
            aiohttp.web.Response(status=404),
            aiohttp.web.Response(status=200),
        ]
    )

    client = WebClient(cast(ClientSession, cli))

    await client.heartbeat()

    with pytest.raises(ResponseError):
        await client.heartbeat()

    with pytest.raises(ResponseError):
        await client.heartbeat()

    await client.heartbeat()


async def test_offer(cli: TestClient) -> None:
    """Test Offer call."""
    assert isinstance(cli.server, TestServer)
    # List call
    cli.server.app["response"].append(
        aiohttp.web.json_response(
            {
                "status": 1,
                "payload": {},
            }
        )
    )
    # Add stream
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
    # Offer
    cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))

    client = WebClient(cast(ClientSession, cli))

    answer_sdp = await client.offer(OFFER_SDP, RTSP_URL)
    assert answer_sdp == ANSWER_SDP
    requests = cli.server.app["request"]
    assert requests == [
        "/streams",
        "/stream/Y7L7SZDOZXHIYFHESPL7YPKXHI======/add",
        "/stream/Y7L7SZDOZXHIYFHESPL7YPKXHI======/channel/0/webrtc",
    ]


async def test_offer_update_stream(cli: TestClient) -> None:
    """Test Offer updates an existing stream."""
    assert isinstance(cli.server, TestServer)
    # List call
    cli.server.app["response"].append(
        aiohttp.web.json_response(
            {
                "status": 1,
                "payload": {
                    "demo1": STREAM_1,
                },
            }
        )
    )
    # Edit stream
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
    # Offer
    cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))

    client = WebClient(cast(ClientSession, cli))

    answer_sdp = await client.offer_stream_id("demo1", OFFER_SDP, f"{RTSP_URL}?example")
    assert answer_sdp == ANSWER_SDP
    requests = cli.server.app["request"]
    assert requests == [
        "/streams",
        "/stream/demo1/edit",
        "/stream/demo1/channel/0/webrtc",
    ]


async def test_offer_channel_data(cli: TestClient) -> None:
    """Test Offer updates an existing stream."""
    assert isinstance(cli.server, TestServer)
    # List call
    cli.server.app["response"].append(
        aiohttp.web.json_response(
            {
                "status": 1,
                "payload": {},
            }
        )
    )
    # Add stream
    cli.server.app["response"].append(aiohttp.web.json_response(SUCCESS_RESPONSE))
    # Offer
    cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))

    client = WebClient(cast(ClientSession, cli))

    answer_sdp = await client.offer_stream_id(
        "demo1", OFFER_SDP, RTSP_URL, channel_data={"insecure_skip_verify": True}
    )
    assert answer_sdp == ANSWER_SDP
    requests = cli.server.app["request"]
    assert requests == [
        "/streams",
        "/stream/demo1/add",
        "/stream/demo1/channel/0/webrtc",
    ]
    assert cli.server.app["request-json"] == [
        {
            "channels": {
                "0": {
                    "insecure_skip_verify": True,
                    "name": "ch1",
                    "url": "rtsp://example",
                }
            },
            "name": "demo1",
        }
    ]


async def test_offer_update_no_op(cli: TestClient) -> None:
    """Test that an offer is a no-up when stream matches."""
    assert isinstance(cli.server, TestServer)
    # List call
    cli.server.app["response"].append(
        aiohttp.web.json_response(
            {
                "status": 1,
                "payload": {
                    "demo1": STREAM_1,
                },
            }
        )
    )
    # Offer
    cli.server.app["response"].append(aiohttp.web.Response(body=ANSWER_PAYLOAD))

    client = WebClient(cast(ClientSession, cli))

    answer_sdp = await client.offer_stream_id("demo1", OFFER_SDP, RTSP_URL)
    assert answer_sdp == ANSWER_SDP
    requests = cli.server.app["request"]
    assert requests == [
        "/streams",
        "/stream/demo1/channel/0/webrtc",
    ]