File: test_concurrent_process_forkserver.py

package info (click to toggle)
python-pebble 5.1.1-1
  • links: PTS
  • area: main
  • in suites: sid, trixie
  • size: 436 kB
  • sloc: python: 5,491; makefile: 2
file content (301 lines) | stat: -rw-r--r-- 9,458 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
import os
import time
import pickle
import signal
import unittest
import threading
import dataclasses
import multiprocessing
from concurrent.futures import CancelledError, TimeoutError

from pebble import concurrent, ProcessExpired, ProcessPool


# set start method
supported = False
mp_context = None


methods = multiprocessing.get_all_start_methods()
if 'forkserver' in methods:
    try:
        mp_context = multiprocessing.get_context('forkserver')

        if mp_context.get_start_method() == 'forkserver':
            supported = True
        else:
            raise Exception(mp_context.get_start_method())
    except RuntimeError:  # child process
        pass
else:
    mp_context = multiprocessing.get_context()


def not_decorated(argument, keyword_argument=0):
    return argument + keyword_argument


@concurrent.process(context=mp_context)
def decorated(argument, keyword_argument=0):
    """A docstring."""
    return argument + keyword_argument


@concurrent.process(context=mp_context)
def error_decorated():
    raise RuntimeError("BOOM!")


@concurrent.process(context=mp_context)
def error_returned():
    return RuntimeError("BOOM!")


@concurrent.process(context=mp_context)
def pickling_error_decorated():
    event = threading.Event()
    return event


@dataclasses.dataclass(frozen=True)
class FrozenError(Exception):
    pass


@concurrent.process(context=mp_context)
def frozen_error_decorated():
    raise FrozenError()


@concurrent.process(context=mp_context)
def critical_decorated():
    os._exit(123)


@concurrent.process(context=mp_context)
def decorated_cancel():
    time.sleep(10)


@concurrent.process(timeout=0.1, context=mp_context)
def long_decorated():
    time.sleep(10)


@concurrent.process(timeout=0.1, context=mp_context)
def sigterm_decorated():
    signal.signal(signal.SIGTERM, signal.SIG_IGN)
    time.sleep(10)


@concurrent.process(daemon=False, context=mp_context)
def daemon_keyword_decorated():
    return multiprocessing.current_process().daemon


@concurrent.process(pool=ProcessPool(1, context=mp_context))
def pool_decorated(_argument, _keyword_argument=0):
    return multiprocessing.current_process().pid


class ProcessConcurrentObj:
    a = 0

    def __init__(self):
        self.b = 1

    @classmethod
    @concurrent.process(context=mp_context)
    def clsmethod(cls):
        return cls.a

    @concurrent.process(context=mp_context)
    def instmethod(self):
        return self.b


@unittest.skipIf(not supported, "Start method is not supported")
class ProcessConcurrentSub1(ProcessConcurrentObj):
    @classmethod
    @concurrent.process(context=mp_context)
    def clsmethod(cls):
        return cls.a + 1

    @concurrent.process(context=mp_context)
    def instmethod(self):
        return self.b + 1


class ProcessConcurrentSub2(ProcessConcurrentObj):
    @classmethod
    @concurrent.process(context=mp_context)
    def clsmethod(cls):
        return cls.a + 2

    @concurrent.process(context=mp_context)
    def instmethod(self):
        return self.b + 2


class CallableClass:
    def __call__(self, argument, keyword_argument=0):
        return argument + keyword_argument


