File: test_concurrent.py

package info (click to toggle)
orange-widget-base 4.27.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,380 kB
  • sloc: python: 16,556; javascript: 58; makefile: 6
file content (294 lines) | stat: -rw-r--r-- 10,186 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
import unittest
import unittest.mock
import threading
import random
import weakref

from concurrent.futures import Future, ThreadPoolExecutor
from types import SimpleNamespace
from typing import Iterable, Set

from AnyQt.QtCore import (
    Qt, QObject, QCoreApplication, QThread, QEventLoop, QTimer, pyqtSlot,
    pyqtSignal
)
from AnyQt.QtTest import QSignalSpy

from orangewidget.utils.concurrent import (
    FutureWatcher, FutureSetWatcher, methodinvoke, PyOwned
)


class CoreAppTestCase(unittest.TestCase):
    def setUp(self):
        self.app = QCoreApplication.instance()
        if self.app is None:
            self.app = QCoreApplication([])

    def tearDown(self):
        self.app.processEvents()
        del self.app


class TestMethodinvoke(CoreAppTestCase):
    def test_methodinvoke(self):
        executor = ThreadPoolExecutor()
        state = [None, None]

        class StateSetter(QObject):
            @pyqtSlot(object)
            def set_state(self, value):
                state[0] = value
                state[1] = QThread.currentThread()

        def func(callback):
            callback(QThread.currentThread())

        obj = StateSetter()
        f1 = executor.submit(func, methodinvoke(obj, "set_state", (object,)))
        f1.result()
        # So invoked method can be called from the event loop
        self.app.processEvents()

        self.assertIs(state[1], QThread.currentThread(),
                      "set_state was called from the wrong thread")

        self.assertIsNot(state[0], QThread.currentThread(),
                         "set_state was invoked in the main thread")

        executor.shutdown(wait=True)


class TestFutureWatcher(CoreAppTestCase):
    def test_watcher(self):
        executor = ThreadPoolExecutor(max_workers=1)
        f = executor.submit(lambda: 42)
        w = FutureWatcher(f)

        def spies(w):
            return SimpleNamespace(
                done=QSignalSpy(w.done),
                finished=QSignalSpy(w.finished),
                result=QSignalSpy(w.resultReady),
                error=QSignalSpy(w.exceptionReady),
                cancelled=QSignalSpy(w.cancelled)
            )

        spy = spies(w)
        self.assertTrue(spy.done.wait())

        self.assertEqual(list(spy.done), [[f]])
        self.assertEqual(list(spy.finished), [[f]])
        self.assertEqual(list(spy.result), [[42]])
        self.assertEqual(list(spy.error), [])
        self.assertEqual(list(spy.cancelled), [])

        f = executor.submit(lambda: 1/0)
        w = FutureWatcher(f)
        spy = spies(w)

        self.assertTrue(spy.done.wait())

        self.assertEqual(list(spy.done), [[f]])
        self.assertEqual(list(spy.finished), [[f]])
        self.assertEqual(len(spy.error), 1)
        self.assertIsInstance(spy.error[0][0], ZeroDivisionError)
        self.assertEqual(list(spy.result), [])
        self.assertEqual(list(spy.cancelled), [])

        ev = threading.Event()
        # block the executor to test cancellation
        executor.submit(lambda: ev.wait())
        f = executor.submit(lambda: 0)
        w = FutureWatcher(f)
        self.assertTrue(f.cancel())
        ev.set()

        spy = spies(w)

        self.assertTrue(spy.done.wait())

        self.assertEqual(list(spy.done), [[f]])
        self.assertEqual(list(spy.finished), [])
        self.assertEqual(list(spy.error), [])
        self.assertEqual(list(spy.result), [])
        self.assertEqual(list(spy.cancelled), [[f]])


