File: test_glib_events.py

package info (click to toggle)
python-gbulb 0.6.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 244 kB
  • sloc: python: 1,851; makefile: 3
file content (617 lines) | stat: -rw-r--r-- 16,041 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
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
import asyncio
import os
import sys
import tempfile
from unittest import mock, skipIf

import pytest
from gi.repository import Gio, GLib

is_windows = sys.platform == "win32"


class TestGLibEventLoopPolicy:
    def test_set_child_watcher(self, glib_policy):
        from gbulb.glib_events import GLibChildWatcher

        with pytest.raises(TypeError):
            glib_policy.set_child_watcher(5)

        glib_policy.set_child_watcher(None)
        assert isinstance(glib_policy.get_child_watcher(), GLibChildWatcher)

        g = GLibChildWatcher()
        glib_policy.set_child_watcher(g)

        assert glib_policy.get_child_watcher() is g

    def test_new_event_loop(self, glib_policy):
        a = glib_policy.new_event_loop()
        b = glib_policy.new_event_loop()

        assert a == glib_policy.get_default_loop()
        assert b != glib_policy.get_default_loop()

    def test_new_event_loop_application(self, glib_policy):
        a = glib_policy.new_event_loop()
        a.set_application(Gio.Application())
        b = glib_policy.new_event_loop()

        assert b._application is None


class TestGLibHandle:
    def test_attachment_order(self, glib_loop):
        call_manager = mock.Mock()

        from gbulb.glib_events import GLibHandle

        # stub this out, we don't care if it gets called or not
        call_manager.loop.get_debug = lambda: True

        h = GLibHandle(
            loop=call_manager.loop,
            source=call_manager.source,
            repeat=True,
            callback=call_manager.callback,
            args=(),
        )

        print(call_manager.mock_calls)

        expected_calls = [
            mock.call.loop._handlers.add(h),
            mock.call.source.set_callback(h.__callback__, h),
            mock.call.source.attach(call_manager.loop._context),
        ]

        assert call_manager.mock_calls == expected_calls


async def no_op_coro():
    pass


