Debian Codegraph @

cpython27/Lib/test/test_multiprocessing.py

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