Debian Codegraph @

lib-python/3/test/test_concurrent_futures/test_process_pool.py

raw symbols SCIP
1 import os
2 import sys
3 import time
4 import unittest
5 from concurrent import futures
6 from concurrent.futures.process import BrokenProcessPool
7
8 from test import support
9 from test.support import hashlib_helper, cpython_only
10
11 from .executor import ExecutorTest, mul
12 from .util import (
13 ProcessPoolForkMixin, ProcessPoolForkserverMixin, ProcessPoolSpawnMixin,
14 create_executor_tests, setup_module)
15
16
17 class EventfulGCObj():
18 def __init__(self, mgr):
19 self.event = mgr.Event()
20
21 def __del__(self):
22 self.event.set()
23
24
25 class ProcessPoolExecutorTest(ExecutorTest):
26
27 @unittest.skipUnless(sys.platform=='win32', 'Windows-only process limit')
28 def test_max_workers_too_large(self):
29 with self.assertRaisesRegex(ValueError,
30 "max_workers must be <= 61"):
31 futures.ProcessPoolExecutor(max_workers=62)
32
33 def test_killed_child(self):
34 # When a child process is abruptly terminated, the whole pool gets
35 # "broken".
36 futures = [self.executor.submit(time.sleep, 3)]
37 # Get one of the processes, and terminate (kill) it
38 p = next(iter(self.executor._processes.values()))
39 p.terminate()
40 for fut in futures:
41 self.assertRaises(BrokenProcessPool, fut.result)
42 # Submitting other jobs fails as well.
43 self.assertRaises(BrokenProcessPool, self.executor.submit, pow, 2, 8)
44
45 def test_map_chunksize(self):
46 def bad_map():
47 list(self.executor.map(pow, range(40), range(40), chunksize=-1))
48
49 ref = list(map(pow, range(40), range(40)))
50 self.assertEqual(
51 list(self.executor.map(pow, range(40), range(40), chunksize=6)),
52 ref)
53 self.assertEqual(
54 list(self.executor.map(pow, range(40), range(40), chunksize=50)),
55 ref)
56 self.assertEqual(
57 list(self.executor.map(pow, range(40), range(40), chunksize=40)),
58 ref)
59 self.assertRaises(ValueError, bad_map)
60
61 @classmethod
62 def _test_traceback(cls):
63 raise RuntimeError(123) # some comment
64
65 def test_traceback(self):
66 # We want ensure that the traceback from the child process is
67 # contained in the traceback raised in the main process.
68 future = self.executor.submit(self._test_traceback)
69 with self.assertRaises(Exception) as cm:
70 future.result()
71
72 exc = cm.exception
73 self.assertIs(type(exc), RuntimeError)
74 self.assertEqual(exc.args, (123,))
75 cause = exc.__cause__
76 self.assertIs(type(cause), futures.process._RemoteTraceback)
77 self.assertIn('raise RuntimeError(123) # some comment', cause.tb)
78
79 with support.captured_stderr() as f1:
80 try:
81 raise exc
82 except RuntimeError:
83 sys.excepthook(*sys.exc_info())
84 self.assertIn('raise RuntimeError(123) # some comment',
85 f1.getvalue())
86
87 @hashlib_helper.requires_hashdigest('md5')
88 @cpython_only
89 def test_ressources_gced_in_workers(self):
90 # Ensure that argument for a job are correctly gc-ed after the job
91 # is finished
92 mgr = self.get_context().Manager()
93 obj = EventfulGCObj(mgr)
94 future = self.executor.submit(id, obj)
95 future.result()
96
97 self.assertTrue(obj.event.wait(timeout=1))
98
99 # explicitly destroy the object to ensure that EventfulGCObj.__del__()
100 # is called while manager is still running.
101 obj = None
102 support.gc_collect()
103
104 mgr.shutdown()
105 mgr.join()
106
107 def test_saturation(self):
108 executor = self.executor
109 mp_context = self.get_context()
110 sem = mp_context.Semaphore(0)
111 job_count = 15 * executor._max_workers
112 for _ in range(job_count):
113 executor.submit(sem.acquire)
114 self.assertEqual(len(executor._processes), executor._max_workers)
115 for _ in range(job_count):
116 sem.release()
117
118 def test_idle_process_reuse_one(self):
119 executor = self.executor
120 assert executor._max_workers >= 4
121 if self.get_context().get_start_method(allow_none=False) == "fork":
122 raise unittest.SkipTest("Incompatible with the fork start method.")
123 executor.submit(mul, 21, 2).result()
124 executor.submit(mul, 6, 7).result()
125 executor.submit(mul, 3, 14).result()
126 self.assertEqual(len(executor._processes), 1)
127
128 def test_idle_process_reuse_multiple(self):
129 executor = self.executor
130 assert executor._max_workers <= 5
131 if self.get_context().get_start_method(allow_none=False) == "fork":
132 raise unittest.SkipTest("Incompatible with the fork start method.")
133 executor.submit(mul, 12, 7).result()
134 executor.submit(mul, 33, 25)
135 executor.submit(mul, 25, 26).result()
136 executor.submit(mul, 18, 29)
137 executor.submit(mul, 1, 2).result()
138 executor.submit(mul, 0, 9)
139 self.assertLessEqual(len(executor._processes), 3)
140 executor.shutdown()
141
142 def test_max_tasks_per_child(self):
143 context = self.get_context()
144 if context.get_start_method(allow_none=False) == "fork":
145 with self.assertRaises(ValueError):
146 self.executor_type(1, mp_context=context, max_tasks_per_child=3)
147 return
148 # not using self.executor as we need to control construction.
149 # arguably this could go in another class w/o that mixin.
150 executor = self.executor_type(
151 1, mp_context=context, max_tasks_per_child=3)
152 f1 = executor.submit(os.getpid)
153 original_pid = f1.result()
154 # The worker pid remains the same as the worker could be reused
155 f2 = executor.submit(os.getpid)
156 self.assertEqual(f2.result(), original_pid)
157 self.assertEqual(len(executor._processes), 1)
158 f3 = executor.submit(os.getpid)
159 self.assertEqual(f3.result(), original_pid)
160
161 # A new worker is spawned, with a statistically different pid,
162 # while the previous was reaped.
163 f4 = executor.submit(os.getpid)
164 new_pid = f4.result()
165 self.assertNotEqual(original_pid, new_pid)
166 self.assertEqual(len(executor._processes), 1)
167
168 executor.shutdown()
169
170 def test_max_tasks_per_child_defaults_to_spawn_context(self):
171 # not using self.executor as we need to control construction.
172 # arguably this could go in another class w/o that mixin.
173 executor = self.executor_type(1, max_tasks_per_child=3)
174 self.assertEqual(executor._mp_context.get_start_method(), "spawn")
175
176 def test_max_tasks_early_shutdown(self):
177 context = self.get_context()
178 if context.get_start_method(allow_none=False) == "fork":
179 raise unittest.SkipTest("Incompatible with the fork start method.")
180 # not using self.executor as we need to control construction.
181 # arguably this could go in another class w/o that mixin.
182 executor = self.executor_type(
183 3, mp_context=context, max_tasks_per_child=1)
184 futures = []
185 for i in range(6):
186 futures.append(executor.submit(mul, i, i))
187 executor.shutdown()
188 for i, future in enumerate(futures):
189 self.assertEqual(future.result(), mul(i, i))
190
191
192 create_executor_tests(globals(), ProcessPoolExecutorTest,
193 executor_mixins=(ProcessPoolForkMixin,
194 ProcessPoolForkserverMixin,
195 ProcessPoolSpawnMixin))
196
197
198 def setUpModule():
199 setup_module()
200
201
202 if __name__ == "__main__":
203 unittest.main()