class TestProcessConcurrent(unittest.TestCase):
    def setUp(self):
        self.results = 0
        self.exception = None
        self.event = threading.Event()
        self.event.clear()
        self.concurrentobj = ProcessConcurrentObj()
        self.concurrentobj1 = ProcessConcurrentSub1()
        self.concurrentobj2 = ProcessConcurrentSub2()

    def callback(self, future):
        try:
            self.results = future.result()
        except (ProcessExpired, RuntimeError, TimeoutError) as error:
            self.exception = error
        finally:
            self.event.set()

    def test_docstring(self):
        """Process Forkserver docstring is preserved."""
        self.assertEqual(decorated.__doc__, "A docstring.")

    def test_wrong_timeout(self):
        """Process Forkserver TypeError is raised if timeout is not number."""
        with self.assertRaises(TypeError):
            @concurrent.process(timeout='Foo', context=mp_context)
            def function():
                return

    def test_class_method(self):
        """Process Forkserver decorated classmethods."""
        future = ProcessConcurrentObj.clsmethod()
        self.assertEqual(future.result(), 0)
        future = ProcessConcurrentSub1.clsmethod()
        self.assertEqual(future.result(), 1)
        future = ProcessConcurrentSub2.clsmethod()
        self.assertEqual(future.result(), 2)

    def test_instance_method(self):
        """Process Forkserver decorated instance methods."""
        future = self.concurrentobj.instmethod()
        self.assertEqual(future.result(), 1)
        future = self.concurrentobj1.instmethod()
        self.assertEqual(future.result(), 2)
        future = self.concurrentobj2.instmethod()
        self.assertEqual(future.result(), 3)

    def test_not_decorated_results(self):
        """Process Forkserver results are produced."""
        non_decorated = concurrent.process(not_decorated, context=mp_context)
        future = non_decorated(1, 1)
        self.assertEqual(future.result(), 2)

    def test_decorated_results(self):
        """Process Forkserver results are produced."""
        future = decorated(1, 1)
        self.assertEqual(future.result(), 2)

    def test_decorated_results_callback(self):
        """Process Forkserver results are forwarded to the callback."""
        future = decorated(1, 1)
        future.add_done_callback(self.callback)
        self.event.wait(timeout=1)
        self.assertEqual(self.results, 2)

    def test_error_decorated(self):
        """Process Forkserver errors are raised by future.result."""
        future = error_decorated()
        with self.assertRaises(RuntimeError):
            future.result()

    def test_error_returned(self):
        """Process Forkserver returned errors are returned by future.result."""
        future = error_returned()
        self.assertIsInstance(future.result(), RuntimeError)

    def test_error_decorated_callback(self):
        """Process Forkserver errors are forwarded to callback."""
        future = error_decorated()
        future.add_done_callback(self.callback)
        self.event.wait(timeout=1)
        self.assertTrue(isinstance(self.exception, RuntimeError),
                        msg=str(self.exception))

    def test_pickling_error_decorated(self):
        """Process Forkserver pickling errors are raised by future.result."""
        future = pickling_error_decorated()
        with self.assertRaises((pickle.PicklingError, TypeError)):
            future.result()

    def test_frozen_error_decorated(self):
        """Process Fork frozen errors are raised by future.result."""
        future = frozen_error_decorated()
        with self.assertRaises(FrozenError):
            future.result()

    def test_timeout_decorated(self):
        """Process Forkserver raises TimeoutError if so."""
        future = long_decorated()
        with self.assertRaises(TimeoutError):
            future.result()

    def test_timeout_decorated_callback(self):
        """Process Forkserver TimeoutError is forwarded to callback."""
        future = long_decorated()
        future.add_done_callback(self.callback)
        self.event.wait(timeout=1)
        self.assertTrue(isinstance(self.exception, TimeoutError),
                        msg=str(self.exception))

    def test_decorated_dead_process(self):
        """Process Forkserver ProcessExpired is raised if process dies."""
        future = critical_decorated()
        with self.assertRaises(ProcessExpired) as exc_ctx:
            future.result()
        self.assertEqual(exc_ctx.exception.exitcode, 123)
        self.assertIsInstance(exc_ctx.exception.pid, int)

    def test_timeout_decorated_callback(self):
        """Process Forkserver ProcessExpired is forwarded to callback."""
        future = critical_decorated()
        future.add_done_callback(self.callback)
        self.event.wait(timeout=1)
        self.assertTrue(isinstance(self.exception, ProcessExpired),
                        msg=str(self.exception))

    def test_cancel_decorated(self):
        """Process Forkserver raises CancelledError if future was cancelled."""
        future = decorated_cancel()
        future.cancel()
        self.assertRaises(CancelledError, future.result)

    @unittest.skipIf(os.name == 'nt', "Test won't run on Windows.")
    def test_decorated_ignoring_sigterm(self):
        """Process Forkserver Concurrent ignored SIGTERM signal are handled on Unix."""
        future = sigterm_decorated()
        with self.assertRaises(TimeoutError):
            future.result()

    def test_daemon_keyword_decorated(self):
        """Daemon keyword can be passed to a decorated function and spawns correctly."""
        f = daemon_keyword_decorated()
        dec_out = f.result()
        self.assertEqual(dec_out, False)

    def test_callable_objects(self):
        """Callable objects are correctly handled."""
        callable_object = concurrent.process(context=mp_context)(CallableClass())
        f = callable_object(1)

        self.assertEqual(f.result(), 1)

    def test_pool_decorated(self):
        """Process Forkserver pool decorated function."""
        future1 = pool_decorated(1, 1)
        future2 = pool_decorated(1, 1)
        self.assertEqual(future1.result(), future2.result())