Benjamin Peterson | 90f5ba5 | 2010-03-11 22:53:45 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Georg Brandl | 86b2fb9 | 2008-07-16 03:43:04 +0000 | [diff] [blame] | 2 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 3 | # |
| 4 | # Unit tests for the multiprocessing package |
| 5 | # |
| 6 | |
| 7 | import unittest |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 8 | import queue as pyqueue |
| 9 | import time |
Alexandre Vassalotti | c57a84f | 2009-07-17 12:07:01 +0000 | [diff] [blame] | 10 | import io |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 11 | import sys |
| 12 | import os |
| 13 | import gc |
Antoine Pitrou | c824e9a | 2011-04-05 18:11:33 +0200 | [diff] [blame] | 14 | import errno |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 15 | import signal |
| 16 | import array |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 17 | import socket |
| 18 | import random |
| 19 | import logging |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 20 | import test.support |
Richard Oudkerk | e88a244 | 2012-08-14 11:41:32 +0100 | [diff] [blame] | 21 | import test.script_helper |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 22 | |
Benjamin Peterson | e5384b0 | 2008-10-04 22:00:42 +0000 | [diff] [blame] | 23 | |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 24 | # Skip tests if _multiprocessing wasn't built. |
| 25 | _multiprocessing = test.support.import_module('_multiprocessing') |
| 26 | # Skip tests if sem_open implementation is broken. |
| 27 | test.support.import_module('multiprocessing.synchronize') |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 28 | # import threading after _multiprocessing to raise a more revelant error |
| 29 | # message: "No module named _multiprocessing". _multiprocessing is not compiled |
| 30 | # without thread support. |
| 31 | import threading |
Benjamin Peterson | e5384b0 | 2008-10-04 22:00:42 +0000 | [diff] [blame] | 32 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 33 | import multiprocessing.dummy |
| 34 | import multiprocessing.connection |
| 35 | import multiprocessing.managers |
| 36 | import multiprocessing.heap |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 37 | import multiprocessing.pool |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 38 | |
Charles-François Natali | e51c8da | 2011-09-21 18:48:21 +0200 | [diff] [blame] | 39 | from multiprocessing import util |
| 40 | |
| 41 | try: |
| 42 | from multiprocessing import reduction |
| 43 | HAS_REDUCTION = True |
| 44 | except ImportError: |
| 45 | HAS_REDUCTION = False |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 46 | |
Brian Curtin | afa88b5 | 2010-10-07 01:12:19 +0000 | [diff] [blame] | 47 | try: |
| 48 | from multiprocessing.sharedctypes import Value, copy |
| 49 | HAS_SHAREDCTYPES = True |
| 50 | except ImportError: |
| 51 | HAS_SHAREDCTYPES = False |
| 52 | |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 53 | try: |
| 54 | import msvcrt |
| 55 | except ImportError: |
| 56 | msvcrt = None |
| 57 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 58 | # |
| 59 | # |
| 60 | # |
| 61 | |
Benjamin Peterson | 2bc91df | 2008-07-13 18:45:30 +0000 | [diff] [blame] | 62 | def latin(s): |
| 63 | return s.encode('latin') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 64 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 65 | # |
| 66 | # Constants |
| 67 | # |
| 68 | |
| 69 | LOG_LEVEL = util.SUBWARNING |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 70 | #LOG_LEVEL = logging.DEBUG |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 71 | |
| 72 | DELTA = 0.1 |
| 73 | CHECK_TIMINGS = False # making true makes tests take a lot longer |
| 74 | # and can sometimes cause some non-serious |
| 75 | # failures because some calls block a bit |
| 76 | # longer than expected |
| 77 | if CHECK_TIMINGS: |
| 78 | TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4 |
| 79 | else: |
| 80 | TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1 |
| 81 | |
| 82 | HAVE_GETVALUE = not getattr(_multiprocessing, |
| 83 | 'HAVE_BROKEN_SEM_GETVALUE', False) |
| 84 | |
Jesse Noller | 6214edd | 2009-01-19 16:23:53 +0000 | [diff] [blame] | 85 | WIN32 = (sys.platform == "win32") |
| 86 | |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 87 | try: |
| 88 | MAXFD = os.sysconf("SC_OPEN_MAX") |
| 89 | except: |
| 90 | MAXFD = 256 |
| 91 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 92 | # |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 93 | # Some tests require ctypes |
| 94 | # |
| 95 | |
| 96 | try: |
Florent Xicluna | aa17106 | 2010-08-14 15:56:42 +0000 | [diff] [blame] | 97 | from ctypes import Structure, c_int, c_double |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 98 | except ImportError: |
| 99 | Structure = object |
| 100 | c_int = c_double = None |
| 101 | |
Charles-François Natali | 3be0095 | 2011-11-22 18:36:39 +0100 | [diff] [blame] | 102 | |
| 103 | def check_enough_semaphores(): |
| 104 | """Check that the system supports enough semaphores to run the test.""" |
| 105 | # minimum number of semaphores available according to POSIX |
| 106 | nsems_min = 256 |
| 107 | try: |
| 108 | nsems = os.sysconf("SC_SEM_NSEMS_MAX") |
| 109 | except (AttributeError, ValueError): |
| 110 | # sysconf not available or setting not available |
| 111 | return |
| 112 | if nsems == -1 or nsems >= nsems_min: |
| 113 | return |
| 114 | raise unittest.SkipTest("The OS doesn't support enough semaphores " |
| 115 | "to run the test (required: %d)." % nsems_min) |
| 116 | |
| 117 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 118 | # |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 119 | # Creates a wrapper for a function which records the time it takes to finish |
| 120 | # |
| 121 | |
| 122 | class TimingWrapper(object): |
| 123 | |
| 124 | def __init__(self, func): |
| 125 | self.func = func |
| 126 | self.elapsed = None |
| 127 | |
| 128 | def __call__(self, *args, **kwds): |
| 129 | t = time.time() |
| 130 | try: |
| 131 | return self.func(*args, **kwds) |
| 132 | finally: |
| 133 | self.elapsed = time.time() - t |
| 134 | |
| 135 | # |
| 136 | # Base class for test cases |
| 137 | # |
| 138 | |
| 139 | class BaseTestCase(object): |
| 140 | |
| 141 | ALLOWED_TYPES = ('processes', 'manager', 'threads') |
| 142 | |
| 143 | def assertTimingAlmostEqual(self, a, b): |
| 144 | if CHECK_TIMINGS: |
| 145 | self.assertAlmostEqual(a, b, 1) |
| 146 | |
| 147 | def assertReturnsIfImplemented(self, value, func, *args): |
| 148 | try: |
| 149 | res = func(*args) |
| 150 | except NotImplementedError: |
| 151 | pass |
| 152 | else: |
| 153 | return self.assertEqual(value, res) |
| 154 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 155 | # For the sanity of Windows users, rather than crashing or freezing in |
| 156 | # multiple ways. |
| 157 | def __reduce__(self, *args): |
| 158 | raise NotImplementedError("shouldn't try to pickle a test case") |
| 159 | |
| 160 | __reduce_ex__ = __reduce__ |
| 161 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 162 | # |
| 163 | # Return the value of a semaphore |
| 164 | # |
| 165 | |
| 166 | def get_value(self): |
| 167 | try: |
| 168 | return self.get_value() |
| 169 | except AttributeError: |
| 170 | try: |
| 171 | return self._Semaphore__value |
| 172 | except AttributeError: |
| 173 | try: |
| 174 | return self._value |
| 175 | except AttributeError: |
| 176 | raise NotImplementedError |
| 177 | |
| 178 | # |
| 179 | # Testcases |
| 180 | # |
| 181 | |
| 182 | class _TestProcess(BaseTestCase): |
| 183 | |
| 184 | ALLOWED_TYPES = ('processes', 'threads') |
| 185 | |
| 186 | def test_current(self): |
| 187 | if self.TYPE == 'threads': |
| 188 | return |
| 189 | |
| 190 | current = self.current_process() |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 191 | authkey = current.authkey |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 192 | |
| 193 | self.assertTrue(current.is_alive()) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 194 | self.assertTrue(not current.daemon) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 195 | self.assertIsInstance(authkey, bytes) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 196 | self.assertTrue(len(authkey) > 0) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 197 | self.assertEqual(current.ident, os.getpid()) |
| 198 | self.assertEqual(current.exitcode, None) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 199 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 200 | @classmethod |
| 201 | def _test(cls, q, *args, **kwds): |
| 202 | current = cls.current_process() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 203 | q.put(args) |
| 204 | q.put(kwds) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 205 | q.put(current.name) |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 206 | if cls.TYPE != 'threads': |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 207 | q.put(bytes(current.authkey)) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 208 | q.put(current.pid) |
| 209 | |
| 210 | def test_process(self): |
| 211 | q = self.Queue(1) |
| 212 | e = self.Event() |
| 213 | args = (q, 1, 2) |
| 214 | kwargs = {'hello':23, 'bye':2.54} |
| 215 | name = 'SomeProcess' |
| 216 | p = self.Process( |
| 217 | target=self._test, args=args, kwargs=kwargs, name=name |
| 218 | ) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 219 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 220 | current = self.current_process() |
| 221 | |
| 222 | if self.TYPE != 'threads': |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 223 | self.assertEqual(p.authkey, current.authkey) |
| 224 | self.assertEqual(p.is_alive(), False) |
| 225 | self.assertEqual(p.daemon, True) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 226 | self.assertNotIn(p, self.active_children()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 227 | self.assertTrue(type(self.active_children()) is list) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 228 | self.assertEqual(p.exitcode, None) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 229 | |
| 230 | p.start() |
| 231 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 232 | self.assertEqual(p.exitcode, None) |
| 233 | self.assertEqual(p.is_alive(), True) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 234 | self.assertIn(p, self.active_children()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 235 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 236 | self.assertEqual(q.get(), args[1:]) |
| 237 | self.assertEqual(q.get(), kwargs) |
| 238 | self.assertEqual(q.get(), p.name) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 239 | if self.TYPE != 'threads': |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 240 | self.assertEqual(q.get(), current.authkey) |
| 241 | self.assertEqual(q.get(), p.pid) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 242 | |
| 243 | p.join() |
| 244 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 245 | self.assertEqual(p.exitcode, 0) |
| 246 | self.assertEqual(p.is_alive(), False) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 247 | self.assertNotIn(p, self.active_children()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 248 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 249 | @classmethod |
| 250 | def _test_terminate(cls): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 251 | time.sleep(1000) |
| 252 | |
| 253 | def test_terminate(self): |
| 254 | if self.TYPE == 'threads': |
| 255 | return |
| 256 | |
| 257 | p = self.Process(target=self._test_terminate) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 258 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 259 | p.start() |
| 260 | |
| 261 | self.assertEqual(p.is_alive(), True) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 262 | self.assertIn(p, self.active_children()) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 263 | self.assertEqual(p.exitcode, None) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 264 | |
| 265 | p.terminate() |
| 266 | |
| 267 | join = TimingWrapper(p.join) |
| 268 | self.assertEqual(join(), None) |
| 269 | self.assertTimingAlmostEqual(join.elapsed, 0.0) |
| 270 | |
| 271 | self.assertEqual(p.is_alive(), False) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 272 | self.assertNotIn(p, self.active_children()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 273 | |
| 274 | p.join() |
| 275 | |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 276 | # XXX sometimes get p.exitcode == 0 on Windows ... |
| 277 | #self.assertEqual(p.exitcode, -signal.SIGTERM) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 278 | |
| 279 | def test_cpu_count(self): |
| 280 | try: |
| 281 | cpus = multiprocessing.cpu_count() |
| 282 | except NotImplementedError: |
| 283 | cpus = 1 |
| 284 | self.assertTrue(type(cpus) is int) |
| 285 | self.assertTrue(cpus >= 1) |
| 286 | |
| 287 | def test_active_children(self): |
| 288 | self.assertEqual(type(self.active_children()), list) |
| 289 | |
| 290 | p = self.Process(target=time.sleep, args=(DELTA,)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 291 | self.assertNotIn(p, self.active_children()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 292 | |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 293 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 294 | p.start() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 295 | self.assertIn(p, self.active_children()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 296 | |
| 297 | p.join() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 298 | self.assertNotIn(p, self.active_children()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 299 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 300 | @classmethod |
| 301 | def _test_recursion(cls, wconn, id): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 302 | from multiprocessing import forking |
| 303 | wconn.send(id) |
| 304 | if len(id) < 2: |
| 305 | for i in range(2): |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 306 | p = cls.Process( |
| 307 | target=cls._test_recursion, args=(wconn, id+[i]) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 308 | ) |
| 309 | p.start() |
| 310 | p.join() |
| 311 | |
| 312 | def test_recursion(self): |
| 313 | rconn, wconn = self.Pipe(duplex=False) |
| 314 | self._test_recursion(wconn, []) |
| 315 | |
| 316 | time.sleep(DELTA) |
| 317 | result = [] |
| 318 | while rconn.poll(): |
| 319 | result.append(rconn.recv()) |
| 320 | |
| 321 | expected = [ |
| 322 | [], |
| 323 | [0], |
| 324 | [0, 0], |
| 325 | [0, 1], |
| 326 | [1], |
| 327 | [1, 0], |
| 328 | [1, 1] |
| 329 | ] |
| 330 | self.assertEqual(result, expected) |
| 331 | |
| 332 | # |
| 333 | # |
| 334 | # |
| 335 | |
| 336 | class _UpperCaser(multiprocessing.Process): |
| 337 | |
| 338 | def __init__(self): |
| 339 | multiprocessing.Process.__init__(self) |
| 340 | self.child_conn, self.parent_conn = multiprocessing.Pipe() |
| 341 | |
| 342 | def run(self): |
| 343 | self.parent_conn.close() |
| 344 | for s in iter(self.child_conn.recv, None): |
| 345 | self.child_conn.send(s.upper()) |
| 346 | self.child_conn.close() |
| 347 | |
| 348 | def submit(self, s): |
| 349 | assert type(s) is str |
| 350 | self.parent_conn.send(s) |
| 351 | return self.parent_conn.recv() |
| 352 | |
| 353 | def stop(self): |
| 354 | self.parent_conn.send(None) |
| 355 | self.parent_conn.close() |
| 356 | self.child_conn.close() |
| 357 | |
| 358 | class _TestSubclassingProcess(BaseTestCase): |
| 359 | |
| 360 | ALLOWED_TYPES = ('processes',) |
| 361 | |
| 362 | def test_subclassing(self): |
| 363 | uppercaser = _UpperCaser() |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 364 | uppercaser.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 365 | uppercaser.start() |
| 366 | self.assertEqual(uppercaser.submit('hello'), 'HELLO') |
| 367 | self.assertEqual(uppercaser.submit('world'), 'WORLD') |
| 368 | uppercaser.stop() |
| 369 | uppercaser.join() |
| 370 | |
Antoine Pitrou | 84a0fbf | 2012-01-27 10:52:37 +0100 | [diff] [blame] | 371 | def test_stderr_flush(self): |
| 372 | # sys.stderr is flushed at process shutdown (issue #13812) |
| 373 | if self.TYPE == "threads": |
| 374 | return |
| 375 | |
| 376 | testfn = test.support.TESTFN |
| 377 | self.addCleanup(test.support.unlink, testfn) |
| 378 | proc = self.Process(target=self._test_stderr_flush, args=(testfn,)) |
| 379 | proc.start() |
| 380 | proc.join() |
| 381 | with open(testfn, 'r') as f: |
| 382 | err = f.read() |
| 383 | # The whole traceback was printed |
| 384 | self.assertIn("ZeroDivisionError", err) |
| 385 | self.assertIn("test_multiprocessing.py", err) |
| 386 | self.assertIn("1/0 # MARKER", err) |
| 387 | |
| 388 | @classmethod |
| 389 | def _test_stderr_flush(cls, testfn): |
| 390 | sys.stderr = open(testfn, 'w') |
| 391 | 1/0 # MARKER |
| 392 | |
| 393 | |
Richard Oudkerk | 29471de | 2012-06-06 19:04:57 +0100 | [diff] [blame] | 394 | @classmethod |
| 395 | def _test_sys_exit(cls, reason, testfn): |
| 396 | sys.stderr = open(testfn, 'w') |
| 397 | sys.exit(reason) |
| 398 | |
| 399 | def test_sys_exit(self): |
| 400 | # See Issue 13854 |
| 401 | if self.TYPE == 'threads': |
| 402 | return |
| 403 | |
| 404 | testfn = test.support.TESTFN |
| 405 | self.addCleanup(test.support.unlink, testfn) |
| 406 | |
| 407 | for reason, code in (([1, 2, 3], 1), ('ignore this', 0)): |
| 408 | p = self.Process(target=self._test_sys_exit, args=(reason, testfn)) |
| 409 | p.daemon = True |
| 410 | p.start() |
| 411 | p.join(5) |
| 412 | self.assertEqual(p.exitcode, code) |
| 413 | |
| 414 | with open(testfn, 'r') as f: |
| 415 | self.assertEqual(f.read().rstrip(), str(reason)) |
| 416 | |
| 417 | for reason in (True, False, 8): |
| 418 | p = self.Process(target=sys.exit, args=(reason,)) |
| 419 | p.daemon = True |
| 420 | p.start() |
| 421 | p.join(5) |
| 422 | self.assertEqual(p.exitcode, reason) |
| 423 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 424 | # |
| 425 | # |
| 426 | # |
| 427 | |
| 428 | def queue_empty(q): |
| 429 | if hasattr(q, 'empty'): |
| 430 | return q.empty() |
| 431 | else: |
| 432 | return q.qsize() == 0 |
| 433 | |
| 434 | def queue_full(q, maxsize): |
| 435 | if hasattr(q, 'full'): |
| 436 | return q.full() |
| 437 | else: |
| 438 | return q.qsize() == maxsize |
| 439 | |
| 440 | |
| 441 | class _TestQueue(BaseTestCase): |
| 442 | |
| 443 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 444 | @classmethod |
| 445 | def _test_put(cls, queue, child_can_start, parent_can_continue): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 446 | child_can_start.wait() |
| 447 | for i in range(6): |
| 448 | queue.get() |
| 449 | parent_can_continue.set() |
| 450 | |
| 451 | def test_put(self): |
| 452 | MAXSIZE = 6 |
| 453 | queue = self.Queue(maxsize=MAXSIZE) |
| 454 | child_can_start = self.Event() |
| 455 | parent_can_continue = self.Event() |
| 456 | |
| 457 | proc = self.Process( |
| 458 | target=self._test_put, |
| 459 | args=(queue, child_can_start, parent_can_continue) |
| 460 | ) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 461 | proc.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 462 | proc.start() |
| 463 | |
| 464 | self.assertEqual(queue_empty(queue), True) |
| 465 | self.assertEqual(queue_full(queue, MAXSIZE), False) |
| 466 | |
| 467 | queue.put(1) |
| 468 | queue.put(2, True) |
| 469 | queue.put(3, True, None) |
| 470 | queue.put(4, False) |
| 471 | queue.put(5, False, None) |
| 472 | queue.put_nowait(6) |
| 473 | |
| 474 | # the values may be in buffer but not yet in pipe so sleep a bit |
| 475 | time.sleep(DELTA) |
| 476 | |
| 477 | self.assertEqual(queue_empty(queue), False) |
| 478 | self.assertEqual(queue_full(queue, MAXSIZE), True) |
| 479 | |
| 480 | put = TimingWrapper(queue.put) |
| 481 | put_nowait = TimingWrapper(queue.put_nowait) |
| 482 | |
| 483 | self.assertRaises(pyqueue.Full, put, 7, False) |
| 484 | self.assertTimingAlmostEqual(put.elapsed, 0) |
| 485 | |
| 486 | self.assertRaises(pyqueue.Full, put, 7, False, None) |
| 487 | self.assertTimingAlmostEqual(put.elapsed, 0) |
| 488 | |
| 489 | self.assertRaises(pyqueue.Full, put_nowait, 7) |
| 490 | self.assertTimingAlmostEqual(put_nowait.elapsed, 0) |
| 491 | |
| 492 | self.assertRaises(pyqueue.Full, put, 7, True, TIMEOUT1) |
| 493 | self.assertTimingAlmostEqual(put.elapsed, TIMEOUT1) |
| 494 | |
| 495 | self.assertRaises(pyqueue.Full, put, 7, False, TIMEOUT2) |
| 496 | self.assertTimingAlmostEqual(put.elapsed, 0) |
| 497 | |
| 498 | self.assertRaises(pyqueue.Full, put, 7, True, timeout=TIMEOUT3) |
| 499 | self.assertTimingAlmostEqual(put.elapsed, TIMEOUT3) |
| 500 | |
| 501 | child_can_start.set() |
| 502 | parent_can_continue.wait() |
| 503 | |
| 504 | self.assertEqual(queue_empty(queue), True) |
| 505 | self.assertEqual(queue_full(queue, MAXSIZE), False) |
| 506 | |
| 507 | proc.join() |
| 508 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 509 | @classmethod |
| 510 | def _test_get(cls, queue, child_can_start, parent_can_continue): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 511 | child_can_start.wait() |
Benjamin Peterson | b29cbbc | 2008-06-16 20:57:14 +0000 | [diff] [blame] | 512 | #queue.put(1) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 513 | queue.put(2) |
| 514 | queue.put(3) |
| 515 | queue.put(4) |
| 516 | queue.put(5) |
| 517 | parent_can_continue.set() |
| 518 | |
| 519 | def test_get(self): |
| 520 | queue = self.Queue() |
| 521 | child_can_start = self.Event() |
| 522 | parent_can_continue = self.Event() |
| 523 | |
| 524 | proc = self.Process( |
| 525 | target=self._test_get, |
| 526 | args=(queue, child_can_start, parent_can_continue) |
| 527 | ) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 528 | proc.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 529 | proc.start() |
| 530 | |
| 531 | self.assertEqual(queue_empty(queue), True) |
| 532 | |
| 533 | child_can_start.set() |
| 534 | parent_can_continue.wait() |
| 535 | |
| 536 | time.sleep(DELTA) |
| 537 | self.assertEqual(queue_empty(queue), False) |
| 538 | |
Benjamin Peterson | b29cbbc | 2008-06-16 20:57:14 +0000 | [diff] [blame] | 539 | # Hangs unexpectedly, remove for now |
| 540 | #self.assertEqual(queue.get(), 1) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 541 | self.assertEqual(queue.get(True, None), 2) |
| 542 | self.assertEqual(queue.get(True), 3) |
| 543 | self.assertEqual(queue.get(timeout=1), 4) |
| 544 | self.assertEqual(queue.get_nowait(), 5) |
| 545 | |
| 546 | self.assertEqual(queue_empty(queue), True) |
| 547 | |
| 548 | get = TimingWrapper(queue.get) |
| 549 | get_nowait = TimingWrapper(queue.get_nowait) |
| 550 | |
| 551 | self.assertRaises(pyqueue.Empty, get, False) |
| 552 | self.assertTimingAlmostEqual(get.elapsed, 0) |
| 553 | |
| 554 | self.assertRaises(pyqueue.Empty, get, False, None) |
| 555 | self.assertTimingAlmostEqual(get.elapsed, 0) |
| 556 | |
| 557 | self.assertRaises(pyqueue.Empty, get_nowait) |
| 558 | self.assertTimingAlmostEqual(get_nowait.elapsed, 0) |
| 559 | |
| 560 | self.assertRaises(pyqueue.Empty, get, True, TIMEOUT1) |
| 561 | self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) |
| 562 | |
| 563 | self.assertRaises(pyqueue.Empty, get, False, TIMEOUT2) |
| 564 | self.assertTimingAlmostEqual(get.elapsed, 0) |
| 565 | |
| 566 | self.assertRaises(pyqueue.Empty, get, timeout=TIMEOUT3) |
| 567 | self.assertTimingAlmostEqual(get.elapsed, TIMEOUT3) |
| 568 | |
| 569 | proc.join() |
| 570 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 571 | @classmethod |
| 572 | def _test_fork(cls, queue): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 573 | for i in range(10, 20): |
| 574 | queue.put(i) |
| 575 | # note that at this point the items may only be buffered, so the |
| 576 | # process cannot shutdown until the feeder thread has finished |
| 577 | # pushing items onto the pipe. |
| 578 | |
| 579 | def test_fork(self): |
| 580 | # Old versions of Queue would fail to create a new feeder |
| 581 | # thread for a forked process if the original process had its |
| 582 | # own feeder thread. This test checks that this no longer |
| 583 | # happens. |
| 584 | |
| 585 | queue = self.Queue() |
| 586 | |
| 587 | # put items on queue so that main process starts a feeder thread |
| 588 | for i in range(10): |
| 589 | queue.put(i) |
| 590 | |
| 591 | # wait to make sure thread starts before we fork a new process |
| 592 | time.sleep(DELTA) |
| 593 | |
| 594 | # fork process |
| 595 | p = self.Process(target=self._test_fork, args=(queue,)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 596 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 597 | p.start() |
| 598 | |
| 599 | # check that all expected items are in the queue |
| 600 | for i in range(20): |
| 601 | self.assertEqual(queue.get(), i) |
| 602 | self.assertRaises(pyqueue.Empty, queue.get, False) |
| 603 | |
| 604 | p.join() |
| 605 | |
| 606 | def test_qsize(self): |
| 607 | q = self.Queue() |
| 608 | try: |
| 609 | self.assertEqual(q.qsize(), 0) |
| 610 | except NotImplementedError: |
| 611 | return |
| 612 | q.put(1) |
| 613 | self.assertEqual(q.qsize(), 1) |
| 614 | q.put(5) |
| 615 | self.assertEqual(q.qsize(), 2) |
| 616 | q.get() |
| 617 | self.assertEqual(q.qsize(), 1) |
| 618 | q.get() |
| 619 | self.assertEqual(q.qsize(), 0) |
| 620 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 621 | @classmethod |
| 622 | def _test_task_done(cls, q): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 623 | for obj in iter(q.get, None): |
| 624 | time.sleep(DELTA) |
| 625 | q.task_done() |
| 626 | |
| 627 | def test_task_done(self): |
| 628 | queue = self.JoinableQueue() |
| 629 | |
| 630 | if sys.version_info < (2, 5) and not hasattr(queue, 'task_done'): |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 631 | self.skipTest("requires 'queue.task_done()' method") |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 632 | |
| 633 | workers = [self.Process(target=self._test_task_done, args=(queue,)) |
| 634 | for i in range(4)] |
| 635 | |
| 636 | for p in workers: |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 637 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 638 | p.start() |
| 639 | |
| 640 | for i in range(10): |
| 641 | queue.put(i) |
| 642 | |
| 643 | queue.join() |
| 644 | |
| 645 | for p in workers: |
| 646 | queue.put(None) |
| 647 | |
| 648 | for p in workers: |
| 649 | p.join() |
| 650 | |
| 651 | # |
| 652 | # |
| 653 | # |
| 654 | |
| 655 | class _TestLock(BaseTestCase): |
| 656 | |
| 657 | def test_lock(self): |
| 658 | lock = self.Lock() |
| 659 | self.assertEqual(lock.acquire(), True) |
| 660 | self.assertEqual(lock.acquire(False), False) |
| 661 | self.assertEqual(lock.release(), None) |
| 662 | self.assertRaises((ValueError, threading.ThreadError), lock.release) |
| 663 | |
| 664 | def test_rlock(self): |
| 665 | lock = self.RLock() |
| 666 | self.assertEqual(lock.acquire(), True) |
| 667 | self.assertEqual(lock.acquire(), True) |
| 668 | self.assertEqual(lock.acquire(), True) |
| 669 | self.assertEqual(lock.release(), None) |
| 670 | self.assertEqual(lock.release(), None) |
| 671 | self.assertEqual(lock.release(), None) |
| 672 | self.assertRaises((AssertionError, RuntimeError), lock.release) |
| 673 | |
Jesse Noller | f8d0085 | 2009-03-31 03:25:07 +0000 | [diff] [blame] | 674 | def test_lock_context(self): |
| 675 | with self.Lock(): |
| 676 | pass |
| 677 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 678 | |
| 679 | class _TestSemaphore(BaseTestCase): |
| 680 | |
| 681 | def _test_semaphore(self, sem): |
| 682 | self.assertReturnsIfImplemented(2, get_value, sem) |
| 683 | self.assertEqual(sem.acquire(), True) |
| 684 | self.assertReturnsIfImplemented(1, get_value, sem) |
| 685 | self.assertEqual(sem.acquire(), True) |
| 686 | self.assertReturnsIfImplemented(0, get_value, sem) |
| 687 | self.assertEqual(sem.acquire(False), False) |
| 688 | self.assertReturnsIfImplemented(0, get_value, sem) |
| 689 | self.assertEqual(sem.release(), None) |
| 690 | self.assertReturnsIfImplemented(1, get_value, sem) |
| 691 | self.assertEqual(sem.release(), None) |
| 692 | self.assertReturnsIfImplemented(2, get_value, sem) |
| 693 | |
| 694 | def test_semaphore(self): |
| 695 | sem = self.Semaphore(2) |
| 696 | self._test_semaphore(sem) |
| 697 | self.assertEqual(sem.release(), None) |
| 698 | self.assertReturnsIfImplemented(3, get_value, sem) |
| 699 | self.assertEqual(sem.release(), None) |
| 700 | self.assertReturnsIfImplemented(4, get_value, sem) |
| 701 | |
| 702 | def test_bounded_semaphore(self): |
| 703 | sem = self.BoundedSemaphore(2) |
| 704 | self._test_semaphore(sem) |
| 705 | # Currently fails on OS/X |
| 706 | #if HAVE_GETVALUE: |
| 707 | # self.assertRaises(ValueError, sem.release) |
| 708 | # self.assertReturnsIfImplemented(2, get_value, sem) |
| 709 | |
| 710 | def test_timeout(self): |
| 711 | if self.TYPE != 'processes': |
| 712 | return |
| 713 | |
| 714 | sem = self.Semaphore(0) |
| 715 | acquire = TimingWrapper(sem.acquire) |
| 716 | |
| 717 | self.assertEqual(acquire(False), False) |
| 718 | self.assertTimingAlmostEqual(acquire.elapsed, 0.0) |
| 719 | |
| 720 | self.assertEqual(acquire(False, None), False) |
| 721 | self.assertTimingAlmostEqual(acquire.elapsed, 0.0) |
| 722 | |
| 723 | self.assertEqual(acquire(False, TIMEOUT1), False) |
| 724 | self.assertTimingAlmostEqual(acquire.elapsed, 0) |
| 725 | |
| 726 | self.assertEqual(acquire(True, TIMEOUT2), False) |
| 727 | self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT2) |
| 728 | |
| 729 | self.assertEqual(acquire(timeout=TIMEOUT3), False) |
| 730 | self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT3) |
| 731 | |
| 732 | |
| 733 | class _TestCondition(BaseTestCase): |
| 734 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 735 | @classmethod |
| 736 | def f(cls, cond, sleeping, woken, timeout=None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 737 | cond.acquire() |
| 738 | sleeping.release() |
| 739 | cond.wait(timeout) |
| 740 | woken.release() |
| 741 | cond.release() |
| 742 | |
| 743 | def check_invariant(self, cond): |
| 744 | # this is only supposed to succeed when there are no sleepers |
| 745 | if self.TYPE == 'processes': |
| 746 | try: |
| 747 | sleepers = (cond._sleeping_count.get_value() - |
| 748 | cond._woken_count.get_value()) |
| 749 | self.assertEqual(sleepers, 0) |
| 750 | self.assertEqual(cond._wait_semaphore.get_value(), 0) |
| 751 | except NotImplementedError: |
| 752 | pass |
| 753 | |
| 754 | def test_notify(self): |
| 755 | cond = self.Condition() |
| 756 | sleeping = self.Semaphore(0) |
| 757 | woken = self.Semaphore(0) |
| 758 | |
| 759 | p = self.Process(target=self.f, args=(cond, sleeping, woken)) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 760 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 761 | p.start() |
| 762 | |
| 763 | p = threading.Thread(target=self.f, args=(cond, sleeping, woken)) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 764 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 765 | p.start() |
| 766 | |
| 767 | # wait for both children to start sleeping |
| 768 | sleeping.acquire() |
| 769 | sleeping.acquire() |
| 770 | |
| 771 | # check no process/thread has woken up |
| 772 | time.sleep(DELTA) |
| 773 | self.assertReturnsIfImplemented(0, get_value, woken) |
| 774 | |
| 775 | # wake up one process/thread |
| 776 | cond.acquire() |
| 777 | cond.notify() |
| 778 | cond.release() |
| 779 | |
| 780 | # check one process/thread has woken up |
| 781 | time.sleep(DELTA) |
| 782 | self.assertReturnsIfImplemented(1, get_value, woken) |
| 783 | |
| 784 | # wake up another |
| 785 | cond.acquire() |
| 786 | cond.notify() |
| 787 | cond.release() |
| 788 | |
| 789 | # check other has woken up |
| 790 | time.sleep(DELTA) |
| 791 | self.assertReturnsIfImplemented(2, get_value, woken) |
| 792 | |
| 793 | # check state is not mucked up |
| 794 | self.check_invariant(cond) |
| 795 | p.join() |
| 796 | |
| 797 | def test_notify_all(self): |
| 798 | cond = self.Condition() |
| 799 | sleeping = self.Semaphore(0) |
| 800 | woken = self.Semaphore(0) |
| 801 | |
| 802 | # start some threads/processes which will timeout |
| 803 | for i in range(3): |
| 804 | p = self.Process(target=self.f, |
| 805 | args=(cond, sleeping, woken, TIMEOUT1)) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 806 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 807 | p.start() |
| 808 | |
| 809 | t = threading.Thread(target=self.f, |
| 810 | args=(cond, sleeping, woken, TIMEOUT1)) |
Benjamin Peterson | 7275370 | 2008-08-18 18:09:21 +0000 | [diff] [blame] | 811 | t.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 812 | t.start() |
| 813 | |
| 814 | # wait for them all to sleep |
| 815 | for i in range(6): |
| 816 | sleeping.acquire() |
| 817 | |
| 818 | # check they have all timed out |
| 819 | for i in range(6): |
| 820 | woken.acquire() |
| 821 | self.assertReturnsIfImplemented(0, get_value, woken) |
| 822 | |
| 823 | # check state is not mucked up |
| 824 | self.check_invariant(cond) |
| 825 | |
| 826 | # start some more threads/processes |
| 827 | for i in range(3): |
| 828 | p = self.Process(target=self.f, args=(cond, sleeping, woken)) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 829 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 830 | p.start() |
| 831 | |
| 832 | t = threading.Thread(target=self.f, args=(cond, sleeping, woken)) |
Benjamin Peterson | 7275370 | 2008-08-18 18:09:21 +0000 | [diff] [blame] | 833 | t.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 834 | t.start() |
| 835 | |
| 836 | # wait for them to all sleep |
| 837 | for i in range(6): |
| 838 | sleeping.acquire() |
| 839 | |
| 840 | # check no process/thread has woken up |
| 841 | time.sleep(DELTA) |
| 842 | self.assertReturnsIfImplemented(0, get_value, woken) |
| 843 | |
| 844 | # wake them all up |
| 845 | cond.acquire() |
| 846 | cond.notify_all() |
| 847 | cond.release() |
| 848 | |
| 849 | # check they have all woken |
Antoine Pitrou | f25a8de | 2011-04-16 21:02:01 +0200 | [diff] [blame] | 850 | for i in range(10): |
| 851 | try: |
| 852 | if get_value(woken) == 6: |
| 853 | break |
| 854 | except NotImplementedError: |
| 855 | break |
| 856 | time.sleep(DELTA) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 857 | self.assertReturnsIfImplemented(6, get_value, woken) |
| 858 | |
| 859 | # check state is not mucked up |
| 860 | self.check_invariant(cond) |
| 861 | |
| 862 | def test_timeout(self): |
| 863 | cond = self.Condition() |
| 864 | wait = TimingWrapper(cond.wait) |
| 865 | cond.acquire() |
| 866 | res = wait(TIMEOUT1) |
| 867 | cond.release() |
Georg Brandl | 65ffae0 | 2010-10-28 09:24:56 +0000 | [diff] [blame] | 868 | self.assertEqual(res, False) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 869 | self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1) |
| 870 | |
| 871 | |
| 872 | class _TestEvent(BaseTestCase): |
| 873 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 874 | @classmethod |
| 875 | def _test_event(cls, event): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 876 | time.sleep(TIMEOUT2) |
| 877 | event.set() |
| 878 | |
| 879 | def test_event(self): |
| 880 | event = self.Event() |
| 881 | wait = TimingWrapper(event.wait) |
| 882 | |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 883 | # Removed temporarily, due to API shear, this does not |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 884 | # work with threading._Event objects. is_set == isSet |
Benjamin Peterson | 965ce87 | 2009-04-05 21:24:58 +0000 | [diff] [blame] | 885 | self.assertEqual(event.is_set(), False) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 886 | |
Benjamin Peterson | 965ce87 | 2009-04-05 21:24:58 +0000 | [diff] [blame] | 887 | # Removed, threading.Event.wait() will return the value of the __flag |
| 888 | # instead of None. API Shear with the semaphore backed mp.Event |
| 889 | self.assertEqual(wait(0.0), False) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 890 | self.assertTimingAlmostEqual(wait.elapsed, 0.0) |
Benjamin Peterson | 965ce87 | 2009-04-05 21:24:58 +0000 | [diff] [blame] | 891 | self.assertEqual(wait(TIMEOUT1), False) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 892 | self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1) |
| 893 | |
| 894 | event.set() |
| 895 | |
| 896 | # See note above on the API differences |
Benjamin Peterson | 965ce87 | 2009-04-05 21:24:58 +0000 | [diff] [blame] | 897 | self.assertEqual(event.is_set(), True) |
| 898 | self.assertEqual(wait(), True) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 899 | self.assertTimingAlmostEqual(wait.elapsed, 0.0) |
Benjamin Peterson | 965ce87 | 2009-04-05 21:24:58 +0000 | [diff] [blame] | 900 | self.assertEqual(wait(TIMEOUT1), True) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 901 | self.assertTimingAlmostEqual(wait.elapsed, 0.0) |
| 902 | # self.assertEqual(event.is_set(), True) |
| 903 | |
| 904 | event.clear() |
| 905 | |
| 906 | #self.assertEqual(event.is_set(), False) |
| 907 | |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 908 | p = self.Process(target=self._test_event, args=(event,)) |
| 909 | p.daemon = True |
| 910 | p.start() |
Benjamin Peterson | 965ce87 | 2009-04-05 21:24:58 +0000 | [diff] [blame] | 911 | self.assertEqual(wait(), True) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 912 | |
| 913 | # |
| 914 | # |
| 915 | # |
| 916 | |
| 917 | class _TestValue(BaseTestCase): |
| 918 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 919 | ALLOWED_TYPES = ('processes',) |
| 920 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 921 | codes_values = [ |
| 922 | ('i', 4343, 24234), |
| 923 | ('d', 3.625, -4.25), |
| 924 | ('h', -232, 234), |
| 925 | ('c', latin('x'), latin('y')) |
| 926 | ] |
| 927 | |
Antoine Pitrou | 7744e2a | 2010-11-22 16:26:21 +0000 | [diff] [blame] | 928 | def setUp(self): |
| 929 | if not HAS_SHAREDCTYPES: |
| 930 | self.skipTest("requires multiprocessing.sharedctypes") |
| 931 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 932 | @classmethod |
| 933 | def _test(cls, values): |
| 934 | for sv, cv in zip(values, cls.codes_values): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 935 | sv.value = cv[2] |
| 936 | |
| 937 | |
| 938 | def test_value(self, raw=False): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 939 | if raw: |
| 940 | values = [self.RawValue(code, value) |
| 941 | for code, value, _ in self.codes_values] |
| 942 | else: |
| 943 | values = [self.Value(code, value) |
| 944 | for code, value, _ in self.codes_values] |
| 945 | |
| 946 | for sv, cv in zip(values, self.codes_values): |
| 947 | self.assertEqual(sv.value, cv[1]) |
| 948 | |
| 949 | proc = self.Process(target=self._test, args=(values,)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 950 | proc.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 951 | proc.start() |
| 952 | proc.join() |
| 953 | |
| 954 | for sv, cv in zip(values, self.codes_values): |
| 955 | self.assertEqual(sv.value, cv[2]) |
| 956 | |
| 957 | def test_rawvalue(self): |
| 958 | self.test_value(raw=True) |
| 959 | |
| 960 | def test_getobj_getlock(self): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 961 | val1 = self.Value('i', 5) |
| 962 | lock1 = val1.get_lock() |
| 963 | obj1 = val1.get_obj() |
| 964 | |
| 965 | val2 = self.Value('i', 5, lock=None) |
| 966 | lock2 = val2.get_lock() |
| 967 | obj2 = val2.get_obj() |
| 968 | |
| 969 | lock = self.Lock() |
| 970 | val3 = self.Value('i', 5, lock=lock) |
| 971 | lock3 = val3.get_lock() |
| 972 | obj3 = val3.get_obj() |
| 973 | self.assertEqual(lock, lock3) |
| 974 | |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 975 | arr4 = self.Value('i', 5, lock=False) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 976 | self.assertFalse(hasattr(arr4, 'get_lock')) |
| 977 | self.assertFalse(hasattr(arr4, 'get_obj')) |
| 978 | |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 979 | self.assertRaises(AttributeError, self.Value, 'i', 5, lock='navalue') |
| 980 | |
| 981 | arr5 = self.RawValue('i', 5) |
| 982 | self.assertFalse(hasattr(arr5, 'get_lock')) |
| 983 | self.assertFalse(hasattr(arr5, 'get_obj')) |
| 984 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 985 | |
| 986 | class _TestArray(BaseTestCase): |
| 987 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 988 | ALLOWED_TYPES = ('processes',) |
| 989 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 990 | @classmethod |
| 991 | def f(cls, seq): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 992 | for i in range(1, len(seq)): |
| 993 | seq[i] += seq[i-1] |
| 994 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 995 | @unittest.skipIf(c_int is None, "requires _ctypes") |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 996 | def test_array(self, raw=False): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 997 | seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831] |
| 998 | if raw: |
| 999 | arr = self.RawArray('i', seq) |
| 1000 | else: |
| 1001 | arr = self.Array('i', seq) |
| 1002 | |
| 1003 | self.assertEqual(len(arr), len(seq)) |
| 1004 | self.assertEqual(arr[3], seq[3]) |
| 1005 | self.assertEqual(list(arr[2:7]), list(seq[2:7])) |
| 1006 | |
| 1007 | arr[4:8] = seq[4:8] = array.array('i', [1, 2, 3, 4]) |
| 1008 | |
| 1009 | self.assertEqual(list(arr[:]), seq) |
| 1010 | |
| 1011 | self.f(seq) |
| 1012 | |
| 1013 | p = self.Process(target=self.f, args=(arr,)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1014 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1015 | p.start() |
| 1016 | p.join() |
| 1017 | |
| 1018 | self.assertEqual(list(arr[:]), seq) |
| 1019 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 1020 | @unittest.skipIf(c_int is None, "requires _ctypes") |
Mark Dickinson | 89461ef | 2011-03-26 10:19:03 +0000 | [diff] [blame] | 1021 | def test_array_from_size(self): |
| 1022 | size = 10 |
| 1023 | # Test for zeroing (see issue #11675). |
| 1024 | # The repetition below strengthens the test by increasing the chances |
| 1025 | # of previously allocated non-zero memory being used for the new array |
| 1026 | # on the 2nd and 3rd loops. |
| 1027 | for _ in range(3): |
| 1028 | arr = self.Array('i', size) |
| 1029 | self.assertEqual(len(arr), size) |
| 1030 | self.assertEqual(list(arr), [0] * size) |
| 1031 | arr[:] = range(10) |
| 1032 | self.assertEqual(list(arr), list(range(10))) |
| 1033 | del arr |
| 1034 | |
| 1035 | @unittest.skipIf(c_int is None, "requires _ctypes") |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1036 | def test_rawarray(self): |
| 1037 | self.test_array(raw=True) |
| 1038 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 1039 | @unittest.skipIf(c_int is None, "requires _ctypes") |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1040 | def test_getobj_getlock_obj(self): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1041 | arr1 = self.Array('i', list(range(10))) |
| 1042 | lock1 = arr1.get_lock() |
| 1043 | obj1 = arr1.get_obj() |
| 1044 | |
| 1045 | arr2 = self.Array('i', list(range(10)), lock=None) |
| 1046 | lock2 = arr2.get_lock() |
| 1047 | obj2 = arr2.get_obj() |
| 1048 | |
| 1049 | lock = self.Lock() |
| 1050 | arr3 = self.Array('i', list(range(10)), lock=lock) |
| 1051 | lock3 = arr3.get_lock() |
| 1052 | obj3 = arr3.get_obj() |
| 1053 | self.assertEqual(lock, lock3) |
| 1054 | |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 1055 | arr4 = self.Array('i', range(10), lock=False) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1056 | self.assertFalse(hasattr(arr4, 'get_lock')) |
| 1057 | self.assertFalse(hasattr(arr4, 'get_obj')) |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 1058 | self.assertRaises(AttributeError, |
| 1059 | self.Array, 'i', range(10), lock='notalock') |
| 1060 | |
| 1061 | arr5 = self.RawArray('i', range(10)) |
| 1062 | self.assertFalse(hasattr(arr5, 'get_lock')) |
| 1063 | self.assertFalse(hasattr(arr5, 'get_obj')) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1064 | |
| 1065 | # |
| 1066 | # |
| 1067 | # |
| 1068 | |
| 1069 | class _TestContainers(BaseTestCase): |
| 1070 | |
| 1071 | ALLOWED_TYPES = ('manager',) |
| 1072 | |
| 1073 | def test_list(self): |
| 1074 | a = self.list(list(range(10))) |
| 1075 | self.assertEqual(a[:], list(range(10))) |
| 1076 | |
| 1077 | b = self.list() |
| 1078 | self.assertEqual(b[:], []) |
| 1079 | |
| 1080 | b.extend(list(range(5))) |
| 1081 | self.assertEqual(b[:], list(range(5))) |
| 1082 | |
| 1083 | self.assertEqual(b[2], 2) |
| 1084 | self.assertEqual(b[2:10], [2,3,4]) |
| 1085 | |
| 1086 | b *= 2 |
| 1087 | self.assertEqual(b[:], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]) |
| 1088 | |
| 1089 | self.assertEqual(b + [5, 6], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6]) |
| 1090 | |
| 1091 | self.assertEqual(a[:], list(range(10))) |
| 1092 | |
| 1093 | d = [a, b] |
| 1094 | e = self.list(d) |
| 1095 | self.assertEqual( |
| 1096 | e[:], |
| 1097 | [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]] |
| 1098 | ) |
| 1099 | |
| 1100 | f = self.list([a]) |
| 1101 | a.append('hello') |
| 1102 | self.assertEqual(f[:], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello']]) |
| 1103 | |
| 1104 | def test_dict(self): |
| 1105 | d = self.dict() |
| 1106 | indices = list(range(65, 70)) |
| 1107 | for i in indices: |
| 1108 | d[i] = chr(i) |
| 1109 | self.assertEqual(d.copy(), dict((i, chr(i)) for i in indices)) |
| 1110 | self.assertEqual(sorted(d.keys()), indices) |
| 1111 | self.assertEqual(sorted(d.values()), [chr(i) for i in indices]) |
| 1112 | self.assertEqual(sorted(d.items()), [(i, chr(i)) for i in indices]) |
| 1113 | |
| 1114 | def test_namespace(self): |
| 1115 | n = self.Namespace() |
| 1116 | n.name = 'Bob' |
| 1117 | n.job = 'Builder' |
| 1118 | n._hidden = 'hidden' |
| 1119 | self.assertEqual((n.name, n.job), ('Bob', 'Builder')) |
| 1120 | del n.job |
| 1121 | self.assertEqual(str(n), "Namespace(name='Bob')") |
| 1122 | self.assertTrue(hasattr(n, 'name')) |
| 1123 | self.assertTrue(not hasattr(n, 'job')) |
| 1124 | |
| 1125 | # |
| 1126 | # |
| 1127 | # |
| 1128 | |
| 1129 | def sqr(x, wait=0.0): |
| 1130 | time.sleep(wait) |
| 1131 | return x*x |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 1132 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1133 | class _TestPool(BaseTestCase): |
| 1134 | |
| 1135 | def test_apply(self): |
| 1136 | papply = self.pool.apply |
| 1137 | self.assertEqual(papply(sqr, (5,)), sqr(5)) |
| 1138 | self.assertEqual(papply(sqr, (), {'x':3}), sqr(x=3)) |
| 1139 | |
| 1140 | def test_map(self): |
| 1141 | pmap = self.pool.map |
| 1142 | self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10))))) |
| 1143 | self.assertEqual(pmap(sqr, list(range(100)), chunksize=20), |
| 1144 | list(map(sqr, list(range(100))))) |
| 1145 | |
Alexandre Vassalotti | e52e378 | 2009-07-17 09:18:18 +0000 | [diff] [blame] | 1146 | def test_map_chunksize(self): |
| 1147 | try: |
| 1148 | self.pool.map_async(sqr, [], chunksize=1).get(timeout=TIMEOUT1) |
| 1149 | except multiprocessing.TimeoutError: |
| 1150 | self.fail("pool.map_async with chunksize stalled on null list") |
| 1151 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1152 | def test_async(self): |
| 1153 | res = self.pool.apply_async(sqr, (7, TIMEOUT1,)) |
| 1154 | get = TimingWrapper(res.get) |
| 1155 | self.assertEqual(get(), 49) |
| 1156 | self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) |
| 1157 | |
| 1158 | def test_async_timeout(self): |
| 1159 | res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 0.2)) |
| 1160 | get = TimingWrapper(res.get) |
| 1161 | self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2) |
| 1162 | self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2) |
| 1163 | |
| 1164 | def test_imap(self): |
| 1165 | it = self.pool.imap(sqr, list(range(10))) |
| 1166 | self.assertEqual(list(it), list(map(sqr, list(range(10))))) |
| 1167 | |
| 1168 | it = self.pool.imap(sqr, list(range(10))) |
| 1169 | for i in range(10): |
| 1170 | self.assertEqual(next(it), i*i) |
| 1171 | self.assertRaises(StopIteration, it.__next__) |
| 1172 | |
| 1173 | it = self.pool.imap(sqr, list(range(1000)), chunksize=100) |
| 1174 | for i in range(1000): |
| 1175 | self.assertEqual(next(it), i*i) |
| 1176 | self.assertRaises(StopIteration, it.__next__) |
| 1177 | |
| 1178 | def test_imap_unordered(self): |
| 1179 | it = self.pool.imap_unordered(sqr, list(range(1000))) |
| 1180 | self.assertEqual(sorted(it), list(map(sqr, list(range(1000))))) |
| 1181 | |
| 1182 | it = self.pool.imap_unordered(sqr, list(range(1000)), chunksize=53) |
| 1183 | self.assertEqual(sorted(it), list(map(sqr, list(range(1000))))) |
| 1184 | |
| 1185 | def test_make_pool(self): |
Victor Stinner | 2fae27b | 2011-06-20 17:53:35 +0200 | [diff] [blame] | 1186 | self.assertRaises(ValueError, multiprocessing.Pool, -1) |
| 1187 | self.assertRaises(ValueError, multiprocessing.Pool, 0) |
| 1188 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1189 | p = multiprocessing.Pool(3) |
| 1190 | self.assertEqual(3, len(p._pool)) |
| 1191 | p.close() |
| 1192 | p.join() |
| 1193 | |
| 1194 | def test_terminate(self): |
| 1195 | if self.TYPE == 'manager': |
| 1196 | # On Unix a forked process increfs each shared object to |
| 1197 | # which its parent process held a reference. If the |
| 1198 | # forked process gets terminated then there is likely to |
| 1199 | # be a reference leak. So to prevent |
| 1200 | # _TestZZZNumberOfObjects from failing we skip this test |
| 1201 | # when using a manager. |
| 1202 | return |
| 1203 | |
| 1204 | result = self.pool.map_async( |
| 1205 | time.sleep, [0.1 for i in range(10000)], chunksize=1 |
| 1206 | ) |
| 1207 | self.pool.terminate() |
| 1208 | join = TimingWrapper(self.pool.join) |
| 1209 | join() |
Victor Stinner | 900189b | 2011-03-24 16:39:07 +0100 | [diff] [blame] | 1210 | self.assertLess(join.elapsed, 0.5) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 1211 | |
Richard Oudkerk | e41682b | 2012-06-06 19:04:57 +0100 | [diff] [blame] | 1212 | def test_empty_iterable(self): |
| 1213 | # See Issue 12157 |
| 1214 | p = self.Pool(1) |
| 1215 | |
| 1216 | self.assertEqual(p.map(sqr, []), []) |
| 1217 | self.assertEqual(list(p.imap(sqr, [])), []) |
| 1218 | self.assertEqual(list(p.imap_unordered(sqr, [])), []) |
| 1219 | self.assertEqual(p.map_async(sqr, []).get(), []) |
| 1220 | |
| 1221 | p.close() |
| 1222 | p.join() |
| 1223 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 1224 | def raising(): |
| 1225 | raise KeyError("key") |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 1226 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 1227 | def unpickleable_result(): |
| 1228 | return lambda: 42 |
| 1229 | |
| 1230 | class _TestPoolWorkerErrors(BaseTestCase): |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 1231 | ALLOWED_TYPES = ('processes', ) |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 1232 | |
| 1233 | def test_async_error_callback(self): |
| 1234 | p = multiprocessing.Pool(2) |
| 1235 | |
| 1236 | scratchpad = [None] |
| 1237 | def errback(exc): |
| 1238 | scratchpad[0] = exc |
| 1239 | |
| 1240 | res = p.apply_async(raising, error_callback=errback) |
| 1241 | self.assertRaises(KeyError, res.get) |
| 1242 | self.assertTrue(scratchpad[0]) |
| 1243 | self.assertIsInstance(scratchpad[0], KeyError) |
| 1244 | |
| 1245 | p.close() |
| 1246 | p.join() |
| 1247 | |
| 1248 | def test_unpickleable_result(self): |
| 1249 | from multiprocessing.pool import MaybeEncodingError |
| 1250 | p = multiprocessing.Pool(2) |
| 1251 | |
| 1252 | # Make sure we don't lose pool processes because of encoding errors. |
| 1253 | for iteration in range(20): |
| 1254 | |
| 1255 | scratchpad = [None] |
| 1256 | def errback(exc): |
| 1257 | scratchpad[0] = exc |
| 1258 | |
| 1259 | res = p.apply_async(unpickleable_result, error_callback=errback) |
| 1260 | self.assertRaises(MaybeEncodingError, res.get) |
| 1261 | wrapped = scratchpad[0] |
| 1262 | self.assertTrue(wrapped) |
| 1263 | self.assertIsInstance(scratchpad[0], MaybeEncodingError) |
| 1264 | self.assertIsNotNone(wrapped.exc) |
| 1265 | self.assertIsNotNone(wrapped.value) |
| 1266 | |
| 1267 | p.close() |
| 1268 | p.join() |
| 1269 | |
| 1270 | class _TestPoolWorkerLifetime(BaseTestCase): |
| 1271 | ALLOWED_TYPES = ('processes', ) |
| 1272 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 1273 | def test_pool_worker_lifetime(self): |
| 1274 | p = multiprocessing.Pool(3, maxtasksperchild=10) |
| 1275 | self.assertEqual(3, len(p._pool)) |
| 1276 | origworkerpids = [w.pid for w in p._pool] |
| 1277 | # Run many tasks so each worker gets replaced (hopefully) |
| 1278 | results = [] |
| 1279 | for i in range(100): |
| 1280 | results.append(p.apply_async(sqr, (i, ))) |
| 1281 | # Fetch the results and verify we got the right answers, |
| 1282 | # also ensuring all the tasks have completed. |
| 1283 | for (j, res) in enumerate(results): |
| 1284 | self.assertEqual(res.get(), sqr(j)) |
| 1285 | # Refill the pool |
| 1286 | p._repopulate_pool() |
Florent Xicluna | fb190f6 | 2010-03-04 16:10:10 +0000 | [diff] [blame] | 1287 | # Wait until all workers are alive |
Antoine Pitrou | 540ab06 | 2011-04-06 22:51:17 +0200 | [diff] [blame] | 1288 | # (countdown * DELTA = 5 seconds max startup process time) |
| 1289 | countdown = 50 |
Florent Xicluna | fb190f6 | 2010-03-04 16:10:10 +0000 | [diff] [blame] | 1290 | while countdown and not all(w.is_alive() for w in p._pool): |
| 1291 | countdown -= 1 |
| 1292 | time.sleep(DELTA) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 1293 | finalworkerpids = [w.pid for w in p._pool] |
Florent Xicluna | fb190f6 | 2010-03-04 16:10:10 +0000 | [diff] [blame] | 1294 | # All pids should be assigned. See issue #7805. |
| 1295 | self.assertNotIn(None, origworkerpids) |
| 1296 | self.assertNotIn(None, finalworkerpids) |
| 1297 | # Finally, check that the worker pids have changed |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 1298 | self.assertNotEqual(sorted(origworkerpids), sorted(finalworkerpids)) |
| 1299 | p.close() |
| 1300 | p.join() |
| 1301 | |
Charles-François Natali | f8859e1 | 2011-10-24 18:45:29 +0200 | [diff] [blame] | 1302 | def test_pool_worker_lifetime_early_close(self): |
| 1303 | # Issue #10332: closing a pool whose workers have limited lifetimes |
| 1304 | # before all the tasks completed would make join() hang. |
| 1305 | p = multiprocessing.Pool(3, maxtasksperchild=1) |
| 1306 | results = [] |
| 1307 | for i in range(6): |
| 1308 | results.append(p.apply_async(sqr, (i, 0.3))) |
| 1309 | p.close() |
| 1310 | p.join() |
| 1311 | # check the results |
| 1312 | for (j, res) in enumerate(results): |
| 1313 | self.assertEqual(res.get(), sqr(j)) |
| 1314 | |
| 1315 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1316 | # |
| 1317 | # Test that manager has expected number of shared objects left |
| 1318 | # |
| 1319 | |
| 1320 | class _TestZZZNumberOfObjects(BaseTestCase): |
| 1321 | # Because test cases are sorted alphabetically, this one will get |
| 1322 | # run after all the other tests for the manager. It tests that |
| 1323 | # there have been no "reference leaks" for the manager's shared |
| 1324 | # objects. Note the comment in _TestPool.test_terminate(). |
| 1325 | ALLOWED_TYPES = ('manager',) |
| 1326 | |
| 1327 | def test_number_of_objects(self): |
| 1328 | EXPECTED_NUMBER = 1 # the pool object is still alive |
| 1329 | multiprocessing.active_children() # discard dead process objs |
| 1330 | gc.collect() # do garbage collection |
| 1331 | refs = self.manager._number_of_objects() |
Jesse Noller | 63b3a97 | 2009-01-21 02:15:48 +0000 | [diff] [blame] | 1332 | debug_info = self.manager._debug_info() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1333 | if refs != EXPECTED_NUMBER: |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 1334 | print(self.manager._debug_info()) |
Jesse Noller | 63b3a97 | 2009-01-21 02:15:48 +0000 | [diff] [blame] | 1335 | print(debug_info) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1336 | |
| 1337 | self.assertEqual(refs, EXPECTED_NUMBER) |
| 1338 | |
| 1339 | # |
| 1340 | # Test of creating a customized manager class |
| 1341 | # |
| 1342 | |
| 1343 | from multiprocessing.managers import BaseManager, BaseProxy, RemoteError |
| 1344 | |
| 1345 | class FooBar(object): |
| 1346 | def f(self): |
| 1347 | return 'f()' |
| 1348 | def g(self): |
| 1349 | raise ValueError |
| 1350 | def _h(self): |
| 1351 | return '_h()' |
| 1352 | |
| 1353 | def baz(): |
| 1354 | for i in range(10): |
| 1355 | yield i*i |
| 1356 | |
| 1357 | class IteratorProxy(BaseProxy): |
Florent Xicluna | aa17106 | 2010-08-14 15:56:42 +0000 | [diff] [blame] | 1358 | _exposed_ = ('__next__',) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1359 | def __iter__(self): |
| 1360 | return self |
| 1361 | def __next__(self): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1362 | return self._callmethod('__next__') |
| 1363 | |
| 1364 | class MyManager(BaseManager): |
| 1365 | pass |
| 1366 | |
| 1367 | MyManager.register('Foo', callable=FooBar) |
| 1368 | MyManager.register('Bar', callable=FooBar, exposed=('f', '_h')) |
| 1369 | MyManager.register('baz', callable=baz, proxytype=IteratorProxy) |
| 1370 | |
| 1371 | |
| 1372 | class _TestMyManager(BaseTestCase): |
| 1373 | |
| 1374 | ALLOWED_TYPES = ('manager',) |
| 1375 | |
| 1376 | def test_mymanager(self): |
| 1377 | manager = MyManager() |
| 1378 | manager.start() |
| 1379 | |
| 1380 | foo = manager.Foo() |
| 1381 | bar = manager.Bar() |
| 1382 | baz = manager.baz() |
| 1383 | |
| 1384 | foo_methods = [name for name in ('f', 'g', '_h') if hasattr(foo, name)] |
| 1385 | bar_methods = [name for name in ('f', 'g', '_h') if hasattr(bar, name)] |
| 1386 | |
| 1387 | self.assertEqual(foo_methods, ['f', 'g']) |
| 1388 | self.assertEqual(bar_methods, ['f', '_h']) |
| 1389 | |
| 1390 | self.assertEqual(foo.f(), 'f()') |
| 1391 | self.assertRaises(ValueError, foo.g) |
| 1392 | self.assertEqual(foo._callmethod('f'), 'f()') |
| 1393 | self.assertRaises(RemoteError, foo._callmethod, '_h') |
| 1394 | |
| 1395 | self.assertEqual(bar.f(), 'f()') |
| 1396 | self.assertEqual(bar._h(), '_h()') |
| 1397 | self.assertEqual(bar._callmethod('f'), 'f()') |
| 1398 | self.assertEqual(bar._callmethod('_h'), '_h()') |
| 1399 | |
| 1400 | self.assertEqual(list(baz), [i*i for i in range(10)]) |
| 1401 | |
| 1402 | manager.shutdown() |
| 1403 | |
| 1404 | # |
| 1405 | # Test of connecting to a remote server and using xmlrpclib for serialization |
| 1406 | # |
| 1407 | |
| 1408 | _queue = pyqueue.Queue() |
| 1409 | def get_queue(): |
| 1410 | return _queue |
| 1411 | |
| 1412 | class QueueManager(BaseManager): |
| 1413 | '''manager class used by server process''' |
| 1414 | QueueManager.register('get_queue', callable=get_queue) |
| 1415 | |
| 1416 | class QueueManager2(BaseManager): |
| 1417 | '''manager class which specifies the same interface as QueueManager''' |
| 1418 | QueueManager2.register('get_queue') |
| 1419 | |
| 1420 | |
| 1421 | SERIALIZER = 'xmlrpclib' |
| 1422 | |
| 1423 | class _TestRemoteManager(BaseTestCase): |
| 1424 | |
| 1425 | ALLOWED_TYPES = ('manager',) |
| 1426 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 1427 | @classmethod |
| 1428 | def _putter(cls, address, authkey): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1429 | manager = QueueManager2( |
| 1430 | address=address, authkey=authkey, serializer=SERIALIZER |
| 1431 | ) |
| 1432 | manager.connect() |
| 1433 | queue = manager.get_queue() |
| 1434 | queue.put(('hello world', None, True, 2.25)) |
| 1435 | |
| 1436 | def test_remote(self): |
| 1437 | authkey = os.urandom(32) |
| 1438 | |
| 1439 | manager = QueueManager( |
| 1440 | address=('localhost', 0), authkey=authkey, serializer=SERIALIZER |
| 1441 | ) |
| 1442 | manager.start() |
| 1443 | |
| 1444 | p = self.Process(target=self._putter, args=(manager.address, authkey)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1445 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1446 | p.start() |
| 1447 | |
| 1448 | manager2 = QueueManager2( |
| 1449 | address=manager.address, authkey=authkey, serializer=SERIALIZER |
| 1450 | ) |
| 1451 | manager2.connect() |
| 1452 | queue = manager2.get_queue() |
| 1453 | |
| 1454 | # Note that xmlrpclib will deserialize object as a list not a tuple |
| 1455 | self.assertEqual(queue.get(), ['hello world', None, True, 2.25]) |
| 1456 | |
| 1457 | # Because we are using xmlrpclib for serialization instead of |
| 1458 | # pickle this will cause a serialization error. |
| 1459 | self.assertRaises(Exception, queue.put, time.sleep) |
| 1460 | |
| 1461 | # Make queue finalizer run before the server is stopped |
| 1462 | del queue |
| 1463 | manager.shutdown() |
| 1464 | |
Jesse Noller | c5d28a0 | 2009-03-30 16:37:36 +0000 | [diff] [blame] | 1465 | class _TestManagerRestart(BaseTestCase): |
| 1466 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 1467 | @classmethod |
| 1468 | def _putter(cls, address, authkey): |
Jesse Noller | c5d28a0 | 2009-03-30 16:37:36 +0000 | [diff] [blame] | 1469 | manager = QueueManager( |
| 1470 | address=address, authkey=authkey, serializer=SERIALIZER) |
| 1471 | manager.connect() |
| 1472 | queue = manager.get_queue() |
| 1473 | queue.put('hello world') |
| 1474 | |
| 1475 | def test_rapid_restart(self): |
| 1476 | authkey = os.urandom(32) |
| 1477 | manager = QueueManager( |
Antoine Pitrou | 043bad0 | 2010-04-30 23:20:15 +0000 | [diff] [blame] | 1478 | address=('localhost', 0), authkey=authkey, serializer=SERIALIZER) |
Brian Curtin | 50be1ca | 2010-11-01 05:10:44 +0000 | [diff] [blame] | 1479 | srvr = manager.get_server() |
| 1480 | addr = srvr.address |
| 1481 | # Close the connection.Listener socket which gets opened as a part |
| 1482 | # of manager.get_server(). It's not needed for the test. |
| 1483 | srvr.listener.close() |
Jesse Noller | c5d28a0 | 2009-03-30 16:37:36 +0000 | [diff] [blame] | 1484 | manager.start() |
| 1485 | |
| 1486 | p = self.Process(target=self._putter, args=(manager.address, authkey)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1487 | p.daemon = True |
Jesse Noller | c5d28a0 | 2009-03-30 16:37:36 +0000 | [diff] [blame] | 1488 | p.start() |
| 1489 | queue = manager.get_queue() |
| 1490 | self.assertEqual(queue.get(), 'hello world') |
Jesse Noller | 35d1f00 | 2009-03-30 22:59:27 +0000 | [diff] [blame] | 1491 | del queue |
Jesse Noller | c5d28a0 | 2009-03-30 16:37:36 +0000 | [diff] [blame] | 1492 | manager.shutdown() |
| 1493 | manager = QueueManager( |
Antoine Pitrou | 043bad0 | 2010-04-30 23:20:15 +0000 | [diff] [blame] | 1494 | address=addr, authkey=authkey, serializer=SERIALIZER) |
Antoine Pitrou | c824e9a | 2011-04-05 18:11:33 +0200 | [diff] [blame] | 1495 | try: |
| 1496 | manager.start() |
| 1497 | except IOError as e: |
| 1498 | if e.errno != errno.EADDRINUSE: |
| 1499 | raise |
| 1500 | # Retry after some time, in case the old socket was lingering |
| 1501 | # (sporadic failure on buildbots) |
| 1502 | time.sleep(1.0) |
| 1503 | manager = QueueManager( |
| 1504 | address=addr, authkey=authkey, serializer=SERIALIZER) |
Jesse Noller | 35d1f00 | 2009-03-30 22:59:27 +0000 | [diff] [blame] | 1505 | manager.shutdown() |
Jesse Noller | c5d28a0 | 2009-03-30 16:37:36 +0000 | [diff] [blame] | 1506 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1507 | # |
| 1508 | # |
| 1509 | # |
| 1510 | |
| 1511 | SENTINEL = latin('') |
| 1512 | |
| 1513 | class _TestConnection(BaseTestCase): |
| 1514 | |
| 1515 | ALLOWED_TYPES = ('processes', 'threads') |
| 1516 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 1517 | @classmethod |
| 1518 | def _echo(cls, conn): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1519 | for msg in iter(conn.recv_bytes, SENTINEL): |
| 1520 | conn.send_bytes(msg) |
| 1521 | conn.close() |
| 1522 | |
| 1523 | def test_connection(self): |
| 1524 | conn, child_conn = self.Pipe() |
| 1525 | |
| 1526 | p = self.Process(target=self._echo, args=(child_conn,)) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 1527 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1528 | p.start() |
| 1529 | |
| 1530 | seq = [1, 2.25, None] |
| 1531 | msg = latin('hello world') |
| 1532 | longmsg = msg * 10 |
| 1533 | arr = array.array('i', list(range(4))) |
| 1534 | |
| 1535 | if self.TYPE == 'processes': |
| 1536 | self.assertEqual(type(conn.fileno()), int) |
| 1537 | |
| 1538 | self.assertEqual(conn.send(seq), None) |
| 1539 | self.assertEqual(conn.recv(), seq) |
| 1540 | |
| 1541 | self.assertEqual(conn.send_bytes(msg), None) |
| 1542 | self.assertEqual(conn.recv_bytes(), msg) |
| 1543 | |
| 1544 | if self.TYPE == 'processes': |
| 1545 | buffer = array.array('i', [0]*10) |
| 1546 | expected = list(arr) + [0] * (10 - len(arr)) |
| 1547 | self.assertEqual(conn.send_bytes(arr), None) |
| 1548 | self.assertEqual(conn.recv_bytes_into(buffer), |
| 1549 | len(arr) * buffer.itemsize) |
| 1550 | self.assertEqual(list(buffer), expected) |
| 1551 | |
| 1552 | buffer = array.array('i', [0]*10) |
| 1553 | expected = [0] * 3 + list(arr) + [0] * (10 - 3 - len(arr)) |
| 1554 | self.assertEqual(conn.send_bytes(arr), None) |
| 1555 | self.assertEqual(conn.recv_bytes_into(buffer, 3 * buffer.itemsize), |
| 1556 | len(arr) * buffer.itemsize) |
| 1557 | self.assertEqual(list(buffer), expected) |
| 1558 | |
| 1559 | buffer = bytearray(latin(' ' * 40)) |
| 1560 | self.assertEqual(conn.send_bytes(longmsg), None) |
| 1561 | try: |
| 1562 | res = conn.recv_bytes_into(buffer) |
| 1563 | except multiprocessing.BufferTooShort as e: |
| 1564 | self.assertEqual(e.args, (longmsg,)) |
| 1565 | else: |
| 1566 | self.fail('expected BufferTooShort, got %s' % res) |
| 1567 | |
| 1568 | poll = TimingWrapper(conn.poll) |
| 1569 | |
| 1570 | self.assertEqual(poll(), False) |
| 1571 | self.assertTimingAlmostEqual(poll.elapsed, 0) |
| 1572 | |
| 1573 | self.assertEqual(poll(TIMEOUT1), False) |
| 1574 | self.assertTimingAlmostEqual(poll.elapsed, TIMEOUT1) |
| 1575 | |
| 1576 | conn.send(None) |
| 1577 | |
| 1578 | self.assertEqual(poll(TIMEOUT1), True) |
| 1579 | self.assertTimingAlmostEqual(poll.elapsed, 0) |
| 1580 | |
| 1581 | self.assertEqual(conn.recv(), None) |
| 1582 | |
| 1583 | really_big_msg = latin('X') * (1024 * 1024 * 16) # 16Mb |
| 1584 | conn.send_bytes(really_big_msg) |
| 1585 | self.assertEqual(conn.recv_bytes(), really_big_msg) |
| 1586 | |
| 1587 | conn.send_bytes(SENTINEL) # tell child to quit |
| 1588 | child_conn.close() |
| 1589 | |
| 1590 | if self.TYPE == 'processes': |
| 1591 | self.assertEqual(conn.readable, True) |
| 1592 | self.assertEqual(conn.writable, True) |
| 1593 | self.assertRaises(EOFError, conn.recv) |
| 1594 | self.assertRaises(EOFError, conn.recv_bytes) |
| 1595 | |
| 1596 | p.join() |
| 1597 | |
| 1598 | def test_duplex_false(self): |
| 1599 | reader, writer = self.Pipe(duplex=False) |
| 1600 | self.assertEqual(writer.send(1), None) |
| 1601 | self.assertEqual(reader.recv(), 1) |
| 1602 | if self.TYPE == 'processes': |
| 1603 | self.assertEqual(reader.readable, True) |
| 1604 | self.assertEqual(reader.writable, False) |
| 1605 | self.assertEqual(writer.readable, False) |
| 1606 | self.assertEqual(writer.writable, True) |
| 1607 | self.assertRaises(IOError, reader.send, 2) |
| 1608 | self.assertRaises(IOError, writer.recv) |
| 1609 | self.assertRaises(IOError, writer.poll) |
| 1610 | |
| 1611 | def test_spawn_close(self): |
| 1612 | # We test that a pipe connection can be closed by parent |
| 1613 | # process immediately after child is spawned. On Windows this |
| 1614 | # would have sometimes failed on old versions because |
| 1615 | # child_conn would be closed before the child got a chance to |
| 1616 | # duplicate it. |
| 1617 | conn, child_conn = self.Pipe() |
| 1618 | |
| 1619 | p = self.Process(target=self._echo, args=(child_conn,)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1620 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1621 | p.start() |
| 1622 | child_conn.close() # this might complete before child initializes |
| 1623 | |
| 1624 | msg = latin('hello') |
| 1625 | conn.send_bytes(msg) |
| 1626 | self.assertEqual(conn.recv_bytes(), msg) |
| 1627 | |
| 1628 | conn.send_bytes(SENTINEL) |
| 1629 | conn.close() |
| 1630 | p.join() |
| 1631 | |
| 1632 | def test_sendbytes(self): |
| 1633 | if self.TYPE != 'processes': |
| 1634 | return |
| 1635 | |
| 1636 | msg = latin('abcdefghijklmnopqrstuvwxyz') |
| 1637 | a, b = self.Pipe() |
| 1638 | |
| 1639 | a.send_bytes(msg) |
| 1640 | self.assertEqual(b.recv_bytes(), msg) |
| 1641 | |
| 1642 | a.send_bytes(msg, 5) |
| 1643 | self.assertEqual(b.recv_bytes(), msg[5:]) |
| 1644 | |
| 1645 | a.send_bytes(msg, 7, 8) |
| 1646 | self.assertEqual(b.recv_bytes(), msg[7:7+8]) |
| 1647 | |
| 1648 | a.send_bytes(msg, 26) |
| 1649 | self.assertEqual(b.recv_bytes(), latin('')) |
| 1650 | |
| 1651 | a.send_bytes(msg, 26, 0) |
| 1652 | self.assertEqual(b.recv_bytes(), latin('')) |
| 1653 | |
| 1654 | self.assertRaises(ValueError, a.send_bytes, msg, 27) |
| 1655 | |
| 1656 | self.assertRaises(ValueError, a.send_bytes, msg, 22, 5) |
| 1657 | |
| 1658 | self.assertRaises(ValueError, a.send_bytes, msg, 26, 1) |
| 1659 | |
| 1660 | self.assertRaises(ValueError, a.send_bytes, msg, -1) |
| 1661 | |
| 1662 | self.assertRaises(ValueError, a.send_bytes, msg, 4, -1) |
| 1663 | |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1664 | @classmethod |
| 1665 | def _is_fd_assigned(cls, fd): |
| 1666 | try: |
| 1667 | os.fstat(fd) |
| 1668 | except OSError as e: |
| 1669 | if e.errno == errno.EBADF: |
| 1670 | return False |
| 1671 | raise |
| 1672 | else: |
| 1673 | return True |
| 1674 | |
| 1675 | @classmethod |
| 1676 | def _writefd(cls, conn, data, create_dummy_fds=False): |
| 1677 | if create_dummy_fds: |
| 1678 | for i in range(0, 256): |
| 1679 | if not cls._is_fd_assigned(i): |
| 1680 | os.dup2(conn.fileno(), i) |
| 1681 | fd = reduction.recv_handle(conn) |
| 1682 | if msvcrt: |
| 1683 | fd = msvcrt.open_osfhandle(fd, os.O_WRONLY) |
| 1684 | os.write(fd, data) |
| 1685 | os.close(fd) |
| 1686 | |
Charles-François Natali | e51c8da | 2011-09-21 18:48:21 +0200 | [diff] [blame] | 1687 | @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1688 | def test_fd_transfer(self): |
| 1689 | if self.TYPE != 'processes': |
| 1690 | self.skipTest("only makes sense with processes") |
| 1691 | conn, child_conn = self.Pipe(duplex=True) |
| 1692 | |
| 1693 | p = self.Process(target=self._writefd, args=(child_conn, b"foo")) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1694 | p.daemon = True |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1695 | p.start() |
Victor Stinner | d0b10a6 | 2011-09-21 01:10:29 +0200 | [diff] [blame] | 1696 | self.addCleanup(test.support.unlink, test.support.TESTFN) |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1697 | with open(test.support.TESTFN, "wb") as f: |
| 1698 | fd = f.fileno() |
| 1699 | if msvcrt: |
| 1700 | fd = msvcrt.get_osfhandle(fd) |
| 1701 | reduction.send_handle(conn, fd, p.pid) |
| 1702 | p.join() |
| 1703 | with open(test.support.TESTFN, "rb") as f: |
| 1704 | self.assertEqual(f.read(), b"foo") |
| 1705 | |
Charles-François Natali | e51c8da | 2011-09-21 18:48:21 +0200 | [diff] [blame] | 1706 | @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1707 | @unittest.skipIf(sys.platform == "win32", |
| 1708 | "test semantics don't make sense on Windows") |
| 1709 | @unittest.skipIf(MAXFD <= 256, |
| 1710 | "largest assignable fd number is too small") |
| 1711 | @unittest.skipUnless(hasattr(os, "dup2"), |
| 1712 | "test needs os.dup2()") |
| 1713 | def test_large_fd_transfer(self): |
| 1714 | # With fd > 256 (issue #11657) |
| 1715 | if self.TYPE != 'processes': |
| 1716 | self.skipTest("only makes sense with processes") |
| 1717 | conn, child_conn = self.Pipe(duplex=True) |
| 1718 | |
| 1719 | p = self.Process(target=self._writefd, args=(child_conn, b"bar", True)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1720 | p.daemon = True |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1721 | p.start() |
Victor Stinner | d0b10a6 | 2011-09-21 01:10:29 +0200 | [diff] [blame] | 1722 | self.addCleanup(test.support.unlink, test.support.TESTFN) |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1723 | with open(test.support.TESTFN, "wb") as f: |
| 1724 | fd = f.fileno() |
| 1725 | for newfd in range(256, MAXFD): |
| 1726 | if not self._is_fd_assigned(newfd): |
| 1727 | break |
| 1728 | else: |
| 1729 | self.fail("could not find an unassigned large file descriptor") |
| 1730 | os.dup2(fd, newfd) |
| 1731 | try: |
| 1732 | reduction.send_handle(conn, newfd, p.pid) |
| 1733 | finally: |
| 1734 | os.close(newfd) |
| 1735 | p.join() |
| 1736 | with open(test.support.TESTFN, "rb") as f: |
| 1737 | self.assertEqual(f.read(), b"bar") |
| 1738 | |
Jesus Cea | 4507e64 | 2011-09-21 03:53:25 +0200 | [diff] [blame] | 1739 | @classmethod |
| 1740 | def _send_data_without_fd(self, conn): |
| 1741 | os.write(conn.fileno(), b"\0") |
| 1742 | |
Charles-François Natali | e51c8da | 2011-09-21 18:48:21 +0200 | [diff] [blame] | 1743 | @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") |
Jesus Cea | 4507e64 | 2011-09-21 03:53:25 +0200 | [diff] [blame] | 1744 | @unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows") |
| 1745 | def test_missing_fd_transfer(self): |
| 1746 | # Check that exception is raised when received data is not |
| 1747 | # accompanied by a file descriptor in ancillary data. |
| 1748 | if self.TYPE != 'processes': |
| 1749 | self.skipTest("only makes sense with processes") |
| 1750 | conn, child_conn = self.Pipe(duplex=True) |
| 1751 | |
| 1752 | p = self.Process(target=self._send_data_without_fd, args=(child_conn,)) |
| 1753 | p.daemon = True |
| 1754 | p.start() |
| 1755 | self.assertRaises(RuntimeError, reduction.recv_handle, conn) |
| 1756 | p.join() |
Antoine Pitrou | bcb39d4 | 2011-08-23 19:46:22 +0200 | [diff] [blame] | 1757 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1758 | class _TestListenerClient(BaseTestCase): |
| 1759 | |
| 1760 | ALLOWED_TYPES = ('processes', 'threads') |
| 1761 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 1762 | @classmethod |
| 1763 | def _test(cls, address): |
| 1764 | conn = cls.connection.Client(address) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1765 | conn.send('hello') |
| 1766 | conn.close() |
| 1767 | |
| 1768 | def test_listener_client(self): |
| 1769 | for family in self.connection.families: |
| 1770 | l = self.connection.Listener(family=family) |
| 1771 | p = self.Process(target=self._test, args=(l.address,)) |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 1772 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1773 | p.start() |
| 1774 | conn = l.accept() |
| 1775 | self.assertEqual(conn.recv(), 'hello') |
| 1776 | p.join() |
| 1777 | l.close() |
Richard Oudkerk | 7ef909c | 2012-05-05 20:41:23 +0100 | [diff] [blame] | 1778 | |
| 1779 | def test_issue14725(self): |
| 1780 | l = self.connection.Listener() |
| 1781 | p = self.Process(target=self._test, args=(l.address,)) |
| 1782 | p.daemon = True |
| 1783 | p.start() |
| 1784 | time.sleep(1) |
| 1785 | # On Windows the client process should by now have connected, |
| 1786 | # written data and closed the pipe handle by now. This causes |
| 1787 | # ConnectNamdedPipe() to fail with ERROR_NO_DATA. See Issue |
| 1788 | # 14725. |
| 1789 | conn = l.accept() |
| 1790 | self.assertEqual(conn.recv(), 'hello') |
| 1791 | conn.close() |
| 1792 | p.join() |
| 1793 | l.close() |
| 1794 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1795 | # |
| 1796 | # Test of sending connection and socket objects between processes |
| 1797 | # |
Benjamin Peterson | b29cbbc | 2008-06-16 20:57:14 +0000 | [diff] [blame] | 1798 | """ |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1799 | class _TestPicklingConnections(BaseTestCase): |
| 1800 | |
| 1801 | ALLOWED_TYPES = ('processes',) |
| 1802 | |
| 1803 | def _listener(self, conn, families): |
| 1804 | for fam in families: |
| 1805 | l = self.connection.Listener(family=fam) |
| 1806 | conn.send(l.address) |
| 1807 | new_conn = l.accept() |
| 1808 | conn.send(new_conn) |
| 1809 | |
| 1810 | if self.TYPE == 'processes': |
| 1811 | l = socket.socket() |
| 1812 | l.bind(('localhost', 0)) |
| 1813 | conn.send(l.getsockname()) |
| 1814 | l.listen(1) |
| 1815 | new_conn, addr = l.accept() |
| 1816 | conn.send(new_conn) |
| 1817 | |
| 1818 | conn.recv() |
| 1819 | |
| 1820 | def _remote(self, conn): |
| 1821 | for (address, msg) in iter(conn.recv, None): |
| 1822 | client = self.connection.Client(address) |
| 1823 | client.send(msg.upper()) |
| 1824 | client.close() |
| 1825 | |
| 1826 | if self.TYPE == 'processes': |
| 1827 | address, msg = conn.recv() |
| 1828 | client = socket.socket() |
| 1829 | client.connect(address) |
| 1830 | client.sendall(msg.upper()) |
| 1831 | client.close() |
| 1832 | |
| 1833 | conn.close() |
| 1834 | |
| 1835 | def test_pickling(self): |
| 1836 | try: |
| 1837 | multiprocessing.allow_connection_pickling() |
| 1838 | except ImportError: |
| 1839 | return |
| 1840 | |
| 1841 | families = self.connection.families |
| 1842 | |
| 1843 | lconn, lconn0 = self.Pipe() |
| 1844 | lp = self.Process(target=self._listener, args=(lconn0, families)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1845 | lp.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1846 | lp.start() |
| 1847 | lconn0.close() |
| 1848 | |
| 1849 | rconn, rconn0 = self.Pipe() |
| 1850 | rp = self.Process(target=self._remote, args=(rconn0,)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1851 | rp.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1852 | rp.start() |
| 1853 | rconn0.close() |
| 1854 | |
| 1855 | for fam in families: |
| 1856 | msg = ('This connection uses family %s' % fam).encode('ascii') |
| 1857 | address = lconn.recv() |
| 1858 | rconn.send((address, msg)) |
| 1859 | new_conn = lconn.recv() |
| 1860 | self.assertEqual(new_conn.recv(), msg.upper()) |
| 1861 | |
| 1862 | rconn.send(None) |
| 1863 | |
| 1864 | if self.TYPE == 'processes': |
| 1865 | msg = latin('This connection uses a normal socket') |
| 1866 | address = lconn.recv() |
| 1867 | rconn.send((address, msg)) |
| 1868 | if hasattr(socket, 'fromfd'): |
| 1869 | new_conn = lconn.recv() |
| 1870 | self.assertEqual(new_conn.recv(100), msg.upper()) |
| 1871 | else: |
| 1872 | # XXX On Windows with Py2.6 need to backport fromfd() |
| 1873 | discard = lconn.recv_bytes() |
| 1874 | |
| 1875 | lconn.send(None) |
| 1876 | |
| 1877 | rconn.close() |
| 1878 | lconn.close() |
| 1879 | |
| 1880 | lp.join() |
| 1881 | rp.join() |
Benjamin Peterson | b29cbbc | 2008-06-16 20:57:14 +0000 | [diff] [blame] | 1882 | """ |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1883 | # |
| 1884 | # |
| 1885 | # |
| 1886 | |
| 1887 | class _TestHeap(BaseTestCase): |
| 1888 | |
| 1889 | ALLOWED_TYPES = ('processes',) |
| 1890 | |
| 1891 | def test_heap(self): |
| 1892 | iterations = 5000 |
| 1893 | maxblocks = 50 |
| 1894 | blocks = [] |
| 1895 | |
| 1896 | # create and destroy lots of blocks of different sizes |
| 1897 | for i in range(iterations): |
| 1898 | size = int(random.lognormvariate(0, 1) * 1000) |
| 1899 | b = multiprocessing.heap.BufferWrapper(size) |
| 1900 | blocks.append(b) |
| 1901 | if len(blocks) > maxblocks: |
| 1902 | i = random.randrange(maxblocks) |
| 1903 | del blocks[i] |
| 1904 | |
| 1905 | # get the heap object |
| 1906 | heap = multiprocessing.heap.BufferWrapper._heap |
| 1907 | |
| 1908 | # verify the state of the heap |
| 1909 | all = [] |
| 1910 | occupied = 0 |
Charles-François Natali | 778db49 | 2011-07-02 14:35:49 +0200 | [diff] [blame] | 1911 | heap._lock.acquire() |
| 1912 | self.addCleanup(heap._lock.release) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1913 | for L in list(heap._len_to_seq.values()): |
| 1914 | for arena, start, stop in L: |
| 1915 | all.append((heap._arenas.index(arena), start, stop, |
| 1916 | stop-start, 'free')) |
| 1917 | for arena, start, stop in heap._allocated_blocks: |
| 1918 | all.append((heap._arenas.index(arena), start, stop, |
| 1919 | stop-start, 'occupied')) |
| 1920 | occupied += (stop-start) |
| 1921 | |
| 1922 | all.sort() |
| 1923 | |
| 1924 | for i in range(len(all)-1): |
| 1925 | (arena, start, stop) = all[i][:3] |
| 1926 | (narena, nstart, nstop) = all[i+1][:3] |
| 1927 | self.assertTrue((arena != narena and nstart == 0) or |
| 1928 | (stop == nstart)) |
| 1929 | |
Charles-François Natali | 778db49 | 2011-07-02 14:35:49 +0200 | [diff] [blame] | 1930 | def test_free_from_gc(self): |
| 1931 | # Check that freeing of blocks by the garbage collector doesn't deadlock |
| 1932 | # (issue #12352). |
| 1933 | # Make sure the GC is enabled, and set lower collection thresholds to |
| 1934 | # make collections more frequent (and increase the probability of |
| 1935 | # deadlock). |
| 1936 | if not gc.isenabled(): |
| 1937 | gc.enable() |
| 1938 | self.addCleanup(gc.disable) |
| 1939 | thresholds = gc.get_threshold() |
| 1940 | self.addCleanup(gc.set_threshold, *thresholds) |
| 1941 | gc.set_threshold(10) |
| 1942 | |
| 1943 | # perform numerous block allocations, with cyclic references to make |
| 1944 | # sure objects are collected asynchronously by the gc |
| 1945 | for i in range(5000): |
| 1946 | a = multiprocessing.heap.BufferWrapper(1) |
| 1947 | b = multiprocessing.heap.BufferWrapper(1) |
| 1948 | # circular references |
| 1949 | a.buddy = b |
| 1950 | b.buddy = a |
| 1951 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1952 | # |
| 1953 | # |
| 1954 | # |
| 1955 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1956 | class _Foo(Structure): |
| 1957 | _fields_ = [ |
| 1958 | ('x', c_int), |
| 1959 | ('y', c_double) |
| 1960 | ] |
| 1961 | |
| 1962 | class _TestSharedCTypes(BaseTestCase): |
| 1963 | |
| 1964 | ALLOWED_TYPES = ('processes',) |
| 1965 | |
Antoine Pitrou | 7744e2a | 2010-11-22 16:26:21 +0000 | [diff] [blame] | 1966 | def setUp(self): |
| 1967 | if not HAS_SHAREDCTYPES: |
| 1968 | self.skipTest("requires multiprocessing.sharedctypes") |
| 1969 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 1970 | @classmethod |
| 1971 | def _double(cls, x, y, foo, arr, string): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1972 | x.value *= 2 |
| 1973 | y.value *= 2 |
| 1974 | foo.x *= 2 |
| 1975 | foo.y *= 2 |
| 1976 | string.value *= 2 |
| 1977 | for i in range(len(arr)): |
| 1978 | arr[i] *= 2 |
| 1979 | |
| 1980 | def test_sharedctypes(self, lock=False): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1981 | x = Value('i', 7, lock=lock) |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1982 | y = Value(c_double, 1.0/3.0, lock=lock) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1983 | foo = Value(_Foo, 3, 2, lock=lock) |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1984 | arr = self.Array('d', list(range(10)), lock=lock) |
| 1985 | string = self.Array('c', 20, lock=lock) |
Brian Curtin | afa88b5 | 2010-10-07 01:12:19 +0000 | [diff] [blame] | 1986 | string.value = latin('hello') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1987 | |
| 1988 | p = self.Process(target=self._double, args=(x, y, foo, arr, string)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 1989 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1990 | p.start() |
| 1991 | p.join() |
| 1992 | |
| 1993 | self.assertEqual(x.value, 14) |
| 1994 | self.assertAlmostEqual(y.value, 2.0/3.0) |
| 1995 | self.assertEqual(foo.x, 6) |
| 1996 | self.assertAlmostEqual(foo.y, 4.0) |
| 1997 | for i in range(10): |
| 1998 | self.assertAlmostEqual(arr[i], i*2) |
| 1999 | self.assertEqual(string.value, latin('hellohello')) |
| 2000 | |
| 2001 | def test_synchronize(self): |
| 2002 | self.test_sharedctypes(lock=True) |
| 2003 | |
| 2004 | def test_copy(self): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2005 | foo = _Foo(2, 5.0) |
Brian Curtin | afa88b5 | 2010-10-07 01:12:19 +0000 | [diff] [blame] | 2006 | bar = copy(foo) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2007 | foo.x = 0 |
| 2008 | foo.y = 0 |
| 2009 | self.assertEqual(bar.x, 2) |
| 2010 | self.assertAlmostEqual(bar.y, 5.0) |
| 2011 | |
| 2012 | # |
| 2013 | # |
| 2014 | # |
| 2015 | |
| 2016 | class _TestFinalize(BaseTestCase): |
| 2017 | |
| 2018 | ALLOWED_TYPES = ('processes',) |
| 2019 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 2020 | @classmethod |
| 2021 | def _test_finalize(cls, conn): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2022 | class Foo(object): |
| 2023 | pass |
| 2024 | |
| 2025 | a = Foo() |
| 2026 | util.Finalize(a, conn.send, args=('a',)) |
| 2027 | del a # triggers callback for a |
| 2028 | |
| 2029 | b = Foo() |
| 2030 | close_b = util.Finalize(b, conn.send, args=('b',)) |
| 2031 | close_b() # triggers callback for b |
| 2032 | close_b() # does nothing because callback has already been called |
| 2033 | del b # does nothing because callback has already been called |
| 2034 | |
| 2035 | c = Foo() |
| 2036 | util.Finalize(c, conn.send, args=('c',)) |
| 2037 | |
| 2038 | d10 = Foo() |
| 2039 | util.Finalize(d10, conn.send, args=('d10',), exitpriority=1) |
| 2040 | |
| 2041 | d01 = Foo() |
| 2042 | util.Finalize(d01, conn.send, args=('d01',), exitpriority=0) |
| 2043 | d02 = Foo() |
| 2044 | util.Finalize(d02, conn.send, args=('d02',), exitpriority=0) |
| 2045 | d03 = Foo() |
| 2046 | util.Finalize(d03, conn.send, args=('d03',), exitpriority=0) |
| 2047 | |
| 2048 | util.Finalize(None, conn.send, args=('e',), exitpriority=-10) |
| 2049 | |
| 2050 | util.Finalize(None, conn.send, args=('STOP',), exitpriority=-100) |
| 2051 | |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 2052 | # call multiprocessing's cleanup function then exit process without |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2053 | # garbage collecting locals |
| 2054 | util._exit_function() |
| 2055 | conn.close() |
| 2056 | os._exit(0) |
| 2057 | |
| 2058 | def test_finalize(self): |
| 2059 | conn, child_conn = self.Pipe() |
| 2060 | |
| 2061 | p = self.Process(target=self._test_finalize, args=(child_conn,)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 2062 | p.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2063 | p.start() |
| 2064 | p.join() |
| 2065 | |
| 2066 | result = [obj for obj in iter(conn.recv, 'STOP')] |
| 2067 | self.assertEqual(result, ['a', 'b', 'd10', 'd03', 'd02', 'd01', 'e']) |
| 2068 | |
| 2069 | # |
| 2070 | # Test that from ... import * works for each module |
| 2071 | # |
| 2072 | |
| 2073 | class _TestImportStar(BaseTestCase): |
| 2074 | |
| 2075 | ALLOWED_TYPES = ('processes',) |
| 2076 | |
| 2077 | def test_import(self): |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 2078 | modules = [ |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2079 | 'multiprocessing', 'multiprocessing.connection', |
| 2080 | 'multiprocessing.heap', 'multiprocessing.managers', |
| 2081 | 'multiprocessing.pool', 'multiprocessing.process', |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2082 | 'multiprocessing.synchronize', 'multiprocessing.util' |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 2083 | ] |
| 2084 | |
Charles-François Natali | e51c8da | 2011-09-21 18:48:21 +0200 | [diff] [blame] | 2085 | if HAS_REDUCTION: |
| 2086 | modules.append('multiprocessing.reduction') |
| 2087 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 2088 | if c_int is not None: |
| 2089 | # This module requires _ctypes |
| 2090 | modules.append('multiprocessing.sharedctypes') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2091 | |
| 2092 | for name in modules: |
| 2093 | __import__(name) |
| 2094 | mod = sys.modules[name] |
| 2095 | |
| 2096 | for attr in getattr(mod, '__all__', ()): |
| 2097 | self.assertTrue( |
| 2098 | hasattr(mod, attr), |
| 2099 | '%r does not have attribute %r' % (mod, attr) |
| 2100 | ) |
| 2101 | |
| 2102 | # |
| 2103 | # Quick test that logging works -- does not test logging output |
| 2104 | # |
| 2105 | |
| 2106 | class _TestLogging(BaseTestCase): |
| 2107 | |
| 2108 | ALLOWED_TYPES = ('processes',) |
| 2109 | |
| 2110 | def test_enable_logging(self): |
| 2111 | logger = multiprocessing.get_logger() |
| 2112 | logger.setLevel(util.SUBWARNING) |
| 2113 | self.assertTrue(logger is not None) |
| 2114 | logger.debug('this will not be printed') |
| 2115 | logger.info('nor will this') |
| 2116 | logger.setLevel(LOG_LEVEL) |
| 2117 | |
Antoine Pitrou | 0d1b38c | 2010-11-02 23:50:11 +0000 | [diff] [blame] | 2118 | @classmethod |
| 2119 | def _test_level(cls, conn): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2120 | logger = multiprocessing.get_logger() |
| 2121 | conn.send(logger.getEffectiveLevel()) |
| 2122 | |
| 2123 | def test_level(self): |
| 2124 | LEVEL1 = 32 |
| 2125 | LEVEL2 = 37 |
| 2126 | |
| 2127 | logger = multiprocessing.get_logger() |
| 2128 | root_logger = logging.getLogger() |
| 2129 | root_level = root_logger.level |
| 2130 | |
| 2131 | reader, writer = multiprocessing.Pipe(duplex=False) |
| 2132 | |
| 2133 | logger.setLevel(LEVEL1) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 2134 | p = self.Process(target=self._test_level, args=(writer,)) |
| 2135 | p.daemon = True |
| 2136 | p.start() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2137 | self.assertEqual(LEVEL1, reader.recv()) |
| 2138 | |
| 2139 | logger.setLevel(logging.NOTSET) |
| 2140 | root_logger.setLevel(LEVEL2) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 2141 | p = self.Process(target=self._test_level, args=(writer,)) |
| 2142 | p.daemon = True |
| 2143 | p.start() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2144 | self.assertEqual(LEVEL2, reader.recv()) |
| 2145 | |
| 2146 | root_logger.setLevel(root_level) |
| 2147 | logger.setLevel(level=LOG_LEVEL) |
| 2148 | |
Jesse Noller | b9a49b7 | 2009-11-21 18:09:38 +0000 | [diff] [blame] | 2149 | |
Jesse Noller | f4ae35f | 2009-11-24 14:22:24 +0000 | [diff] [blame] | 2150 | # class _TestLoggingProcessName(BaseTestCase): |
| 2151 | # |
| 2152 | # def handle(self, record): |
| 2153 | # assert record.processName == multiprocessing.current_process().name |
| 2154 | # self.__handled = True |
| 2155 | # |
| 2156 | # def test_logging(self): |
| 2157 | # handler = logging.Handler() |
| 2158 | # handler.handle = self.handle |
| 2159 | # self.__handled = False |
| 2160 | # # Bypass getLogger() and side-effects |
| 2161 | # logger = logging.getLoggerClass()( |
| 2162 | # 'multiprocessing.test.TestLoggingProcessName') |
| 2163 | # logger.addHandler(handler) |
| 2164 | # logger.propagate = False |
| 2165 | # |
| 2166 | # logger.warn('foo') |
| 2167 | # assert self.__handled |
Jesse Noller | b9a49b7 | 2009-11-21 18:09:38 +0000 | [diff] [blame] | 2168 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2169 | # |
Jesse Noller | 6214edd | 2009-01-19 16:23:53 +0000 | [diff] [blame] | 2170 | # Test to verify handle verification, see issue 3321 |
| 2171 | # |
| 2172 | |
| 2173 | class TestInvalidHandle(unittest.TestCase): |
| 2174 | |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 2175 | @unittest.skipIf(WIN32, "skipped on Windows") |
Jesse Noller | 6214edd | 2009-01-19 16:23:53 +0000 | [diff] [blame] | 2176 | def test_invalid_handles(self): |
Jesse Noller | 6214edd | 2009-01-19 16:23:53 +0000 | [diff] [blame] | 2177 | conn = _multiprocessing.Connection(44977608) |
| 2178 | self.assertRaises(IOError, conn.poll) |
| 2179 | self.assertRaises(IOError, _multiprocessing.Connection, -1) |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 2180 | |
Jesse Noller | 6214edd | 2009-01-19 16:23:53 +0000 | [diff] [blame] | 2181 | # |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2182 | # Functions used to create test cases from the base ones in this module |
| 2183 | # |
| 2184 | |
| 2185 | def get_attributes(Source, names): |
| 2186 | d = {} |
| 2187 | for name in names: |
| 2188 | obj = getattr(Source, name) |
| 2189 | if type(obj) == type(get_attributes): |
| 2190 | obj = staticmethod(obj) |
| 2191 | d[name] = obj |
| 2192 | return d |
| 2193 | |
| 2194 | def create_test_cases(Mixin, type): |
| 2195 | result = {} |
| 2196 | glob = globals() |
Florent Xicluna | fd1b093 | 2010-03-28 00:25:02 +0000 | [diff] [blame] | 2197 | Type = type.capitalize() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2198 | |
| 2199 | for name in list(glob.keys()): |
| 2200 | if name.startswith('_Test'): |
| 2201 | base = glob[name] |
| 2202 | if type in base.ALLOWED_TYPES: |
| 2203 | newname = 'With' + Type + name[1:] |
| 2204 | class Temp(base, unittest.TestCase, Mixin): |
| 2205 | pass |
| 2206 | result[newname] = Temp |
| 2207 | Temp.__name__ = newname |
| 2208 | Temp.__module__ = Mixin.__module__ |
| 2209 | return result |
| 2210 | |
| 2211 | # |
| 2212 | # Create test cases |
| 2213 | # |
| 2214 | |
| 2215 | class ProcessesMixin(object): |
| 2216 | TYPE = 'processes' |
| 2217 | Process = multiprocessing.Process |
| 2218 | locals().update(get_attributes(multiprocessing, ( |
| 2219 | 'Queue', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', |
| 2220 | 'Condition', 'Event', 'Value', 'Array', 'RawValue', |
| 2221 | 'RawArray', 'current_process', 'active_children', 'Pipe', |
Richard Oudkerk | e41682b | 2012-06-06 19:04:57 +0100 | [diff] [blame] | 2222 | 'connection', 'JoinableQueue', 'Pool' |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2223 | ))) |
| 2224 | |
| 2225 | testcases_processes = create_test_cases(ProcessesMixin, type='processes') |
| 2226 | globals().update(testcases_processes) |
| 2227 | |
| 2228 | |
| 2229 | class ManagerMixin(object): |
| 2230 | TYPE = 'manager' |
| 2231 | Process = multiprocessing.Process |
| 2232 | manager = object.__new__(multiprocessing.managers.SyncManager) |
| 2233 | locals().update(get_attributes(manager, ( |
| 2234 | 'Queue', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', |
| 2235 | 'Condition', 'Event', 'Value', 'Array', 'list', 'dict', |
Richard Oudkerk | e41682b | 2012-06-06 19:04:57 +0100 | [diff] [blame] | 2236 | 'Namespace', 'JoinableQueue', 'Pool' |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2237 | ))) |
| 2238 | |
| 2239 | testcases_manager = create_test_cases(ManagerMixin, type='manager') |
| 2240 | globals().update(testcases_manager) |
| 2241 | |
| 2242 | |
| 2243 | class ThreadsMixin(object): |
| 2244 | TYPE = 'threads' |
| 2245 | Process = multiprocessing.dummy.Process |
| 2246 | locals().update(get_attributes(multiprocessing.dummy, ( |
| 2247 | 'Queue', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', |
| 2248 | 'Condition', 'Event', 'Value', 'Array', 'current_process', |
| 2249 | 'active_children', 'Pipe', 'connection', 'dict', 'list', |
Richard Oudkerk | e41682b | 2012-06-06 19:04:57 +0100 | [diff] [blame] | 2250 | 'Namespace', 'JoinableQueue', 'Pool' |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2251 | ))) |
| 2252 | |
| 2253 | testcases_threads = create_test_cases(ThreadsMixin, type='threads') |
| 2254 | globals().update(testcases_threads) |
| 2255 | |
Neal Norwitz | 5d6415e | 2008-08-25 01:53:32 +0000 | [diff] [blame] | 2256 | class OtherTest(unittest.TestCase): |
| 2257 | # TODO: add more tests for deliver/answer challenge. |
| 2258 | def test_deliver_challenge_auth_failure(self): |
| 2259 | class _FakeConnection(object): |
| 2260 | def recv_bytes(self, size): |
Neal Norwitz | ec105ad | 2008-08-25 03:05:54 +0000 | [diff] [blame] | 2261 | return b'something bogus' |
Neal Norwitz | 5d6415e | 2008-08-25 01:53:32 +0000 | [diff] [blame] | 2262 | def send_bytes(self, data): |
| 2263 | pass |
| 2264 | self.assertRaises(multiprocessing.AuthenticationError, |
| 2265 | multiprocessing.connection.deliver_challenge, |
| 2266 | _FakeConnection(), b'abc') |
| 2267 | |
| 2268 | def test_answer_challenge_auth_failure(self): |
| 2269 | class _FakeConnection(object): |
| 2270 | def __init__(self): |
| 2271 | self.count = 0 |
| 2272 | def recv_bytes(self, size): |
| 2273 | self.count += 1 |
| 2274 | if self.count == 1: |
| 2275 | return multiprocessing.connection.CHALLENGE |
| 2276 | elif self.count == 2: |
Neal Norwitz | ec105ad | 2008-08-25 03:05:54 +0000 | [diff] [blame] | 2277 | return b'something bogus' |
| 2278 | return b'' |
Neal Norwitz | 5d6415e | 2008-08-25 01:53:32 +0000 | [diff] [blame] | 2279 | def send_bytes(self, data): |
| 2280 | pass |
| 2281 | self.assertRaises(multiprocessing.AuthenticationError, |
| 2282 | multiprocessing.connection.answer_challenge, |
| 2283 | _FakeConnection(), b'abc') |
| 2284 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 2285 | # |
| 2286 | # Test Manager.start()/Pool.__init__() initializer feature - see issue 5585 |
| 2287 | # |
| 2288 | |
| 2289 | def initializer(ns): |
| 2290 | ns.test += 1 |
| 2291 | |
| 2292 | class TestInitializers(unittest.TestCase): |
| 2293 | def setUp(self): |
| 2294 | self.mgr = multiprocessing.Manager() |
| 2295 | self.ns = self.mgr.Namespace() |
| 2296 | self.ns.test = 0 |
| 2297 | |
| 2298 | def tearDown(self): |
| 2299 | self.mgr.shutdown() |
| 2300 | |
| 2301 | def test_manager_initializer(self): |
| 2302 | m = multiprocessing.managers.SyncManager() |
| 2303 | self.assertRaises(TypeError, m.start, 1) |
| 2304 | m.start(initializer, (self.ns,)) |
| 2305 | self.assertEqual(self.ns.test, 1) |
| 2306 | m.shutdown() |
| 2307 | |
| 2308 | def test_pool_initializer(self): |
| 2309 | self.assertRaises(TypeError, multiprocessing.Pool, initializer=1) |
| 2310 | p = multiprocessing.Pool(1, initializer, (self.ns,)) |
| 2311 | p.close() |
| 2312 | p.join() |
| 2313 | self.assertEqual(self.ns.test, 1) |
| 2314 | |
Alexandre Vassalotti | c57a84f | 2009-07-17 12:07:01 +0000 | [diff] [blame] | 2315 | # |
| 2316 | # Issue 5155, 5313, 5331: Test process in processes |
| 2317 | # Verifies os.close(sys.stdin.fileno) vs. sys.stdin.close() behavior |
| 2318 | # |
| 2319 | |
| 2320 | def _ThisSubProcess(q): |
| 2321 | try: |
| 2322 | item = q.get(block=False) |
| 2323 | except pyqueue.Empty: |
| 2324 | pass |
| 2325 | |
| 2326 | def _TestProcess(q): |
| 2327 | queue = multiprocessing.Queue() |
| 2328 | subProc = multiprocessing.Process(target=_ThisSubProcess, args=(queue,)) |
Jesus Cea | 94f964f | 2011-09-09 20:26:57 +0200 | [diff] [blame] | 2329 | subProc.daemon = True |
Alexandre Vassalotti | c57a84f | 2009-07-17 12:07:01 +0000 | [diff] [blame] | 2330 | subProc.start() |
| 2331 | subProc.join() |
| 2332 | |
| 2333 | def _afunc(x): |
| 2334 | return x*x |
| 2335 | |
| 2336 | def pool_in_process(): |
| 2337 | pool = multiprocessing.Pool(processes=4) |
| 2338 | x = pool.map(_afunc, [1, 2, 3, 4, 5, 6, 7]) |
| 2339 | |
| 2340 | class _file_like(object): |
| 2341 | def __init__(self, delegate): |
| 2342 | self._delegate = delegate |
| 2343 | self._pid = None |
| 2344 | |
| 2345 | @property |
| 2346 | def cache(self): |
| 2347 | pid = os.getpid() |
| 2348 | # There are no race conditions since fork keeps only the running thread |
| 2349 | if pid != self._pid: |
| 2350 | self._pid = pid |
| 2351 | self._cache = [] |
| 2352 | return self._cache |
| 2353 | |
| 2354 | def write(self, data): |
| 2355 | self.cache.append(data) |
| 2356 | |
| 2357 | def flush(self): |
| 2358 | self._delegate.write(''.join(self.cache)) |
| 2359 | self._cache = [] |
| 2360 | |
| 2361 | class TestStdinBadfiledescriptor(unittest.TestCase): |
| 2362 | |
| 2363 | def test_queue_in_process(self): |
| 2364 | queue = multiprocessing.Queue() |
| 2365 | proc = multiprocessing.Process(target=_TestProcess, args=(queue,)) |
| 2366 | proc.start() |
| 2367 | proc.join() |
| 2368 | |
| 2369 | def test_pool_in_process(self): |
| 2370 | p = multiprocessing.Process(target=pool_in_process) |
| 2371 | p.start() |
| 2372 | p.join() |
| 2373 | |
| 2374 | def test_flushing(self): |
| 2375 | sio = io.StringIO() |
| 2376 | flike = _file_like(sio) |
| 2377 | flike.write('foo') |
| 2378 | proc = multiprocessing.Process(target=lambda: flike.flush()) |
| 2379 | flike.flush() |
| 2380 | assert sio.getvalue() == 'foo' |
| 2381 | |
Antoine Pitrou | 709176f | 2012-04-01 17:19:09 +0200 | [diff] [blame] | 2382 | |
| 2383 | # |
| 2384 | # Issue 14151: Test invalid family on invalid environment |
| 2385 | # |
| 2386 | |
| 2387 | class TestInvalidFamily(unittest.TestCase): |
| 2388 | |
| 2389 | @unittest.skipIf(WIN32, "skipped on Windows") |
| 2390 | def test_invalid_family(self): |
| 2391 | with self.assertRaises(ValueError): |
| 2392 | multiprocessing.connection.Listener(r'\\.\test') |
| 2393 | |
Antoine Pitrou | 6d20cba | 2012-04-03 20:12:23 +0200 | [diff] [blame] | 2394 | @unittest.skipUnless(WIN32, "skipped on non-Windows platforms") |
| 2395 | def test_invalid_family_win32(self): |
| 2396 | with self.assertRaises(ValueError): |
| 2397 | multiprocessing.connection.Listener('/var/test.pipe') |
| 2398 | |
Richard Oudkerk | 4887b1c | 2012-07-27 14:06:11 +0100 | [diff] [blame] | 2399 | # |
| 2400 | # Test interaction with socket timeouts - see Issue #6056 |
| 2401 | # |
| 2402 | |
| 2403 | class TestTimeouts(unittest.TestCase): |
| 2404 | @classmethod |
| 2405 | def _test_timeout(cls, child, address): |
| 2406 | time.sleep(1) |
| 2407 | child.send(123) |
| 2408 | child.close() |
| 2409 | conn = multiprocessing.connection.Client(address) |
| 2410 | conn.send(456) |
| 2411 | conn.close() |
| 2412 | |
| 2413 | def test_timeout(self): |
| 2414 | old_timeout = socket.getdefaulttimeout() |
| 2415 | try: |
| 2416 | socket.setdefaulttimeout(0.1) |
| 2417 | parent, child = multiprocessing.Pipe(duplex=True) |
| 2418 | l = multiprocessing.connection.Listener(family='AF_INET') |
| 2419 | p = multiprocessing.Process(target=self._test_timeout, |
| 2420 | args=(child, l.address)) |
| 2421 | p.start() |
| 2422 | child.close() |
| 2423 | self.assertEqual(parent.recv(), 123) |
| 2424 | parent.close() |
| 2425 | conn = l.accept() |
| 2426 | self.assertEqual(conn.recv(), 456) |
| 2427 | conn.close() |
| 2428 | l.close() |
| 2429 | p.join(10) |
| 2430 | finally: |
| 2431 | socket.setdefaulttimeout(old_timeout) |
Antoine Pitrou | 6d20cba | 2012-04-03 20:12:23 +0200 | [diff] [blame] | 2432 | |
Richard Oudkerk | e88a244 | 2012-08-14 11:41:32 +0100 | [diff] [blame] | 2433 | # |
| 2434 | # Test what happens with no "if __name__ == '__main__'" |
| 2435 | # |
| 2436 | |
| 2437 | class TestNoForkBomb(unittest.TestCase): |
| 2438 | def test_noforkbomb(self): |
| 2439 | name = os.path.join(os.path.dirname(__file__), 'mp_fork_bomb.py') |
| 2440 | if WIN32: |
| 2441 | rc, out, err = test.script_helper.assert_python_failure(name) |
| 2442 | self.assertEqual('', out.decode('ascii')) |
| 2443 | self.assertIn('RuntimeError', err.decode('ascii')) |
| 2444 | else: |
| 2445 | rc, out, err = test.script_helper.assert_python_ok(name) |
| 2446 | self.assertEqual('123', out.decode('ascii').rstrip()) |
| 2447 | self.assertEqual('', err.decode('ascii')) |
| 2448 | |
| 2449 | # |
| 2450 | # |
| 2451 | # |
| 2452 | |
Alexandre Vassalotti | c57a84f | 2009-07-17 12:07:01 +0000 | [diff] [blame] | 2453 | testcases_other = [OtherTest, TestInvalidHandle, TestInitializers, |
Richard Oudkerk | 4887b1c | 2012-07-27 14:06:11 +0100 | [diff] [blame] | 2454 | TestStdinBadfiledescriptor, TestInvalidFamily, |
Richard Oudkerk | e88a244 | 2012-08-14 11:41:32 +0100 | [diff] [blame] | 2455 | TestTimeouts, TestNoForkBomb] |
Neal Norwitz | 5d6415e | 2008-08-25 01:53:32 +0000 | [diff] [blame] | 2456 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2457 | # |
| 2458 | # |
| 2459 | # |
| 2460 | |
| 2461 | def test_main(run=None): |
Jesse Noller | d00df3c | 2008-06-18 14:22:48 +0000 | [diff] [blame] | 2462 | if sys.platform.startswith("linux"): |
| 2463 | try: |
| 2464 | lock = multiprocessing.RLock() |
| 2465 | except OSError: |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 2466 | raise unittest.SkipTest("OSError raises on RLock creation, see issue 3111!") |
Benjamin Peterson | 3c0dd06 | 2008-06-17 22:43:48 +0000 | [diff] [blame] | 2467 | |
Charles-François Natali | 3be0095 | 2011-11-22 18:36:39 +0100 | [diff] [blame] | 2468 | check_enough_semaphores() |
| 2469 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2470 | if run is None: |
| 2471 | from test.support import run_unittest as run |
| 2472 | |
| 2473 | util.get_temp_dir() # creates temp directory for use by all processes |
| 2474 | |
| 2475 | multiprocessing.get_logger().setLevel(LOG_LEVEL) |
| 2476 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 2477 | ProcessesMixin.pool = multiprocessing.Pool(4) |
| 2478 | ThreadsMixin.pool = multiprocessing.dummy.Pool(4) |
| 2479 | ManagerMixin.manager.__init__() |
| 2480 | ManagerMixin.manager.start() |
| 2481 | ManagerMixin.pool = ManagerMixin.manager.Pool(4) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2482 | |
| 2483 | testcases = ( |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 2484 | sorted(testcases_processes.values(), key=lambda tc:tc.__name__) + |
| 2485 | sorted(testcases_threads.values(), key=lambda tc:tc.__name__) + |
Neal Norwitz | 5d6415e | 2008-08-25 01:53:32 +0000 | [diff] [blame] | 2486 | sorted(testcases_manager.values(), key=lambda tc:tc.__name__) + |
| 2487 | testcases_other |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2488 | ) |
| 2489 | |
| 2490 | loadTestsFromTestCase = unittest.defaultTestLoader.loadTestsFromTestCase |
| 2491 | suite = unittest.TestSuite(loadTestsFromTestCase(tc) for tc in testcases) |
| 2492 | run(suite) |
| 2493 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 2494 | ThreadsMixin.pool.terminate() |
| 2495 | ProcessesMixin.pool.terminate() |
| 2496 | ManagerMixin.pool.terminate() |
| 2497 | ManagerMixin.manager.shutdown() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2498 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 2499 | del ProcessesMixin.pool, ThreadsMixin.pool, ManagerMixin.pool |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 2500 | |
| 2501 | def main(): |
| 2502 | test_main(unittest.TextTestRunner(verbosity=2).run) |
| 2503 | |
| 2504 | if __name__ == '__main__': |
| 2505 | main() |