File: test_connection.py

package info (click to toggle)
streamlink 8.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,568 kB
  • sloc: python: 51,299; sh: 184; makefile: 152
file content (807 lines) | stat: -rw-r--r-- 32,024 bytes parent folder | download | duplicates (2)
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
from __future__ import annotations

import contextlib
from contextlib import nullcontext
from dataclasses import dataclass
from functools import partial
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock

import pytest
import trio
from trio.testing import wait_all_tasks_blocked
from trio_websocket import CloseReason, ConnectionClosed, ConnectionTimeout  # type: ignore[import]

from streamlink.compat import ExceptionGroup
from streamlink.webbrowser.cdp.connection import MAX_BUFFER_SIZE, CDPConnection, CDPSession
from streamlink.webbrowser.cdp.devtools.target import SessionID, TargetID
from streamlink.webbrowser.cdp.exceptions import CDPError
from tests.webbrowser.cdp import FakeWebsocketConnection


if TYPE_CHECKING:
    from collections.abc import Generator

    from trio.testing import MockClock

    from streamlink.webbrowser.cdp.connection import CDPEventListener
    from streamlink.webbrowser.cdp.devtools.util import T_JSON_DICT


EPSILON = 0.1


@dataclass
class FakeCommand(str):
    value: str

    def to_json(self) -> T_JSON_DICT:
        return {"value": self.value}

    @classmethod
    def from_json(cls, data: T_JSON_DICT):
        return cls(data["value"])


def fake_command(command: FakeCommand) -> Generator[T_JSON_DICT, T_JSON_DICT, FakeCommand]:
    json: T_JSON_DICT
    json = yield {"method": "Fake.fakeCommand", "params": command.to_json()}
    return FakeCommand.from_json(json)


def bad_command() -> Generator[T_JSON_DICT, T_JSON_DICT, None]:
    yield {"method": "Fake.badCommand", "params": {}}
    yield {}


@dataclass
class FakeEvent:
    value: str

    @classmethod
    def from_json(cls, data: T_JSON_DICT):
        return cls(data["value"])


@pytest.fixture()
async def cdp_connection(websocket_connection: FakeWebsocketConnection):
    try:
        async with CDPConnection.create("ws://localhost:1234/fake") as cdp_connection:
            assert isinstance(cdp_connection, CDPConnection)
            assert not websocket_connection.closed
            try:
                yield cdp_connection
            finally:
                await cdp_connection.aclose()
                assert cdp_connection.sessions == {}
    finally:
        assert websocket_connection.closed


class TestCreateConnection:
    @pytest.mark.trio()
    async def test_success(self, cdp_connection: CDPConnection):
        assert cdp_connection.target_id is None
        assert cdp_connection.session_id is None

    @pytest.mark.trio()
    async def test_failure(self, monkeypatch: pytest.MonkeyPatch):
        fake_connect_websocket_url = AsyncMock(side_effect=ConnectionTimeout)
        monkeypatch.setattr("streamlink.webbrowser.cdp.connection.connect_websocket_url", fake_connect_websocket_url)
        with pytest.raises(ExceptionGroup) as excinfo:
            async with CDPConnection.create("ws://localhost:1234/fake"):
                pass  # pragma: no cover
        assert excinfo.group_contains(ConnectionTimeout)

    @pytest.mark.trio()
    @pytest.mark.parametrize(
        ("timeout", "expected"),
        [
            pytest.param(None, 2, id="Default value of 2 seconds"),
            pytest.param(0, 2, id="No timeout uses default value"),
            pytest.param(3, 3, id="Custom timeout value"),
        ],
    )
    async def test_timeout(self, websocket_connection: FakeWebsocketConnection, timeout: int | None, expected: int):
        async with CDPConnection.create("ws://localhost:1234/fake", timeout=timeout) as cdp_conn:
            pass
        assert cdp_conn.cmd_timeout == expected