class TestBaseGLibEventLoop:
    @skipIf(is_windows, "Unix signal handlers are not supported on Windows")
    def test_add_signal_handler(self, glib_loop):
        import os
        import signal

        called = False

        def handler():
            nonlocal called
            called = True
            glib_loop.stop()

        glib_loop.add_signal_handler(signal.SIGHUP, handler)
        assert signal.SIGHUP in glib_loop._sighandlers

        glib_loop.call_later(0.01, os.kill, os.getpid(), signal.SIGHUP)
        glib_loop.run_forever()

        assert called, "signal handler didn't fire"

    @skipIf(is_windows, "Unix signal handlers are not supported on Windows")
    def test_remove_signal_handler(self, glib_loop):
        import signal

        glib_loop.add_signal_handler(signal.SIGHUP, None)

        assert signal.SIGHUP in glib_loop._sighandlers
        assert glib_loop.remove_signal_handler(signal.SIGHUP)
        assert signal.SIGHUP not in glib_loop._sighandlers

        # FIXME: it'd be great if we could actually try signalling the process

    @skipIf(is_windows, "Unix signal handlers are not supported on Windows")
    def test_remove_signal_handler_unhandled(self, glib_loop):
        import signal

        assert not glib_loop.remove_signal_handler(signal.SIGHUP)

    @skipIf(is_windows, "Unix signal handlers are not supported on Windows")
    @pytest.mark.filterwarnings("ignore:g_unix_signal_source_new")
    def test_remove_signal_handler_sigkill(self, glib_loop):
        import signal

        with pytest.raises(RuntimeError):
            glib_loop.add_signal_handler(signal.SIGKILL, None)

    @skipIf(is_windows, "Unix signal handlers are not supported on Windows")
    @pytest.mark.filterwarnings("ignore:g_unix_signal_source_new")
    def test_remove_signal_handler_sigill(self, glib_loop):
        import signal

        with pytest.raises(ValueError):
            glib_loop.add_signal_handler(signal.SIGILL, None)

    def test_run_until_complete_early_stop(self, glib_loop):
        import asyncio

        async def coro():
            glib_loop.call_soon(glib_loop.stop)
            await asyncio.sleep(5)

        with pytest.raises(RuntimeError):
            glib_loop.run_until_complete(coro())

    @skipIf(
        is_windows, "Waiting on raw file descriptors only works for sockets on Windows"
    )
    def test_add_writer(self, glib_loop):
        import os

        rfd, wfd = os.pipe()

        called = False

        def callback(*args):
            nonlocal called
            called = True
            glib_loop.stop()

        glib_loop.add_writer(wfd, callback)
        glib_loop.run_forever()
        os.close(rfd)
        os.close(wfd)

        assert called, "callback handler didn't fire"

    @skipIf(
        is_windows, "Waiting on raw file descriptors only works for sockets on Windows"
    )
    def test_add_reader(self, glib_loop):
        import os

        rfd, wfd = os.pipe()

        called = False

        def callback(*args):
            nonlocal called
            called = True
            glib_loop.stop()

        glib_loop.add_reader(rfd, callback)

        os.write(wfd, b"hey")

        glib_loop.run_forever()

        os.close(rfd)
        os.close(wfd)

        assert called, "callback handler didn't fire"

    @skipIf(
        is_windows, "Waiting on raw file descriptors only works for sockets on Windows"
    )
    def test_add_reader_file(self, glib_loop):
        import os

        rfd, wfd = os.pipe()

        f = os.fdopen(rfd, "r")

        glib_loop.add_reader(f, None)

        os.close(rfd)
        os.close(wfd)

    @skipIf(
        is_windows, "Waiting on raw file descriptors only works for sockets on Windows"
    )
    def test_add_writer_file(self, glib_loop):
        import os

        rfd, wfd = os.pipe()

        f = os.fdopen(wfd, "r")

        glib_loop.add_writer(f, None)

        os.close(rfd)
        os.close(wfd)

    @skipIf(
        is_windows, "Waiting on raw file descriptors only works for sockets on Windows"
    )
    def test_remove_reader(self, glib_loop):
        import os

        rfd, wfd = os.pipe()

        f = os.fdopen(wfd, "r")

        glib_loop.add_reader(f, None)

        os.close(rfd)
        os.close(wfd)

        assert glib_loop.remove_reader(f)
        assert not glib_loop.remove_reader(f.fileno())

    @skipIf(
        is_windows, "Waiting on raw file descriptors only works for sockets on Windows"
    )
    def test_remove_writer(self, glib_loop):
        import os

        rfd, wfd = os.pipe()

        f = os.fdopen(wfd, "r")

        glib_loop.add_writer(f, None)

        os.close(rfd)
        os.close(wfd)

        assert glib_loop.remove_writer(f)
        assert not glib_loop.remove_writer(f.fileno())

    def test_time(self, glib_loop):
        import time

        SLEEP_TIME = 0.125
        s = glib_loop.time()
        time.sleep(SLEEP_TIME)
        e = glib_loop.time()

        diff = e - s
        assert SLEEP_TIME + 0.01 >= diff >= SLEEP_TIME

    def test_call_at(self, glib_loop):
        called = False

        def handler():
            nonlocal called
            called = True

            now = glib_loop.time()
            glib_loop.stop()

            print(now, s)

            assert now - s <= 0.2

        s = glib_loop.time()

        glib_loop.call_at(s + 0.1, handler)
        glib_loop.run_forever()

        assert called, "call_at handler didn't fire"

    def test_call_soon_no_coroutine(self, glib_loop):
        with pytest.raises(TypeError):
            glib_loop.call_soon(no_op_coro)

    def test_call_later_no_coroutine(self, glib_loop):
        with pytest.raises(TypeError):
            glib_loop.call_later(1, no_op_coro)

    def test_call_at_no_coroutine(self, glib_loop):
        with pytest.raises(TypeError):
            glib_loop.call_at(1, no_op_coro)

    def test_call_soon_priority_order(self, glib_loop):
        items = []

        def handler(i):
            items.append(i)

        for i in range(10):
            glib_loop.call_soon(handler, i)
        glib_loop.call_soon(glib_loop.stop)

        glib_loop.run_forever()

        assert items
        assert items == sorted(items)

    def test_call_soon_priority(self, glib_loop):
        h = glib_loop.call_soon(lambda: None)
        assert h._source.get_priority() == GLib.PRIORITY_DEFAULT
        h.cancel()

    @skipIf(
        is_windows, "Waiting on raw file descriptors only works for sockets on Windows"
    )
    def test_add_writer_multiple_calls(self, glib_loop):
        import os

        rfd, wfd = os.pipe()

        timeout_occurred = False

        expected_i = 10
        i = 0

        def callback():
            nonlocal i
            i += 1

            if i == expected_i:
                glib_loop.stop()

        def timeout():
            nonlocal timeout_occurred
            timeout_occurred = True
            glib_loop.stop()

        try:
            glib_loop.add_writer(wfd, callback)
            glib_loop.call_later(0.1, timeout)
            glib_loop.run_forever()
        finally:
            os.close(rfd)
            os.close(wfd)

        assert not timeout_occurred
        assert i == expected_i

    def test_call_soon_threadsafe(self, glib_loop):
        called = False

        def handler():
            nonlocal called
            called = True
            glib_loop.stop()

        glib_loop.call_soon_threadsafe(handler)
        glib_loop.run_forever()

        assert called, "call_soon_threadsafe handler didn't fire"