class TestFutureSetWatcher(CoreAppTestCase):
    def test_watcher(self):
        def spies(w):
            # type: (FutureSetWatcher) -> SimpleNamespace
            return SimpleNamespace(
                doneAt=QSignalSpy(w.doneAt),
                finishedAt=QSignalSpy(w.finishedAt),
                cancelledAt=QSignalSpy(w.cancelledAt),
                resultAt=QSignalSpy(w.resultReadyAt),
                exceptionAt=QSignalSpy(w.exceptionReadyAt),
                doneAll=QSignalSpy(w.doneAll),
            )

        executor = ThreadPoolExecutor(max_workers=5)
        fs = [executor.submit(lambda i: "Hello {}".format(i), i)
              for i in range(10)]
        w = FutureSetWatcher(fs)
        spy = spies(w)

        def as_set(seq):
            # type: (Iterable[list]) -> Set[tuple]
            seq = list(map(tuple, seq))
            set_ = set(seq)
            assert len(set_) == len(seq)
            return set_

        self.assertTrue(spy.doneAll.wait())
        expected = {(i, "Hello {}".format(i)) for i in range(10)}
        self.assertSetEqual(as_set(spy.doneAt), set(enumerate(fs)))
        self.assertSetEqual(as_set(spy.finishedAt), set(enumerate(fs)))
        self.assertSetEqual(as_set(spy.cancelledAt), set())
        self.assertSetEqual(as_set(spy.resultAt), expected)
        self.assertSetEqual(as_set(spy.exceptionAt), set())

        rseq = [random.randrange(0, 10) for _ in range(10)]
        fs = [executor.submit(lambda i: 1 / (i % 3), i) for i in rseq]
        w = FutureSetWatcher(fs)
        spy = spies(w)

        self.assertTrue(spy.doneAll.wait())
        self.assertSetEqual(as_set(spy.doneAt), set(enumerate(fs)))
        self.assertSetEqual(as_set(spy.finishedAt), set(enumerate(fs)))
        self.assertSetEqual(as_set(spy.cancelledAt), set())
        results = {(i, f.result())
                   for i, f in enumerate(fs) if not f.exception()}
        exceptions = {(i, f.exception())
                      for i, f in enumerate(fs) if f.exception()}
        assert len(results | exceptions) == len(fs)
        self.assertSetEqual(as_set(spy.resultAt), results)
        self.assertSetEqual(as_set(spy.exceptionAt), exceptions)

        executor = ThreadPoolExecutor(max_workers=1)
        ev = threading.Event()
        # Block the single worker thread to ensure successful cancel for f2
        f1 = executor.submit(lambda: ev.wait())
        f2 = executor.submit(lambda: 42)
        w = FutureSetWatcher([f1, f2])
        self.assertTrue(f2.cancel())
        # Unblock the worker
        ev.set()

        spy = spies(w)
        self.assertTrue(spy.doneAll.wait())
        self.assertSetEqual(as_set(spy.doneAt), {(0, f1), (1, f2)})
        self.assertSetEqual(as_set(spy.finishedAt), {(0, f1)})
        self.assertSetEqual(as_set(spy.cancelledAt), {(1, f2)})
        self.assertSetEqual(as_set(spy.resultAt), {(0, True)})
        self.assertSetEqual(as_set(spy.exceptionAt), set())

        # doneAll must always be emitted after the doneAt signals.
        executor = ThreadPoolExecutor(max_workers=2)
        futures = [executor.submit(pow, 1000, 1000) for _ in range(100)]
        watcher = FutureSetWatcher(futures)
        emithistory = []
        watcher.doneAt.connect(lambda i, f: emithistory.append(("doneAt", i, f)))
        watcher.doneAll.connect(lambda: emithistory.append(("doneAll", )))

        spy = spies(watcher)
        watcher.wait()
        self.assertEqual(len(spy.doneAll), 0)
        self.assertEqual(len(spy.doneAt), 0)
        watcher.flush()
        self.assertEqual(len(spy.doneAt), 100)
        self.assertEqual(list(spy.doneAll), [[]])
        self.assertSetEqual(set(emithistory[:-1]),
                            {("doneAt", i, f) for i, f in enumerate(futures)})
        self.assertEqual(emithistory[-1], ("doneAll",))

        # doneAll must be emitted even when on an empty futures list
        watcher = FutureSetWatcher()
        watcher.setFutures([])
        spy = spies(watcher)
        self.assertTrue(spy.doneAll.wait())

        watcher = FutureSetWatcher()
        watcher.setFutures([])
        watcher.wait()

        watcher = FutureSetWatcher()
        with self.assertRaises(RuntimeError):
            watcher.wait()

        with unittest.mock.patch.object(watcher, "thread", lambda: 42), \
                self.assertRaises(RuntimeError):
            watcher.flush()


class TestPyOwned(CoreAppTestCase):
    def test_py_owned(self):
        class Obj(QObject, PyOwned):
            pass

        executor = ThreadPoolExecutor()
        ref = SimpleNamespace(obj=Obj())
        wref = weakref.ref(ref.obj)
        event = threading.Event()
        event.clear()

        def clear_ref():
            del ref.obj
            event.set()

        executor.submit(clear_ref)
        event.wait()
        self.assertIsNotNone(wref())
        self.assertIn(wref(), PyOwned._PyOwned__delete_later_set)
        loop = QEventLoop()
        QTimer.singleShot(0, loop.quit)
        loop.exec()
        self.assertIsNone(wref())

    def test_py_owned_enqueued(self):
        # https://www.riverbankcomputing.com/pipermail/pyqt/2020-April/042734.html
        class Emitter(QObject, PyOwned):
            signal = pyqtSignal()
            _p_signal = pyqtSignal()

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                # queued signal -> signal connection
                self._p_signal.connect(self.signal, Qt.QueuedConnection)

            def schedule_emit(self):
                """Schedule `signal` emit"""
                self._p_signal.emit()

        executor = ThreadPoolExecutor(max_workers=4)

        def test_one():
            ref = SimpleNamespace()  # hold single reference to Emitter obj
            ref.obj = Emitter()
            # enqueue 200 meta call events to the obj
            for i in range(200):
                ref.obj.schedule_emit()

            # event signaling the event loop is about to be entered
            event = threading.Event()

            def clear_obj(ref=ref):
                # wait for main thread to signal it is about to enter the event loop
                event.wait()
                del ref.obj  # clear the last/single ref to obj

            executor.submit(clear_obj)

            loop = QEventLoop()
            QTimer.singleShot(0, loop.quit)
            # bytecode optimizations, reduce the time between event.set and
            # exec to minimum
            set = event.set
            exec = loop.exec

            set()  # signal/unblock the worker;
            exec()  # enter event loop to process the queued meta calls

        for i in range(10):
            test_one()