class TestReaderError:
    @pytest.mark.trio()
    async def test_invalid_json(self, caplog: pytest.LogCaptureFixture, websocket_connection: FakeWebsocketConnection):
        with pytest.raises(ExceptionGroup) as excinfo:  # noqa: PT012
            async with CDPConnection.create("ws://localhost:1234/fake"):
                assert not websocket_connection.closed
                await websocket_connection.sender.send("INVALID JSON")
                await wait_all_tasks_blocked()

        assert excinfo.group_contains(
            CDPError,
            match=r"^Received invalid CDP JSON data: Expecting value: line 1 column 1 \(char 0\)$",
        )
        assert caplog.records == []

    @pytest.mark.trio()
    async def test_unknown_session_id(self, caplog: pytest.LogCaptureFixture, websocket_connection: FakeWebsocketConnection):
        with pytest.raises(ExceptionGroup) as excinfo:  # noqa: PT012
            async with CDPConnection.create("ws://localhost:1234/fake"):
                assert not websocket_connection.closed
                await websocket_connection.sender.send("""{"sessionId":"unknown"}""")
                await wait_all_tasks_blocked()

        assert excinfo.group_contains(CDPError, match=r"^Unknown CDP session ID: SessionID\('unknown'\)$")
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            ("streamlink.webbrowser.cdp.connection", "all", """Received message: {"sessionId":"unknown"}"""),
        ]


@contextlib.contextmanager
def raises_group(*group_contains):
    try:
        with pytest.raises(ExceptionGroup) as excinfo:
            yield
    finally:
        for args, kwargs, expected in group_contains:
            assert excinfo.group_contains(*args, **kwargs) is expected


class TestSend:
    # noinspection PyUnusedLocal
    @pytest.mark.trio()
    @pytest.mark.parametrize(
        ("timeout", "jump", "raises"),
        [
            pytest.param(
                None,
                2 - EPSILON,
                nullcontext(),
                id="Default timeout, response in time",
            ),
            pytest.param(
                None,
                2,
                raises_group(
                    ((CDPError,), {"match": "^Sending CDP message and receiving its response timed out$"}, True),
                ),
                id="Default timeout, response not in time",
            ),
            pytest.param(
                3,
                3 - EPSILON,
                nullcontext(),
                id="Custom timeout, response in time",
            ),
            pytest.param(
                3,
                3,
                raises_group(
                    ((CDPError,), {"match": "^Sending CDP message and receiving its response timed out$"}, True),
                ),
                id="Custom timeout, response not in time",
            ),
        ],
    )
    async def test_timeout(
        self,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
        autojump_clock: MockClock,
        timeout: float | None,
        jump: float,
        raises: nullcontext,
    ):
        assert cdp_connection.cmd_timeout == 2
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        async def response():
            await trio.sleep(jump)
            await websocket_connection.sender.send("""{"id":0,"result":{"value":"foo"}}""")

        with raises:
            async with trio.open_nursery() as nursery:
                nursery.start_soon(partial(cdp_connection.send, fake_command(FakeCommand("foo")), timeout=timeout))
                nursery.start_soon(response)

        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == ["""{"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}"""]

    @pytest.mark.trio()
    async def test_closed(
        self,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        # noinspection PyTypeChecker
        fake_send_message = AsyncMock(side_effect=ConnectionClosed(CloseReason(1000, None)))
        monkeypatch.setattr(FakeWebsocketConnection, "send_message", fake_send_message)

        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        with pytest.raises(CDPError) as cm:
            await cdp_connection.send(fake_command(FakeCommand("foo")))

        assert str(cm.value) == "CloseReason<code=1000, name=NORMAL_CLOSURE, reason=None>"
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            ),
        ]

    @pytest.mark.trio()
    async def test_bad_command(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        with pytest.raises(ExceptionGroup) as excinfo:  # noqa: PT012
            async with trio.open_nursery() as nursery:
                nursery.start_soon(cdp_connection.send, bad_command())
                nursery.start_soon(websocket_connection.sender.send, """{"id":0,"result":{}}""")

        assert excinfo.group_contains(CDPError, match="^Generator of CDP command ID 0 did not exit when expected!$")
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == ["""{"id":0,"method":"Fake.badCommand","params":{}}"""]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.badCommand","params":{}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0,"result":{}}""",
            ),
        ]

    @pytest.mark.trio()
    async def test_result_exception(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        with pytest.raises(ExceptionGroup) as excinfo:  # noqa: PT012
            async with trio.open_nursery() as nursery:
                nursery.start_soon(cdp_connection.send, fake_command(FakeCommand("foo")))
                nursery.start_soon(websocket_connection.sender.send, """{"id":0,"result":{}}""")

        assert excinfo.group_contains(CDPError, match="^Generator of CDP command ID 0 raised KeyError: 'value'$")
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == ["""{"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}"""]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0,"result":{}}""",
            ),
        ]

    @pytest.mark.trio()
    async def test_result_success(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        results = {}

        async def send(key):
            results[key] = await cdp_connection.send(fake_command(FakeCommand(key)))

        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        async with trio.open_nursery() as nursery:
            # ensure that we start the tasks in the correct order
            nursery.start_soon(send, "foo")
            await wait_all_tasks_blocked()
            nursery.start_soon(send, "bar")
            await wait_all_tasks_blocked()

            assert list(cdp_connection.cmd_buffers.keys()) == [0, 1]
            assert all(buf.response is None for buf in cdp_connection.cmd_buffers.values())
            assert all(buf.event.is_set() is False for buf in cdp_connection.cmd_buffers.values())

            # send result of second command first
            nursery.start_soon(websocket_connection.sender.send, """{"id":1,"result":{"value":"BAR"}}""")
            await wait_all_tasks_blocked()
            nursery.start_soon(websocket_connection.sender.send, """{"id":0,"result":{"value":"FOO"}}""")

        assert list(results.keys()) == ["bar", "foo"]
        assert all(isinstance(result, FakeCommand) for result in results.values())
        assert results["foo"].value == "FOO"
        assert results["bar"].value == "BAR"

        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == [
            """{"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            """{"id":1,"method":"Fake.fakeCommand","params":{"value":"bar"}}""",
        ]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":1,"method":"Fake.fakeCommand","params":{"value":"bar"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":1,"result":{"value":"BAR"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0,"result":{"value":"FOO"}}""",
            ),
        ]


