blob: de5f782ee4afdfaaa00a6dd11cba8b685e4500c3 [file] [log] [blame]
Nick Coghlan9a767352013-12-17 22:17:26 +10001# tests __main__ module handling in multiprocessing
Terry Jan Reedybc7c96b2014-06-13 14:23:43 -04002from test import support
3# Skip tests if _thread or _multiprocessing wasn't built.
4support.import_module('_thread')
5support.import_module('_multiprocessing')
Nick Coghlan9a767352013-12-17 22:17:26 +10006
7import importlib
8import importlib.machinery
9import zipimport
10import unittest
11import sys
12import os
13import os.path
14import py_compile
15
Nick Coghlan9a767352013-12-17 22:17:26 +100016from test.script_helper import (
17 make_pkg, make_script, make_zip_pkg, make_zip_script,
18 assert_python_ok, assert_python_failure, temp_dir,
19 spawn_python, kill_python)
20
Nick Coghlan05385292013-12-20 22:14:03 +100021# Look up which start methods are available to test
22import multiprocessing
23AVAILABLE_START_METHODS = set(multiprocessing.get_all_start_methods())
Nick Coghlan9a767352013-12-17 22:17:26 +100024
Victor Stinner2bb8a082014-09-03 23:48:08 +020025# Issue #22332: Skip tests if sem_open implementation is broken.
26support.import_module('multiprocessing.synchronize')
27
Nick Coghlan9a767352013-12-17 22:17:26 +100028verbose = support.verbose
29
30test_source = """\
31# multiprocessing includes all sorts of shenanigans to make __main__
32# attributes accessible in the subprocess in a pickle compatible way.
33
34# We run the "doesn't work in the interactive interpreter" example from
35# the docs to make sure it *does* work from an executed __main__,
36# regardless of the invocation mechanism
37
38import sys
39import time
40from multiprocessing import Pool, set_start_method
41
42# We use this __main__ defined function in the map call below in order to
43# check that multiprocessing in correctly running the unguarded
44# code in child processes and then making it available as __main__
45def f(x):
46 return x*x
47
48# Check explicit relative imports
49if "check_sibling" in __file__:
50 # We're inside a package and not in a __main__.py file
51 # so make sure explicit relative imports work correctly
52 from . import sibling
53
54if __name__ == '__main__':
55 start_method = sys.argv[1]
56 set_start_method(start_method)
57 p = Pool(5)
58 results = []
59 p.map_async(f, [1, 2, 3], callback=results.extend)
Nick Coghlan23f597e2013-12-23 18:17:20 +100060 deadline = time.time() + 10 # up to 10 s to report the results
Nick Coghlan9a767352013-12-17 22:17:26 +100061 while not results:
62 time.sleep(0.05)
63 if time.time() > deadline:
64 raise RuntimeError("Timed out waiting for results")
65 results.sort()
66 print(start_method, "->", results)
67"""
68
69test_source_main_skipped_in_children = """\
70# __main__.py files have an implied "if __name__ == '__main__'" so
71# multiprocessing should always skip running them in child processes
72
73# This means we can't use __main__ defined functions in child processes,
74# so we just use "int" as a passthrough operation below
75
76if __name__ != "__main__":
77 raise RuntimeError("Should only be called as __main__!")
78
79import sys
80import time
81from multiprocessing import Pool, set_start_method
82
83start_method = sys.argv[1]
84set_start_method(start_method)
85p = Pool(5)
86results = []
87p.map_async(int, [1, 4, 9], callback=results.extend)
Nick Coghlan23f597e2013-12-23 18:17:20 +100088deadline = time.time() + 10 # up to 10 s to report the results
Nick Coghlan9a767352013-12-17 22:17:26 +100089while not results:
90 time.sleep(0.05)
91 if time.time() > deadline:
92 raise RuntimeError("Timed out waiting for results")
93results.sort()
94print(start_method, "->", results)
95"""
96
97# These helpers were copied from test_cmd_line_script & tweaked a bit...
98
99def _make_test_script(script_dir, script_basename,
100 source=test_source, omit_suffix=False):
101 to_return = make_script(script_dir, script_basename,
102 source, omit_suffix)
103 # Hack to check explicit relative imports
104 if script_basename == "check_sibling":
105 make_script(script_dir, "sibling", "")
106 importlib.invalidate_caches()
107 return to_return
108
109def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
110 source=test_source, depth=1):
111 to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
112 source, depth)
113 importlib.invalidate_caches()
114 return to_return
115
116# There's no easy way to pass the script directory in to get
117# -m to work (avoiding that is the whole point of making
118# directories and zipfiles executable!)
119# So we fake it for testing purposes with a custom launch script
120launch_source = """\
121import sys, os.path, runpy
122sys.path.insert(0, %s)
123runpy._run_module_as_main(%r)
124"""
125
126def _make_launch_script(script_dir, script_basename, module_name, path=None):
127 if path is None:
128 path = "os.path.dirname(__file__)"
129 else:
130 path = repr(path)
131 source = launch_source % (path, module_name)
132 to_return = make_script(script_dir, script_basename, source)
133 importlib.invalidate_caches()
134 return to_return
135
136class MultiProcessingCmdLineMixin():
137 maxDiff = None # Show full tracebacks on subprocess failure
138
Nick Coghlanfeae73e2013-12-19 21:53:31 +1000139 def setUp(self):
Nick Coghlan05385292013-12-20 22:14:03 +1000140 if self.start_method not in AVAILABLE_START_METHODS:
Nick Coghlanfeae73e2013-12-19 21:53:31 +1000141 self.skipTest("%r start method not available" % self.start_method)
Nick Coghlan9a767352013-12-17 22:17:26 +1000142
143 def _check_output(self, script_name, exit_code, out, err):
144 if verbose > 1:
145 print("Output from test script %r:" % script_name)
Serhiy Storchakab0749ca2015-03-25 01:33:19 +0200146 print(repr(out))
Nick Coghlan9a767352013-12-17 22:17:26 +1000147 self.assertEqual(exit_code, 0)
148 self.assertEqual(err.decode('utf-8'), '')
149 expected_results = "%s -> [1, 4, 9]" % self.start_method
150 self.assertEqual(out.decode('utf-8').strip(), expected_results)
151
152 def _check_script(self, script_name, *cmd_line_switches):
153 if not __debug__:
154 cmd_line_switches += ('-' + 'O' * sys.flags.optimize,)
155 run_args = cmd_line_switches + (script_name, self.start_method)
156 rc, out, err = assert_python_ok(*run_args, __isolated=False)
157 self._check_output(script_name, rc, out, err)
158
159 def test_basic_script(self):
160 with temp_dir() as script_dir:
161 script_name = _make_test_script(script_dir, 'script')
162 self._check_script(script_name)
163
164 def test_basic_script_no_suffix(self):
165 with temp_dir() as script_dir:
166 script_name = _make_test_script(script_dir, 'script',
167 omit_suffix=True)
168 self._check_script(script_name)
169
170 def test_ipython_workaround(self):
171 # Some versions of the IPython launch script are missing the
172 # __name__ = "__main__" guard, and multiprocessing has long had
173 # a workaround for that case
174 # See https://github.com/ipython/ipython/issues/4698
175 source = test_source_main_skipped_in_children
176 with temp_dir() as script_dir:
177 script_name = _make_test_script(script_dir, 'ipython',
178 source=source)
179 self._check_script(script_name)
180 script_no_suffix = _make_test_script(script_dir, 'ipython',
181 source=source,
182 omit_suffix=True)
183 self._check_script(script_no_suffix)
184
185 def test_script_compiled(self):
186 with temp_dir() as script_dir:
187 script_name = _make_test_script(script_dir, 'script')
188 py_compile.compile(script_name, doraise=True)
189 os.remove(script_name)
190 pyc_file = support.make_legacy_pyc(script_name)
191 self._check_script(pyc_file)
192
193 def test_directory(self):
194 source = self.main_in_children_source
195 with temp_dir() as script_dir:
196 script_name = _make_test_script(script_dir, '__main__',
197 source=source)
198 self._check_script(script_dir)
199
200 def test_directory_compiled(self):
201 source = self.main_in_children_source
202 with temp_dir() as script_dir:
203 script_name = _make_test_script(script_dir, '__main__',
204 source=source)
205 py_compile.compile(script_name, doraise=True)
206 os.remove(script_name)
207 pyc_file = support.make_legacy_pyc(script_name)
208 self._check_script(script_dir)
209
210 def test_zipfile(self):
211 source = self.main_in_children_source
212 with temp_dir() as script_dir:
213 script_name = _make_test_script(script_dir, '__main__',
214 source=source)
215 zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
216 self._check_script(zip_name)
217
218 def test_zipfile_compiled(self):
219 source = self.main_in_children_source
220 with temp_dir() as script_dir:
221 script_name = _make_test_script(script_dir, '__main__',
222 source=source)
223 compiled_name = py_compile.compile(script_name, doraise=True)
224 zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
225 self._check_script(zip_name)
226
227 def test_module_in_package(self):
228 with temp_dir() as script_dir:
229 pkg_dir = os.path.join(script_dir, 'test_pkg')
230 make_pkg(pkg_dir)
231 script_name = _make_test_script(pkg_dir, 'check_sibling')
232 launch_name = _make_launch_script(script_dir, 'launch',
233 'test_pkg.check_sibling')
234 self._check_script(launch_name)
235
236 def test_module_in_package_in_zipfile(self):
237 with temp_dir() as script_dir:
238 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
239 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name)
240 self._check_script(launch_name)
241
242 def test_module_in_subpackage_in_zipfile(self):
243 with temp_dir() as script_dir:
244 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
245 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
246 self._check_script(launch_name)
247
248 def test_package(self):
249 source = self.main_in_children_source
250 with temp_dir() as script_dir:
251 pkg_dir = os.path.join(script_dir, 'test_pkg')
252 make_pkg(pkg_dir)
253 script_name = _make_test_script(pkg_dir, '__main__',
254 source=source)
255 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
256 self._check_script(launch_name)
257
258 def test_package_compiled(self):
259 source = self.main_in_children_source
260 with temp_dir() as script_dir:
261 pkg_dir = os.path.join(script_dir, 'test_pkg')
262 make_pkg(pkg_dir)
263 script_name = _make_test_script(pkg_dir, '__main__',
264 source=source)
265 compiled_name = py_compile.compile(script_name, doraise=True)
266 os.remove(script_name)
267 pyc_file = support.make_legacy_pyc(script_name)
268 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
269 self._check_script(launch_name)
270
271# Test all supported start methods (setupClass skips as appropriate)
272
273class SpawnCmdLineTest(MultiProcessingCmdLineMixin, unittest.TestCase):
274 start_method = 'spawn'
275 main_in_children_source = test_source_main_skipped_in_children
276
277class ForkCmdLineTest(MultiProcessingCmdLineMixin, unittest.TestCase):
278 start_method = 'fork'
279 main_in_children_source = test_source
280
281class ForkServerCmdLineTest(MultiProcessingCmdLineMixin, unittest.TestCase):
282 start_method = 'forkserver'
283 main_in_children_source = test_source_main_skipped_in_children
284
Nick Coghlanfeae73e2013-12-19 21:53:31 +1000285def tearDownModule():
Nick Coghlan9a767352013-12-17 22:17:26 +1000286 support.reap_children()
287
288if __name__ == '__main__':
Nick Coghlanfeae73e2013-12-19 21:53:31 +1000289 unittest.main()