forked from beeware/toga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_handlers.py
716 lines (524 loc) · 19.9 KB
/
test_handlers.py
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
import asyncio
from unittest.mock import Mock
import pytest
from toga.handlers import AsyncResult, NativeHandler, simple_handler, wrapped_handler
class ExampleAsyncResult(AsyncResult):
RESULT_TYPE = "Test"
def test_noop_handler():
"""None can be wrapped as a valid handler."""
obj = Mock()
wrapped = wrapped_handler(obj, None)
assert wrapped._raw is None
# This does nothing, but doesn't raise an error, and returns None
assert wrapped("arg1", "arg2", kwarg1=3, kwarg2=4) is None
def test_noop_handler_with_cleanup():
"""Cleanup is still performed when a no-op handler is used."""
obj = Mock()
cleanup = Mock()
wrapped = wrapped_handler(obj, None, cleanup=cleanup)
assert wrapped._raw is None
# This does nothing, but doesn't raise an error, and returns None
assert wrapped("arg1", "arg2", kwarg1=3, kwarg2=4) is None
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, None)
def test_noop_handler_with_cleanup_error(capsys):
"""If cleanup on a no-op handler raises an error, it is logged."""
obj = Mock()
cleanup = Mock(side_effect=Exception("Problem in cleanup"))
wrapped = wrapped_handler(obj, None, cleanup=cleanup)
assert wrapped._raw is None
# This does nothing, but doesn't raise an error, and returns None
assert wrapped("arg1", "arg2", kwarg1=3, kwarg2=4) is None
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, None)
# Evidence of the handler cleanup error is in the log.
assert (
"Error in handler cleanup: Problem in cleanup\nTraceback (most recent call last):\n"
in capsys.readouterr().err
)
def test_function_handler():
"""A function can be used as a handler."""
obj = Mock()
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
return 42
wrapped = wrapped_handler(obj, handler)
# Raw handler is the original function
assert wrapped._raw == handler
# Invoke wrapper; handler return value is preserved
assert wrapped("arg1", "arg2", kwarg1=3, kwarg2=4) == 42
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
def test_function_handler_error(capsys):
"""A function handler can raise an error."""
obj = Mock()
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
raise Exception("Problem in handler")
wrapped = wrapped_handler(obj, handler)
assert wrapped._raw == handler
# Invoke handler. The exception is swallowed; return value is None
assert wrapped("arg1", "arg2", kwarg1=3, kwarg2=4) is None
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
# Evidence of the handler error is in the log.
assert (
"Error in handler: Problem in handler\nTraceback (most recent call last):\n"
in capsys.readouterr().err
)
def test_function_handler_with_cleanup():
"""A function handler can have a cleanup method."""
obj = Mock()
cleanup = Mock()
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
return 42
wrapped = wrapped_handler(obj, handler, cleanup=cleanup)
# Raw handler is the original function
assert wrapped._raw == handler
# Invoke handler
assert wrapped("arg1", "arg2", kwarg1=3, kwarg2=4) == 42
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, 42)
def test_function_handler_with_cleanup_error(capsys):
"""A function handler can have a cleanup method that raises an error."""
obj = Mock()
cleanup = Mock(side_effect=Exception("Problem in cleanup"))
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
return 42
wrapped = wrapped_handler(obj, handler, cleanup=cleanup)
# Raw handler is the original function
assert wrapped._raw == handler
# Invoke handler. The error in cleanup is swallowed.
assert wrapped("arg1", "arg2", kwarg1=3, kwarg2=4) == 42
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, 42)
# Evidence of the handler cleanup error is in the log.
assert (
"Error in handler cleanup: Problem in cleanup\nTraceback (most recent call last):\n"
in capsys.readouterr().err
)
def test_generator_handler(event_loop):
"""A generator can be used as a handler."""
obj = Mock()
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
yield 0.01 # A short sleep
handler_call["slept"] = True
yield # A yield without a sleep
handler_call["done"] = True
return 42
wrapped = wrapped_handler(obj, handler)
# Raw handler is the original generator
assert wrapped._raw == handler
# Invoke the handler, and run until it is complete.
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4)) == 42
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
"slept": True,
"done": True,
}
def test_generator_handler_error(event_loop, capsys):
"""A generator can raise an error."""
obj = Mock()
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
yield 0.01 # A short sleep
raise Exception("Problem in handler")
wrapped = wrapped_handler(obj, handler)
# Raw handler is the original generator
assert wrapped._raw == handler
# Invoke the handler; return value is None due to exception
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4))
is None
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
# Evidence of the handler cleanup error is in the log.
assert (
"Error in long running handler: Problem in handler\nTraceback (most recent call last):\n"
in capsys.readouterr().err
)
def test_generator_handler_with_cleanup(event_loop):
"""A generator can have cleanup."""
obj = Mock()
cleanup = Mock()
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
yield 0.01 # A short sleep
handler_call["slept"] = True
yield # A yield without a sleep
handler_call["done"] = True
return 42
wrapped = wrapped_handler(obj, handler, cleanup=cleanup)
# Raw handler is the original generator
assert wrapped._raw == handler
# Invoke the handler
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4)) == 42
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
"slept": True,
"done": True,
}
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, 42)
def test_generator_handler_with_cleanup_error(event_loop, capsys):
"""A generator can raise an error during cleanup."""
obj = Mock()
cleanup = Mock(side_effect=Exception("Problem in cleanup"))
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
yield 0.01 # A short sleep
handler_call["slept"] = True
yield # A yield without a sleep
handler_call["done"] = True
return 42
wrapped = wrapped_handler(obj, handler, cleanup=cleanup)
# Raw handler is the original generator
assert wrapped._raw == handler
# Invoke the handler; error in cleanup is swallowed
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4)) == 42
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
"slept": True,
"done": True,
}
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, 42)
# Evidence of the handler cleanup error is in the log.
assert (
"Error in long running handler cleanup: Problem in cleanup\nTraceback (most recent call last):\n"
in capsys.readouterr().err
)
def test_coroutine_handler(event_loop):
"""A coroutine can be used as a handler."""
obj = Mock()
handler_call = {}
async def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
await asyncio.sleep(0.01) # A short sleep
handler_call["done"] = True
return 42
wrapped = wrapped_handler(obj, handler)
# Raw handler is the original coroutine
assert wrapped._raw == handler
# Invoke the handler
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4)) == 42
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
"done": True,
}
def test_coroutine_handler_error(event_loop, capsys):
"""A coroutine can raise an error."""
obj = Mock()
handler_call = {}
async def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
await asyncio.sleep(0.01) # A short sleep
raise Exception("Problem in handler")
wrapped = wrapped_handler(obj, handler)
# Raw handler is the original coroutine
assert wrapped._raw == handler
# Invoke the handler; return value is None due to exception
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4))
is None
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
# Evidence of the handler cleanup error is in the log.
assert (
"Error in async handler: Problem in handler\nTraceback (most recent call last):\n"
in capsys.readouterr().err
)
def test_coroutine_handler_with_cleanup(event_loop):
"""A coroutine can have cleanup."""
obj = Mock()
cleanup = Mock()
handler_call = {}
async def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
await asyncio.sleep(0.01) # A short sleep
handler_call["done"] = True
return 42
wrapped = wrapped_handler(obj, handler, cleanup=cleanup)
# Raw handler is the original coroutine
assert wrapped._raw == handler
# Invoke the handler
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4)) == 42
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
"done": True,
}
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, 42)
def test_coroutine_handler_with_cleanup_error(event_loop, capsys):
"""A coroutine can raise an error during cleanup."""
obj = Mock()
cleanup = Mock(side_effect=Exception("Problem in cleanup"))
handler_call = {}
async def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
await asyncio.sleep(0.01) # A short sleep
handler_call["done"] = True
return 42
wrapped = wrapped_handler(obj, handler, cleanup=cleanup)
# Raw handler is the original coroutine
assert wrapped._raw == handler
# Invoke the handler; error in cleanup is swallowed
assert (
event_loop.run_until_complete(wrapped("arg1", "arg2", kwarg1=3, kwarg2=4)) == 42
)
# Handler arguments are as expected.
assert handler_call == {
"args": (obj, "arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
"done": True,
}
# Cleanup method was invoked
cleanup.assert_called_once_with(obj, 42)
# Evidence of the handler cleanup error is in the log.
assert (
"Error in async handler cleanup: Problem in cleanup\nTraceback (most recent call last):\n"
in capsys.readouterr().err
)
def test_native_handler():
"""A native function can be used as a handler."""
obj = Mock()
native_method = Mock()
handler = NativeHandler(native_method)
wrapped = wrapped_handler(obj, handler)
# Native method is returned as the handler.
assert wrapped == native_method
def test_async_result_non_comparable(event_loop):
"""An async result can't be compared or evaluated."""
result = ExampleAsyncResult(None)
# repr for the result is useful
assert repr(result).startswith("<Async Test result; future=<Future pending")
# Result cannot be compared.
with pytest.raises(
RuntimeError,
match=r"Can't check Test result directly; use await or an on_result handler",
):
result == 42
with pytest.raises(
RuntimeError,
match=r"Can't check Test result directly; use await or an on_result handler",
):
result < 42
with pytest.raises(
RuntimeError,
match=r"Can't check Test result directly; use await or an on_result handler",
):
result <= 42
with pytest.raises(
RuntimeError,
match=r"Can't check Test result directly; use await or an on_result handler",
):
result > 42
with pytest.raises(
RuntimeError,
match=r"Can't check Test result directly; use await or an on_result handler",
):
result >= 42
with pytest.raises(
RuntimeError,
match=r"Can't check Test result directly; use await or an on_result handler",
):
result != 42
def test_async_result(event_loop):
"""An async result can be set."""
result = ExampleAsyncResult()
result.set_result(42)
# Evaluate the future
async_answer = event_loop.run_until_complete(result.future)
# The answer was returned, and passed to the callback
assert async_answer == 42
def test_async_result_cancelled(event_loop):
"""An async result can be set even if the future is cancelled."""
result = ExampleAsyncResult()
# cancel the future.
result.future.cancel()
result.set_result(42)
# Evaluate the future. This will raise an error
with pytest.raises(asyncio.CancelledError):
event_loop.run_until_complete(result.future)
def test_async_exception(event_loop):
"""An async result can raise an exception."""
result = ExampleAsyncResult()
result.set_exception(ValueError("Bad stuff"))
# Evaluate the future; this will raise an exception
with pytest.raises(ValueError, match=r"Bad stuff"):
event_loop.run_until_complete(result.future)
def test_async_exception_cancelled(event_loop):
"""An async result can raise an exception even if the future is cancelled."""
result = ExampleAsyncResult()
# Cancel the future
result.future.cancel()
result.set_exception(ValueError("Bad stuff"))
# Evaluate the future. This will raise an error
with pytest.raises(asyncio.CancelledError):
event_loop.run_until_complete(result.future)
def test_simple_handler_function():
"""A function can be wrapped as a simple handler."""
handler_call = {}
def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
return 42
wrapped = simple_handler(handler, "arg1", "arg2", kwarg1=3, kwarg2=4)
# Invoke the handler as if it were a method handler (i.e., with the extra "widget"
# argument)
assert wrapped("obj") == 42
assert wrapped._raw == handler
# The "widget" bound argument has been dropped
assert handler_call == {
"args": ("arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
def test_simple_handler_coroutine(event_loop):
"""A coroutine can be wrapped as a simple handler."""
handler_call = {}
async def handler(*args, **kwargs):
handler_call["args"] = args
handler_call["kwargs"] = kwargs
return 42
wrapped = simple_handler(handler, "arg1", "arg2", kwarg1=3, kwarg2=4)
# Invoke the handler as if it were a coroutine method handler (i.e., with the extra
# "widget" argument)
assert event_loop.run_until_complete(wrapped("obj")) == 42
assert wrapped._raw == handler
# The "widget" bound argument has been dropped
assert handler_call == {
"args": ("arg1", "arg2"),
"kwargs": {"kwarg1": 3, "kwarg2": 4},
}
######################################################################
# 2023-12: Backwards compatibility
######################################################################
def test_async_result_sync(event_loop):
"""The deprecated behavior of using a synchronous result handler is supported."""
on_result = Mock()
with pytest.warns(
DeprecationWarning,
match=r"Synchronous `on_result` handlers have been deprecated;",
):
result = ExampleAsyncResult(on_result)
result.set_result(42)
# Evaluate the future
async_answer = event_loop.run_until_complete(result.future)
# The answer was returned, and passed to the callback
assert async_answer == 42
on_result.assert_called_once_with(42)
def test_async_result_cancelled_sync(event_loop):
"""A deprecated on_result handler won't be fired on a cancelled future."""
on_result = Mock()
with pytest.warns(
DeprecationWarning,
match=r"Synchronous `on_result` handlers have been deprecated;",
):
result = ExampleAsyncResult(on_result)
# cancel the future.
result.future.cancel()
result.set_result(42)
# Evaluate the future. This will raise an error
with pytest.raises(asyncio.CancelledError):
event_loop.run_until_complete(result.future)
# The callback wasn't called
on_result.assert_not_called()
def test_async_exception_sync(event_loop):
"""A deprecated on_result handler can raise an exception."""
on_result = Mock()
with pytest.warns(
DeprecationWarning,
match=r"Synchronous `on_result` handlers have been deprecated;",
):
result = ExampleAsyncResult(on_result)
result.set_exception(ValueError("Bad stuff"))
# Evaluate the future; this will raise an exception
with pytest.raises(ValueError, match=r"Bad stuff"):
event_loop.run_until_complete(result.future)
# The answer was returned, and passed to the callback
on_result.assert_called_once()
assert on_result.call_args[0] == (None,)
assert isinstance(on_result.call_args[1]["exception"], ValueError)
def test_async_exception_cancelled_sync(event_loop):
"""An async result can raise an exception even if the future is cancelled."""
on_result = Mock()
with pytest.warns(
DeprecationWarning,
match=r"Synchronous `on_result` handlers have been deprecated;",
):
result = ExampleAsyncResult(on_result)
# Cancel the future
result.future.cancel()
result.set_exception(ValueError("Bad stuff"))
# Evaluate the future. This will raise an error
with pytest.raises(asyncio.CancelledError):
event_loop.run_until_complete(result.future)
# The callback wasn't called
on_result.assert_not_called()