class TestHandleCmdResponse:
    @pytest.mark.trio()
    async def test_unknown_id(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert cdp_connection.cmd_buffers == {}

        await websocket_connection.sender.send("""{"id":123}""")
        await wait_all_tasks_blocked()

        assert cdp_connection.cmd_buffers == {}
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":123}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "warning",
                "Got a CDP command response with an unknown ID: 123",
            ),
        ]

    @pytest.mark.trio()
    async def test_response_error(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        with pytest.raises(ExceptionGroup) as excinfo:  # noqa: PT012
            async with trio.open_nursery() as nursery:
                nursery.start_soon(cdp_connection.send, fake_command(FakeCommand("foo")))
                nursery.start_soon(websocket_connection.sender.send, """{"id":0,"error":"Some error message"}""")

        assert excinfo.group_contains(CDPError, match="^Error in CDP command response 0: Some error message$")
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == ["""{"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}"""]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0,"error":"Some error message"}""",
            ),
        ]

    @pytest.mark.trio()
    async def test_response_no_result(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        with pytest.raises(ExceptionGroup) as excinfo:  # noqa: PT012
            async with trio.open_nursery() as nursery:
                nursery.start_soon(cdp_connection.send, fake_command(FakeCommand("foo")))
                nursery.start_soon(websocket_connection.sender.send, """{"id":0}""")

        assert excinfo.group_contains(CDPError, match="^No result in CDP command response 0$")
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == ["""{"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}"""]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0}""",
            ),
        ]


class TestSession:
    @pytest.fixture()
    async def cdp_session(self, cdp_connection: CDPConnection):
        target_id = TargetID("01234")
        session_id = SessionID("56789")
        session = cdp_connection.sessions[session_id] = CDPSession(
            cdp_connection.websocket,
            target_id=target_id,
            session_id=session_id,
            cmd_timeout=cdp_connection.cmd_timeout,
        )
        return session

    @pytest.mark.trio()
    async def test_new_target(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert cdp_connection.sessions == {}
        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == []

        session = None

        async def send():
            nonlocal session
            session = await cdp_connection.new_target("http://localhost")

        async with trio.open_nursery() as nursery:
            nursery.start_soon(send)
            await wait_all_tasks_blocked()
            nursery.start_soon(websocket_connection.sender.send, """{"id":0,"result":{"targetId":"01234"}}""")
            await wait_all_tasks_blocked()
            nursery.start_soon(websocket_connection.sender.send, """{"id":1,"result":{"sessionId":"56789"}}""")

        assert isinstance(session, CDPSession)
        assert session.target_id == TargetID("01234")
        assert session.session_id == SessionID("56789")
        assert cdp_connection.sessions[SessionID("56789")] is session

        assert cdp_connection.cmd_buffers == {}
        assert websocket_connection.sent == [
            """{"id":0,"method":"Target.createTarget","params":{"url":"http://localhost"}}""",
            """{"id":1,"method":"Target.attachToTarget","params":{"flatten":true,"targetId":"01234"}}""",
        ]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Target.createTarget","params":{"url":"http://localhost"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0,"result":{"targetId":"01234"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":1,"method":"Target.attachToTarget","params":{"flatten":true,"targetId":"01234"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":1,"result":{"sessionId":"56789"}}""",
            ),
        ]

    @pytest.mark.trio()
    async def test_session_command(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        cdp_session: CDPSession,
        websocket_connection: FakeWebsocketConnection,
    ):
        results = {}

        async def send(obj, key):
            results[key] = await obj.send(fake_command(FakeCommand(key)))

        assert cdp_connection.cmd_buffers == {}
        assert cdp_session.cmd_buffers == {}
        assert websocket_connection.sent == []

        async with trio.open_nursery() as nursery:
            # ensure that we start the tasks in the correct order
            nursery.start_soon(send, cdp_connection, "foo")
            await wait_all_tasks_blocked()
            nursery.start_soon(send, cdp_session, "bar")
            await wait_all_tasks_blocked()

            assert list(cdp_connection.cmd_buffers.keys()) == [0]
            assert list(cdp_session.cmd_buffers.keys()) == [0]

            # send result of second command first
            nursery.start_soon(websocket_connection.sender.send, """{"id":0,"result":{"value":"BAR"},"sessionId":"56789"}""")
            await wait_all_tasks_blocked()
            nursery.start_soon(websocket_connection.sender.send, """{"id":0,"result":{"value":"FOO"}}""")

        assert list(results.keys()) == ["bar", "foo"]
        assert all(isinstance(result, FakeCommand) for result in results.values())
        assert results["foo"].value == "FOO"
        assert results["bar"].value == "BAR"

        assert cdp_connection.cmd_buffers == {}
        assert cdp_session.cmd_buffers == {}
        assert websocket_connection.sent == [
            """{"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            """{"id":0,"method":"Fake.fakeCommand","params":{"value":"bar"},"sessionId":"56789"}""",
        ]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.fakeCommand","params":{"value":"foo"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Sending message: {"id":0,"method":"Fake.fakeCommand","params":{"value":"bar"},"sessionId":"56789"}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0,"result":{"value":"BAR"},"sessionId":"56789"}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"id":0,"result":{"value":"FOO"}}""",
            ),
        ]