class TestGLibEventLoop:
    def test_run_forever_recursion(self, glib_loop):
        def play_it_again_sam():
            with pytest.raises(RuntimeError):
                glib_loop.run_forever()

        glib_loop.call_soon(play_it_again_sam)
        glib_loop.call_soon(glib_loop.stop)
        glib_loop.run_forever()

    def test_run_recursion(self, glib_loop):
        passed = False

        def first():
            assert glib_loop._running

            glib_loop.call_soon(second)
            glib_loop.run()

            assert glib_loop._running

        def second():
            nonlocal passed
            assert glib_loop._running

            glib_loop.stop()

            assert glib_loop._running

            passed = True

        assert not glib_loop._running

        glib_loop.call_soon(first)
        glib_loop.run()

        assert not glib_loop._running
        assert passed

    def test_run(self, glib_loop):
        with mock.patch.object(glib_loop, "_mainloop") as ml:
            glib_loop.run()
            ml.run.assert_any_call()

        glib_loop.set_application(Gio.Application())

        with mock.patch.object(glib_loop, "_application") as app:
            glib_loop.run()
            app.run.assert_any_call(None)

    def test_stop(self, glib_loop):
        with mock.patch.object(glib_loop, "_mainloop") as ml:
            glib_loop.stop()
            ml.quit.assert_any_call()

        glib_loop.set_application(Gio.Application())

        with mock.patch.object(glib_loop, "_application") as app:
            glib_loop.stop()
            app.quit.assert_any_call()

    def test_set_application(self, glib_loop):
        assert glib_loop._application is None
        assert glib_loop._policy._application is None

        app = Gio.Application()
        glib_loop.set_application(app)

        assert glib_loop._application == app
        assert glib_loop._policy._application == app

    def test_set_application_invalid_type(self, glib_loop):
        with pytest.raises(TypeError):
            glib_loop.set_application(None)

    def test_set_application_invalid_repeat_calls(self, glib_loop):
        app = Gio.Application()
        glib_loop.set_application(app)

        with pytest.raises(ValueError):
            glib_loop.set_application(app)

    def test_set_application_invalid_when_running(self, glib_loop):
        app = Gio.Application()

        with pytest.raises(RuntimeError):
            with mock.patch.object(glib_loop, "is_running", return_value=True):
                glib_loop.set_application(app)


