Debian Codegraph @

tests/qml/qt_util.py

raw symbols SCIP
1 import threading
2 import traceback
3 import unittest
4 from functools import wraps, partial
5 from unittest import SkipTest
6
7 from PyQt6.QtCore import QCoreApplication, QMetaObject, Qt, pyqtSlot, QObject
8
9
10 class TestQCoreApplication(QCoreApplication):
11 @pyqtSlot()
12 def doInvoke(self):
13 getattr(self._instance, self._method)()
14
15
16 class QEventReceiver(QObject):
17 def __init__(self, *signals):
18 super().__init__()
19 self.received = []
20 self.signals = []
21 for signal in signals:
22 self.signals.append(signal)
23 signal.connect(partial(self.doReceive, signal))
24
25 # intentionally no pyqtSlot decorator, to catch all
26 def doReceive(self, signal, *args):
27 self.received.append((signal, args))
28
29 def receivedForSignal(self, signal):
30 return list(filter(lambda x: x[0] == signal, self.received))
31
32 def clear(self):
33 self.received.clear()
34
35
36 class QETestCase(unittest.TestCase):
37
38 def setUp(self):
39 super().setUp()
40 self.app = None
41 self._e = None
42 self._testcase_event = threading.Event()
43 self._app_ready_event = threading.Event()
44
45 def start_qt_task():
46 try:
47 assert self.app is None
48 self.app = TestQCoreApplication([])
49 self._app_ready_event.set()
50 self.app.exec()
51 self.app = None
52 except Exception as e:
53 print(f'Problem starting QCoreApplication: {str(e)}')
54
55 self._qt_thread = threading.Thread(target=start_qt_task)
56 self._qt_thread.start()
57
58 def tearDown(self):
59 self.app.exit()
60 if self._qt_thread.is_alive():
61 self._qt_thread.join()
62
63
64 def qt_test(func):
65 @wraps(func)
66 def decorator(self, *args):
67 if threading.current_thread().name == 'MainThread':
68 res = self._app_ready_event.wait(3)
69 if not res:
70 raise Exception('app not ready in time')
71 self._testcase_event.clear()
72 self.app._instance = self
73 self.app._method = func.__name__
74 QMetaObject.invokeMethod(self.app, 'doInvoke', Qt.ConnectionType.QueuedConnection)
75 res = self._testcase_event.wait(15)
76 if not res:
77 self._e = Exception('testcase timed out')
78 if self._e:
79 print("".join(traceback.format_exception(self._e)))
80 # deallocate stored exception from qt thread otherwise we SEGV garbage collector
81 # instead, re-create using the exception message, special casing AssertionError and SkipTest
82 e = None
83 if isinstance(self._e, AssertionError):
84 e = AssertionError(str(self._e))
85 elif isinstance(self._e, SkipTest):
86 e = SkipTest(str(self._e))
87 else:
88 e = Exception(str(self._e))
89 self._e = None
90 raise e
91 return
92 try:
93 func(self, *args)
94 except Exception as e:
95 self._e = e
96 finally:
97 self._testcase_event.set()
98 return decorator