class TestHandleEvent:
    @pytest.fixture(autouse=True)
    def event_parsers(self, monkeypatch: pytest.MonkeyPatch):
        event_parsers: dict[str, type] = {
            "Fake.fakeEvent": FakeEvent,
        }
        monkeypatch.setattr("streamlink.webbrowser.cdp.devtools.util._event_parsers", event_parsers)
        return event_parsers

    @pytest.mark.trio()
    @pytest.mark.parametrize(
        "message",
        [
            pytest.param("""{"foo":"bar"}""", id="Missing method and params"),
            pytest.param("""{"method":"method"}""", id="Missing params"),
            pytest.param("""{"params":{}}""", id="Missing method"),
        ],
    )
    async def test_invalid_event(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
        message: str,
    ):
        await websocket_connection.sender.send(message)
        await wait_all_tasks_blocked()
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                f"Received message: {message}",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "warning",
                "Invalid CDP event message received without method or params",
            ),
        ]

    @pytest.mark.trio()
    async def test_unknown_event(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        await websocket_connection.sender.send("""{"method":"unknown","params":{}}""")
        await wait_all_tasks_blocked()
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"method":"unknown","params":{}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "warning",
                "Unknown CDP event message received: unknown",
            ),
        ]

    @pytest.mark.trio()
    async def test_eventlistener(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert FakeEvent not in cdp_connection.event_channels
        listener1 = cdp_connection.listen(FakeEvent)
        listener2 = cdp_connection.listen(FakeEvent)
        listener3 = cdp_connection.listen(FakeEvent, max_buffer_size=MAX_BUFFER_SIZE * 2)
        listeners = listener1, listener2, listener3
        assert FakeEvent in cdp_connection.event_channels
        assert len(cdp_connection.event_channels[FakeEvent]) == 3

        assert listener1._sender.statistics().max_buffer_size == MAX_BUFFER_SIZE
        assert listener2._sender.statistics().max_buffer_size == MAX_BUFFER_SIZE
        assert listener3._sender.statistics().max_buffer_size == MAX_BUFFER_SIZE * 2

        results = []

        async def listen_once(listener: CDPEventListener):
            async with listener as result:
                results.append(result)

        async def listen_twice(listener: CDPEventListener):
            async with listener as result:
                results.append(result)
                results.append(await listener.receive())

        async def listen_forever(listener: CDPEventListener):
            async for result in listener:
                results.append(result)

        async with trio.open_nursery() as nursery:
            nursery.start_soon(listen_once, listener1)
            await wait_all_tasks_blocked()
            nursery.start_soon(listen_twice, listener2)
            await wait_all_tasks_blocked()
            nursery.start_soon(listen_forever, listener3)
            await wait_all_tasks_blocked()

            await websocket_connection.sender.send("""{"method":"Fake.fakeEvent","params":{"value":"foo"}}""")
            await wait_all_tasks_blocked()
            assert len(cdp_connection.event_channels[FakeEvent]) == 3

            await websocket_connection.sender.send("""{"method":"Fake.fakeEvent","params":{"value":"bar"}}""")
            await wait_all_tasks_blocked()
            assert len(cdp_connection.event_channels[FakeEvent]) == 2

            await websocket_connection.sender.send("""{"method":"Fake.fakeEvent","params":{"value":"baz"}}""")
            await wait_all_tasks_blocked()
            assert len(cdp_connection.event_channels[FakeEvent]) == 1

            await cdp_connection.aclose()

        assert results == [
            FakeEvent(value="foo"),
            FakeEvent(value="foo"),
            FakeEvent(value="foo"),
            FakeEvent(value="bar"),
            FakeEvent(value="bar"),
            FakeEvent(value="baz"),
        ]
        assert FakeEvent not in cdp_connection.event_channels
        assert all(listener._sender._closed for listener in listeners)  # type: ignore[attr-defined]
        assert all(listener._receiver._closed for listener in listeners)  # type: ignore[attr-defined]
        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"method":"Fake.fakeEvent","params":{"value":"foo"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                "Received event: FakeEvent(value='foo')",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"method":"Fake.fakeEvent","params":{"value":"bar"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                "Received event: FakeEvent(value='bar')",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"method":"Fake.fakeEvent","params":{"value":"baz"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                "Received event: FakeEvent(value='baz')",
            ),
        ]

    @pytest.mark.trio()
    async def test_would_block(
        self,
        caplog: pytest.LogCaptureFixture,
        cdp_connection: CDPConnection,
        websocket_connection: FakeWebsocketConnection,
    ):
        assert FakeEvent not in cdp_connection.event_channels
        listener = cdp_connection.listen(FakeEvent, max_buffer_size=1)
        assert FakeEvent in cdp_connection.event_channels
        assert len(cdp_connection.event_channels[FakeEvent]) == 1

        assert listener._sender.statistics().current_buffer_used == 0
        assert listener._sender.statistics().max_buffer_size == 1

        await websocket_connection.sender.send("""{"method":"Fake.fakeEvent","params":{"value":"foo"}}""")
        await wait_all_tasks_blocked()
        assert listener._sender.statistics().current_buffer_used == 1
        assert listener._sender.statistics().max_buffer_size == 1

        await websocket_connection.sender.send("""{"method":"Fake.fakeEvent","params":{"value":"bar"}}""")
        await wait_all_tasks_blocked()
        assert listener._sender.statistics().current_buffer_used == 1
        assert listener._sender.statistics().max_buffer_size == 1

        assert [(record.name, record.levelname, record.message) for record in caplog.records] == [
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"method":"Fake.fakeEvent","params":{"value":"foo"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                "Received event: FakeEvent(value='foo')",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                """Received message: {"method":"Fake.fakeEvent","params":{"value":"bar"}}""",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "all",
                "Received event: FakeEvent(value='bar')",
            ),
            (
                "streamlink.webbrowser.cdp.connection",
                "error",
                """Unable to propagate CDP event FakeEvent(value='bar') due to full channel""",
            ),
        ]