-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathtest_wait_signal.py
More file actions
1478 lines (1267 loc) · 51.1 KB
/
Copy pathtest_wait_signal.py
File metadata and controls
1478 lines (1267 loc) · 51.1 KB
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import fnmatch
import pytest
import sys
from pytestqt.qt_compat import qt_api
from pytestqt.wait_signal import (
SignalEmittedError,
TimeoutError,
SignalAndArgs,
CallbackCalledTwiceError,
)
flaky_on_macos = pytest.mark.xfail(
sys.platform == "darwin", run=False, reason="Flaky on macOS: #313"
)
@pytest.mark.parametrize(
"method, signal, timeout",
[
("waitSignal", None, None),
("waitSignal", None, 1000),
("waitSignals", [], None),
("waitSignals", [], 1000),
("waitSignals", None, None),
("waitSignals", None, 1000),
],
)
def test_signal_blocker_none(qtbot, method, signal, timeout):
"""
Make sure waitSignal without signals isn't supported anymore.
"""
meth = getattr(qtbot, method)
with pytest.raises(ValueError):
meth(signal, timeout=timeout).wait()
def explicit_wait(qtbot, signal, timeout, multiple, raising, should_raise):
"""
Explicit wait for the signal using blocker API.
"""
func = qtbot.waitSignals if multiple else qtbot.waitSignal
blocker = func(signal, timeout=timeout, raising=raising)
assert not blocker.signal_triggered
if should_raise:
with pytest.raises(qtbot.TimeoutError):
blocker.wait()
else:
blocker.wait()
return blocker
def context_manager_wait(qtbot, signal, timeout, multiple, raising, should_raise):
"""
Waiting for signal using context manager API.
"""
func = qtbot.waitSignals if multiple else qtbot.waitSignal
if should_raise:
with pytest.raises(qtbot.TimeoutError):
with func(signal, timeout=timeout, raising=raising) as blocker:
pass
else:
with func(signal, timeout=timeout, raising=raising) as blocker:
pass
return blocker
def build_signal_tests_variants(params):
"""
Helper function to use with pytest's parametrize, to generate additional
combinations of parameters in a parametrize call:
- explicit wait and context-manager wait
- raising True and False (since we check for the correct behavior inside
each test).
"""
result = []
for param in params:
for wait_function in (explicit_wait, context_manager_wait):
for raising in (True, False):
result.append(param + (wait_function, raising))
return result
@pytest.mark.parametrize(
("delay", "timeout", "expected_signal_triggered", "wait_function", "raising"),
build_signal_tests_variants(
[
# delay, timeout, expected_signal_triggered
(200, None, True),
(200, 400, True),
(400, 200, False),
]
),
)
@flaky_on_macos
def test_signal_triggered(
qtbot,
timer,
stop_watch,
wait_function,
delay,
timeout,
expected_signal_triggered,
raising,
signaller,
):
"""
Testing for a signal in different conditions, ensuring we are obtaining
the expected results.
"""
timer.single_shot(signaller.signal, delay)
should_raise = raising and not expected_signal_triggered
stop_watch.start()
blocker = wait_function(
qtbot,
signaller.signal,
timeout=timeout,
raising=raising,
should_raise=should_raise,
multiple=False,
)
# ensure that either signal was triggered or timeout occurred
assert blocker.signal_triggered == expected_signal_triggered
stop_watch.check(timeout, delay)
@pytest.mark.parametrize("delayed", [True, False])
def test_zero_timeout(qtbot, timer, delayed, signaller):
"""
With a zero timeout, we don't run a main loop, so only immediate signals are
processed.
"""
with qtbot.waitSignal(signaller.signal, raising=False, timeout=0) as blocker:
if delayed:
timer.single_shot(signaller.signal, 0)
else:
signaller.signal.emit()
assert blocker.signal_triggered != delayed
@pytest.mark.parametrize(
"configval, raises", [("false", False), ("true", True), (None, True)]
)
def test_raising(qtbot, testdir, configval, raises):
if configval is not None:
testdir.makeini(f"""
[pytest]
qt_default_raising = {configval}
""")
testdir.makepyfile("""
import pytest
from pytestqt.qt_compat import qt_api
class Signaller(qt_api.QtCore.QObject):
signal = qt_api.Signal()
def test_foo(qtbot):
signaller = Signaller()
with qtbot.waitSignal(signaller.signal, timeout=10):
pass
""")
res = testdir.runpytest()
if raises:
res.stdout.fnmatch_lines(["*1 failed*"])
else:
res.stdout.fnmatch_lines(["*1 passed*"])
def test_raising_by_default_overridden(qtbot, testdir):
testdir.makeini("""
[pytest]
qt_default_raising = false
""")
testdir.makepyfile("""
import pytest
from pytestqt.qt_compat import qt_api
class Signaller(qt_api.QtCore.QObject):
signal = qt_api.Signal()
def test_foo(qtbot):
signaller = Signaller()
signal = signaller.signal
with qtbot.waitSignal(signal, raising=True, timeout=10) as blocker:
pass
""")
res = testdir.runpytest()
res.stdout.fnmatch_lines(["*1 failed*"])
@pytest.mark.parametrize(
(
"delay_1",
"delay_2",
"timeout",
"expected_signal_triggered",
"wait_function",
"raising",
),
build_signal_tests_variants(
[
# delay1, delay2, timeout, expected_signal_triggered
(200, 300, 400, True),
(300, 200, 400, True),
(200, 300, None, True),
(400, 400, 200, False),
(200, 400, 300, False),
(400, 200, 200, False),
(200, 1000, 400, False),
]
),
)
@flaky_on_macos
def test_signal_triggered_multiple(
qtbot,
timer,
stop_watch,
wait_function,
delay_1,
delay_2,
timeout,
signaller,
expected_signal_triggered,
raising,
):
"""
Testing for a signal in different conditions, ensuring we are obtaining
the expected results.
"""
timer.single_shot(signaller.signal, delay_1)
timer.single_shot(signaller.signal_2, delay_2)
should_raise = raising and not expected_signal_triggered
stop_watch.start()
blocker = wait_function(
qtbot,
[signaller.signal, signaller.signal_2],
timeout=timeout,
multiple=True,
raising=raising,
should_raise=should_raise,
)
# ensure that either signal was triggered or timeout occurred
assert blocker.signal_triggered == expected_signal_triggered
stop_watch.check(timeout, delay_1, delay_2)
def test_explicit_emit(qtbot, signaller):
"""
Make sure an explicit emit() inside a waitSignal block works.
"""
with qtbot.waitSignal(signaller.signal, timeout=5000) as waiting:
signaller.signal.emit()
assert waiting.signal_triggered
def test_explicit_emit_multiple(qtbot, signaller):
"""
Make sure an explicit emit() inside a waitSignal block works.
"""
with qtbot.waitSignals(
[signaller.signal, signaller.signal_2], timeout=5000
) as waiting:
signaller.signal.emit()
signaller.signal_2.emit()
assert waiting.signal_triggered
@pytest.fixture
def signaller(timer):
"""
Fixture that provides an object with to signals that can be emitted by
tests.
.. note:: we depend on "timer" fixture to ensure that signals emitted
with "timer" are disconnected before the Signaller() object is destroyed.
This was the reason for some random crashes experienced on Windows (#80).
"""
class Signaller(qt_api.QtCore.QObject):
signal = qt_api.Signal()
signal_2 = qt_api.Signal()
signal_args = qt_api.Signal(str, int)
signal_args_2 = qt_api.Signal(str, int)
signal_single_arg = qt_api.Signal(int)
assert timer
return Signaller()
@pytest.mark.parametrize("blocker", ["single", "multiple", "callback"])
@pytest.mark.parametrize("raising", [True, False])
def test_blockers_handle_exceptions(qtbot, blocker, raising, signaller):
"""
Make sure blockers handle exceptions correctly.
"""
class TestException(Exception):
pass
if blocker == "multiple":
func = qtbot.waitSignals
args = [[signaller.signal, signaller.signal_2]]
elif blocker == "single":
func = qtbot.waitSignal
args = [signaller.signal]
elif blocker == "callback":
func = qtbot.waitCallback
args = []
else:
assert False
with pytest.raises(TestException):
with func(*args, timeout=10, raising=raising):
raise TestException
@pytest.mark.parametrize("multiple", [True, False])
@pytest.mark.parametrize("do_timeout", [True, False])
def test_wait_twice(qtbot, timer, multiple, do_timeout, signaller):
"""
https://github.com/pytest-dev/pytest-qt/issues/69
"""
if multiple:
func = qtbot.waitSignals
arg = [signaller.signal]
else:
func = qtbot.waitSignal
arg = signaller.signal
if do_timeout:
with func(arg, timeout=100, raising=False):
timer.single_shot(signaller.signal, 200)
with func(arg, timeout=100, raising=False):
timer.single_shot(signaller.signal, 200)
else:
with func(arg):
signaller.signal.emit()
with func(arg):
signaller.signal.emit()
def test_wait_signals_invalid_strict_parameter(qtbot, signaller):
with pytest.raises(ValueError):
qtbot.waitSignals([signaller.signal], order="invalid")
def test_destroyed(qtbot):
"""Test that waitSignal works with the destroyed signal (#82)."""
class Obj(qt_api.QtCore.QObject):
pass
obj = Obj()
with qtbot.waitSignal(obj.destroyed):
obj.deleteLater()
with pytest.raises(RuntimeError):
obj.objectName()
class TestArgs:
"""Try to get the signal arguments from the signal blocker."""
def test_simple(self, qtbot, signaller):
"""The blocker should store the signal args in an 'args' attribute."""
with qtbot.waitSignal(signaller.signal_args) as blocker:
signaller.signal_args.emit("test", 123)
assert blocker.args == ["test", 123]
def test_timeout(self, qtbot, signaller):
"""If there's a timeout, the args attribute is None."""
with qtbot.waitSignal(signaller.signal, timeout=100, raising=False) as blocker:
pass
assert blocker.args is None
def test_without_args(self, qtbot, signaller):
"""If a signal has no args, the args attribute is an empty list."""
with qtbot.waitSignal(signaller.signal) as blocker:
signaller.signal.emit()
assert blocker.args == []
def test_multi(self, qtbot, signaller):
"""A MultiSignalBlocker doesn't have an args attribute."""
with qtbot.waitSignals([signaller.signal]) as blocker:
signaller.signal.emit()
with pytest.raises(AttributeError):
blocker.args
def test_connected_signal(self, qtbot, signaller):
"""A second signal connected via .connect also works."""
with qtbot.waitSignal(signaller.signal_args) as blocker:
blocker.connect(signaller.signal_args_2)
signaller.signal_args_2.emit("foo", 2342)
assert blocker.args == ["foo", 2342]
def test_signal_identity(signaller):
"""
Tests that the identity of signals can be determined correctly, using str(signal).
PyQt5 has the following issue:
x = signaller.signal
y = signaller.signal
x == y # is False
id(signaller.signal) == id(signaller.signal) # only True because of garbage collection
between first and second id() call
id(x) == id(y) # is False
str(x) == str(y) # is True (for all Qt frameworks)
"""
assert str(signaller.signal) == str(signaller.signal)
x = signaller.signal
y = signaller.signal
assert str(x) == str(y)
# different signals should also be recognized as different ones
z = signaller.signal_2
assert str(x) != str(z)
def test_invalid_signal(qtbot):
"""Tests that a TypeError is raised when providing a signal object that actually is not a Qt signal at all."""
class NotReallyASignal:
def __init__(self):
self.signal = False
with pytest.raises(TypeError):
with qtbot.waitSignal(signal=NotReallyASignal(), raising=False):
pass
def test_invalid_signal_tuple_length(qtbot, signaller):
"""
Test that a ValueError is raised when not providing a signal+name tuple with exactly 2 elements
as signal parameter.
"""
with pytest.raises(ValueError):
signal_tuple_with_invalid_length = (
signaller.signal,
"signal()",
"does not belong here",
)
with qtbot.waitSignal(signal=signal_tuple_with_invalid_length, raising=False):
pass
def test_provided_empty_signal_name(qtbot, signaller):
"""Test that a ValueError is raised when providing a signal+name tuple where the name is an empty string."""
with pytest.raises(ValueError):
invalid_signal_tuple = (signaller.signal, "")
with qtbot.waitSignal(signal=invalid_signal_tuple, raising=False):
pass
def test_provided_invalid_signal_name_type(qtbot, signaller):
"""Test that a TypeError is raised when providing a signal+name tuple where the name is not actually string."""
with pytest.raises(TypeError):
invalid_signal_tuple = (signaller.signal, 12345) # 12345 is not a signal name
with qtbot.waitSignal(signal=invalid_signal_tuple, raising=False):
pass
def test_signalandargs_equality():
signal_args1 = SignalAndArgs(signal_name="signal", args=(1, 2))
signal_args2 = SignalAndArgs(signal_name="signal", args=(1, 2))
assert signal_args1 == signal_args2
def test_signalandargs_inequality():
signal_args1_1 = SignalAndArgs(signal_name="signal", args=(1, 2))
signal_args1_2 = "foo"
assert signal_args1_1 != signal_args1_2
def get_waitsignals_cases_all(order):
"""
Returns the list of tuples (emitted-signal-list, expected-signal-list, expect_signal_triggered) for the
given order parameter of waitSignals().
"""
cases = get_waitsignals_cases(order, working=True)
cases.extend(get_waitsignals_cases(order, working=False))
return cases
def get_waitsignals_cases(order, working):
"""
Builds combinations for signals to be emitted and expected for working cases (i.e. blocker.signal_triggered == True)
and non-working cases, depending on the order.
Note:
The order ("none", "simple", "strict") becomes stricter from left to right.
Working cases of stricter cases also work in less stricter cases.
Non-working cases in less stricter cases also are non-working in stricter cases.
"""
if order == "none":
if working:
cases = get_waitsignals_cases(order="simple", working=True)
cases.extend(
[
# allow even out-of-order signals
(("A1", "A2"), ("A2", "A1"), True),
(("A1", "A2"), ("A2", "Ax"), True),
(("A1", "B1"), ("B1", "A1"), True),
(("A1", "B1"), ("B1", "Ax"), True),
(("A1", "B1", "B1"), ("B1", "A1", "B1"), True),
]
)
return cases
else:
return [
(("A2",), ("A1",), False),
(("A1",), ("B1",), False),
(("A1",), ("Bx",), False),
(("A1", "A1"), ("A1", "B1"), False),
(("A1", "A1"), ("A1", "Bx"), False),
(("A1", "A1"), ("B1", "A1"), False),
(("A1", "B1"), ("A1", "A1"), False),
(("A1", "B1"), ("B1", "B1"), False),
(("A1", "B1", "B1"), ("A1", "A1", "B1"), False),
]
elif order == "simple":
if working:
cases = get_waitsignals_cases(order="strict", working=True)
cases.extend(
[
# allow signals that occur in-between, before or after the expected signals
(("B1", "A1", "A1", "B1", "A1"), ("A1", "B1"), True),
(("A1", "A1", "A1"), ("A1", "A1"), True),
(("A1", "A1", "A1"), ("A1", "Ax"), True),
(("A1", "A2", "A1"), ("A1", "A1"), True),
]
)
return cases
else:
cases = get_waitsignals_cases(order="none", working=False)
cases.extend(
[
# don't allow out-of-order signals
(("A1", "B1"), ("B1", "A1"), False),
(("A1", "B1"), ("B1", "Ax"), False),
(("A1", "B1", "B1"), ("B1", "A1", "B1"), False),
(("A1", "B1", "B1"), ("B1", "B1", "A1"), False),
]
)
return cases
elif order == "strict":
if working:
return [
# only allow exactly the same signals to be emitted that were also expected
(("A1",), ("A1",), True),
(("A1",), ("Ax",), True),
(("A1", "A1"), ("A1", "A1"), True),
(("A1", "A1"), ("A1", "Ax"), True),
(("A1", "A1"), ("Ax", "Ax"), True),
(("A1", "A2"), ("A1", "A2"), True),
(("A2", "A1"), ("A2", "A1"), True),
(("A1", "B1"), ("A1", "B1"), True),
(("A1", "A1", "B1"), ("A1", "A1", "B1"), True),
(("A1", "A2", "B1"), ("A1", "A2", "B1"), True),
(
("A1", "B1", "A1"),
("A1", "A1"),
True,
), # blocker doesn't know about signal B1 -> test passes
(("A1", "B1", "A1"), ("Ax", "A1"), True),
]
else:
cases = get_waitsignals_cases(order="simple", working=False)
cases.extend(
[
# don't allow in-between signals
(("A1", "A1", "A2", "B1"), ("A1", "A2", "B1"), False)
]
)
return cases
class TestCallback:
"""
Tests the callback parameter for waitSignal (callbacks in case of waitSignals).
Uses so-called "signal codes" such as "A1", "B1" or "Ax" which are converted to signals and callback functions.
The first letter ("A" or "B" is allowed) specifies the signal (signaller.signal_args or signaller.signal_args_2
respectively), the second letter specifies the parameter to expect or emit ('x' stands for "don't care", i.e. allow
any value - only applicable for expected signals (not for emitted signals)).
"""
@staticmethod
def get_signal_from_code(signaller, code):
"""Converts a code such as 'A1' to a signal (signaller.signal_args for example)."""
assert type(code) is str and len(code) == 2
signal = signaller.signal_args if code[0] == "A" else signaller.signal_args_2
return signal
@staticmethod
def emit_parametrized_signals(signaller, emitted_signal_codes):
"""Emits the signals as specified in the list of emitted_signal_codes using the signaller."""
for code in emitted_signal_codes:
signal = TestCallback.get_signal_from_code(signaller, code)
param_str = code[1]
assert (
param_str != "x"
), "x is not allowed in emitted_signal_codes, only in expected_signal_codes"
param_int = int(param_str)
signal.emit(param_str, param_int)
@staticmethod
def parameter_evaluation_callback(
param_str, param_int, expected_param_str, expected_param_int
):
"""
This generic callback method evaluates that the two provided parameters match the expected ones (which are bound
using functools.partial).
"""
return param_str == expected_param_str and param_int == expected_param_int
@staticmethod
def parameter_evaluation_callback_accept_any(param_str, param_int):
return True
@staticmethod
def get_signals_and_callbacks(signaller, expected_signal_codes):
"""
Converts an iterable of strings, such as ('A1', 'A2') to a tuple of the form
(list of Qt signals, matching parameter-evaluation callbacks)
Example: ('A1', 'A2') is converted to
([signaller.signal_args, signaller.signal_args], [callback(str,int), callback(str,int)]) where the
first callback expects the values to be '1' and 1, and the second one '2' and 2 respectively.
I.e. the first character of each signal-code determines the Qt signal, the second one the parameter values.
"""
signals_to_expect = []
callbacks = []
for code in expected_signal_codes:
# e.g. "A2" means to use signaller.signal_args with parameters "2", 2
signal = TestCallback.get_signal_from_code(signaller, code)
signals_to_expect.append(signal)
param_value_as_string = code[1]
if param_value_as_string == "x":
callback = TestCallback.parameter_evaluation_callback_accept_any
else:
param_value_as_int = int(param_value_as_string)
callback = functools.partial(
TestCallback.parameter_evaluation_callback,
expected_param_str=param_value_as_string,
expected_param_int=param_value_as_int,
)
callbacks.append(callback)
return signals_to_expect, callbacks
@pytest.mark.parametrize(
("emitted_signal_codes", "expected_signal_codes", "expected_signal_triggered"),
[
# working cases
(("A1",), ("A1",), True),
(("A1",), ("Ax",), True),
(("A1", "A1"), ("A1",), True),
(("A1", "A2"), ("A1",), True),
(("A2", "A1"), ("A1",), True),
# non working cases
(("A2",), ("A1",), False),
(("B1",), ("A1",), False),
(("A1",), ("Bx",), False),
],
)
def test_wait_signal(
self,
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
):
"""Tests that waitSignal() correctly checks the signal parameters using the provided callback"""
signals_to_expect, callbacks = TestCallback.get_signals_and_callbacks(
signaller, expected_signal_codes
)
with qtbot.waitSignal(
signal=signals_to_expect[0],
check_params_cb=callbacks[0],
timeout=200,
raising=False,
) as blocker:
TestCallback.emit_parametrized_signals(signaller, emitted_signal_codes)
assert blocker.signal_triggered == expected_signal_triggered
@pytest.mark.parametrize(
("emitted_signal_codes", "expected_signal_codes", "expected_signal_triggered"),
get_waitsignals_cases_all(order="none"),
)
def test_wait_signals_none_order(
self,
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
):
"""Tests waitSignals() with order="none"."""
self._test_wait_signals(
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
order="none",
)
@pytest.mark.parametrize(
("emitted_signal_codes", "expected_signal_codes", "expected_signal_triggered"),
get_waitsignals_cases_all(order="simple"),
)
def test_wait_signals_simple_order(
self,
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
):
"""Tests waitSignals() with order="simple"."""
self._test_wait_signals(
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
order="simple",
)
@pytest.mark.parametrize(
("emitted_signal_codes", "expected_signal_codes", "expected_signal_triggered"),
get_waitsignals_cases_all(order="strict"),
)
def test_wait_signals_strict_order(
self,
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
):
"""Tests waitSignals() with order="strict"."""
self._test_wait_signals(
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
order="strict",
)
@staticmethod
def _test_wait_signals(
qtbot,
signaller,
emitted_signal_codes,
expected_signal_codes,
expected_signal_triggered,
order,
):
signals_to_expect, callbacks = TestCallback.get_signals_and_callbacks(
signaller, expected_signal_codes
)
with qtbot.waitSignals(
signals=signals_to_expect,
order=order,
check_params_cbs=callbacks,
timeout=200,
raising=False,
) as blocker:
TestCallback.emit_parametrized_signals(signaller, emitted_signal_codes)
assert blocker.signal_triggered == expected_signal_triggered
def test_signals_and_callbacks_length_mismatch(self, qtbot, signaller):
"""
Tests that a ValueError is raised if the number of expected signals doesn't match the number of provided
callbacks.
"""
expected_signal_codes = ("A1", "A2")
signals_to_expect, callbacks = TestCallback.get_signals_and_callbacks(
signaller, expected_signal_codes
)
callbacks.append(None)
with pytest.raises(ValueError):
with qtbot.waitSignals(
signals=signals_to_expect,
order="none",
check_params_cbs=callbacks,
raising=False,
):
pass
class TestAllArgs:
"""
Tests blocker.all_args (waitSignal() blocker) which is filled with the args of the emitted signals in case
the signal has args and the user provided a callable for the check_params_cb argument of waitSignal().
"""
def test_no_signal_without_args(self, qtbot, signaller):
"""When not emitting any signal and expecting one without args, all_args has to be empty."""
with qtbot.waitSignal(
signal=signaller.signal, timeout=200, check_params_cb=None, raising=False
) as blocker:
pass # don't emit anything
assert blocker.all_args == []
def test_one_signal_without_args(self, qtbot, signaller):
"""When emitting an expected signal without args, all_args has to be empty."""
with qtbot.waitSignal(
signal=signaller.signal, timeout=200, check_params_cb=None, raising=False
) as blocker:
signaller.signal.emit()
assert blocker.all_args == []
def test_one_signal_with_args_matching(self, qtbot, signaller):
"""
When emitting an expected signals with args that match the expected one (satisfy the cb), all_args must
contain these args.
"""
def cb(str_param, int_param):
return True
with qtbot.waitSignal(
signal=signaller.signal_args, timeout=200, check_params_cb=cb, raising=False
) as blocker:
signaller.signal_args.emit("1", 1)
assert blocker.all_args == [("1", 1)]
def test_two_signals_with_args_partially_matching(self, qtbot, signaller):
"""
When emitting an expected signals with non-matching args followed by emitting it again with matching args,
all_args must contain both of these args.
"""
def cb(str_param, int_param):
return str_param == "1" and int_param == 1
with qtbot.waitSignal(
signal=signaller.signal_args, timeout=200, check_params_cb=cb, raising=False
) as blocker:
signaller.signal_args.emit("2", 2)
signaller.signal_args.emit("1", 1)
assert blocker.all_args == [("2", 2), ("1", 1)]
def get_mixed_signals_with_guaranteed_name(signaller):
"""
Returns a list of signals with the guarantee that the signals have names (i.e. the names are
manually provided in case of using PySide6, where the signal names cannot be determined at run-time).
"""
if qt_api.is_pyside:
signals = [
(signaller.signal, "signal()"),
(signaller.signal_args, "signal_args(QString,int)"),
(signaller.signal_args, "signal_args(QString,int)"),
]
else:
signals = [signaller.signal, signaller.signal_args, signaller.signal_args]
return signals
class TestAllSignalsAndArgs:
"""
Tests blocker.all_signals_and_args (waitSignals() blocker) is a list of SignalAndArgs objects, one for each
received expected signal (irrespective of the order parameter).
"""
def test_empty_when_no_signal(self, qtbot, signaller):
"""Tests that all_signals_and_args is empty when no expected signal is emitted."""
signals = get_mixed_signals_with_guaranteed_name(signaller)
with qtbot.waitSignals(
signals=signals,
timeout=200,
check_params_cbs=None,
order="none",
raising=False,
) as blocker:
pass
assert blocker.all_signals_and_args == []
def test_non_empty_on_pyside(self, qtbot, signaller):
"""
Tests that all_signals_and_args is empty even though expected signals are emitted, but signal names aren't
available.
"""
if qt_api.pytest_qt_api != "pyside6":
pytest.skip(
"test only makes sense for PySide6, whose signals don't contain a name"
)
with qtbot.waitSignals(
signals=[signaller.signal, signaller.signal_args, signaller.signal_args],
timeout=200,
check_params_cbs=None,
order="none",
raising=False,
) as blocker:
signaller.signal.emit()
signaller.signal_args.emit("1", 1)
assert len(blocker.all_signals_and_args) == 2
def test_non_empty_on_timeout_no_cb(self, qtbot, signaller):
"""
Tests that all_signals_and_args contains the emitted signals. No callbacks for arg-evaluation are provided. The
signals are emitted out of order, causing a timeout.
"""
signals = get_mixed_signals_with_guaranteed_name(signaller)
with qtbot.waitSignals(
signals=signals,
timeout=200,
check_params_cbs=None,
order="simple",
raising=False,
) as blocker:
signaller.signal_args.emit("1", 1)
signaller.signal.emit()
assert not blocker.signal_triggered
assert blocker.all_signals_and_args == [
SignalAndArgs(signal_name="signal_args(QString,int)", args=("1", 1)),
SignalAndArgs(signal_name="signal()", args=()),
]
def test_non_empty_no_cb(self, qtbot, signaller):
"""
Tests that all_signals_and_args contains the emitted signals. No callbacks for arg-evaluation are provided. The
signals are emitted in order.
"""
signals = get_mixed_signals_with_guaranteed_name(signaller)
with qtbot.waitSignals(
signals=signals,
timeout=200,
check_params_cbs=None,
order="simple",
raising=False,
) as blocker:
signaller.signal.emit()
signaller.signal_args.emit("1", 1)
signaller.signal_args.emit("2", 2)
assert blocker.signal_triggered
assert blocker.all_signals_and_args == [
SignalAndArgs(signal_name="signal()", args=()),
SignalAndArgs(signal_name="signal_args(QString,int)", args=("1", 1)),
SignalAndArgs(signal_name="signal_args(QString,int)", args=("2", 2)),
]
class TestWaitSignalTimeoutErrorMessage:
"""Tests that the messages of TimeoutError are formatted correctly, for waitSignal() calls."""
def test_without_callback_and_args(self, qtbot, signaller):
"""
In a situation where a signal without args is expected but not emitted, tests that the TimeoutError
message contains the name of the signal (without arguments).
"""
if qt_api.is_pyside:
signal = (signaller.signal, "signal()")
else:
signal = signaller.signal
with pytest.raises(TimeoutError) as excinfo:
with qtbot.waitSignal(
signal=signal, timeout=200, check_params_cb=None, raising=True
):
pass # don't emit any signals
ex_msg = TestWaitSignalsTimeoutErrorMessage.get_exception_message(excinfo)
assert ex_msg == "Signal signal() not emitted after 200 ms"
def test_with_single_arg(self, qtbot, signaller):
"""
In a situation where a signal with one argument is expected but the emitted instances have values that are
rejected by a callback, tests that the TimeoutError message contains the name of the signal and the
list of non-accepted arguments.
"""