@skipIf(is_windows, "Unix signal handlers are not supported on Windows")
def test_signal_handling_with_multiple_invocations(glib_loop):
    import os
    import signal

    glib_loop.call_later(0.01, os.kill, os.getpid(), signal.SIGINT)

    with pytest.raises(KeyboardInterrupt):
        glib_loop.run_forever()

    glib_loop.run_until_complete(asyncio.sleep(0))


@skipIf(is_windows, "Unix signal handlers are not supported on Windows")
def test_default_signal_handling(glib_loop):
    import os
    import signal

    glib_loop.call_later(0.01, os.kill, os.getpid(), signal.SIGINT)

    with pytest.raises(KeyboardInterrupt):
        glib_loop.run_forever()


def test_subprocesses_read_after_closure(glib_loop):
    import asyncio
    import subprocess

    # needed to ensure events.get_child_watcher() returns the right object
    import gbulb

    gbulb.install()

    async def coro():
        proc = await asyncio.create_subprocess_exec(
            "cat",
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        proc.stdin.write(b"hey\n")
        await proc.stdin.drain()

        proc.stdin.close()

        out = await proc.stdout.read()
        assert out == b"hey\n"

        await proc.wait()

    glib_loop.run_until_complete(coro())


def test_subprocesses_readline_without_closure(glib_loop):
    # needed to ensure events.get_child_watcher() returns the right object
    import gbulb

    gbulb.install()

    async def run():
        proc = await asyncio.create_subprocess_exec(
            "cat",
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
        )

        try:
            proc.stdin.write(b"test line\n")
            await proc.stdin.drain()

            line = await asyncio.wait_for(proc.stdout.readline(), timeout=5)
            assert line == b"test line\n"

            proc.stdin.close()

            line = await asyncio.wait_for(proc.stdout.readline(), timeout=5)
            assert line == b""
        finally:
            await proc.wait()

    glib_loop.run_until_complete(run())


def test_sockets(glib_loop):
    server_done = asyncio.Event()
    server_done._loop = glib_loop
    server_success = False

    async def cb(reader, writer):
        nonlocal server_success

        writer.write(b"cool data\n")
        await writer.drain()

        print("reading")
        d = await reader.readline()
        print("hrm", d)
        server_success = d == b"thank you\n"

        writer.close()
        server_done.set()

    async def run():
        s = await asyncio.start_server(cb, "127.0.0.1", 0)
        reader, writer = await asyncio.open_connection(
            "127.0.0.1", s.sockets[0].getsockname()[-1]
        )

        d = await reader.readline()
        assert d == b"cool data\n"

        writer.write(b"thank you\n")
        await writer.drain()

        writer.close()

        await server_done.wait()

        assert server_success

    glib_loop.run_until_complete(run())


def test_unix_sockets(glib_loop):
    server_done = asyncio.Event()
    server_done._loop = glib_loop
    server_success = False

    async def cb(reader, writer):
        nonlocal server_success

        writer.write(b"cool data\n")
        await writer.drain()

        d = await reader.readline()
        server_success = d == b"thank you\n"

        writer.close()
        server_done.set()

    async def run():
        with tempfile.TemporaryDirectory() as tmpdir:
            path = os.path.join(tmpdir, "socket")
            await asyncio.start_unix_server(cb, path)
            reader, writer = await asyncio.open_unix_connection(path)

            d = await reader.readline()
            assert d == b"cool data\n"

            writer.write(b"thank you\n")
            await writer.drain()

            writer.close()

            await server_done.wait()

        assert server_success

    glib_loop.run_until_complete(run())