| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
# |
| 4 |
# Unit tests for the multiprocessing package |
| 5 |
# |
| 6 |
|
| 7 |
import unittest |
| 8 |
import Queue |
| 9 |
import time |
| 10 |
import sys |
| 11 |
import os |
| 12 |
import gc |
| 13 |
import array |
| 14 |
import random |
| 15 |
import logging |
| 16 |
from StringIO import StringIO |
| 17 |
|
| 18 |
import pytest |
| 19 |
from test import test_support |
| 20 |
|
| 21 |
try: |
| 22 |
from billiard._ext import _billiard |
| 23 |
except ImportError as exc: |
| 24 |
raise pytest.skip(exc) |
| 25 |
# import threading after _billiard to raise a more relevant error |
| 26 |
# message: "No module named _billiard". _billiard is not compiled |
| 27 |
# without thread support. |
| 28 |
import threading |
| 29 |
|
| 30 |
# Work around broken sem_open implementations |
| 31 |
try: |
| 32 |
import billiard.synchronize |
| 33 |
except ImportError as exc: |
| 34 |
raise pytest.skip(exc) |
| 35 |
|
| 36 |
import billiard.dummy |
| 37 |
import billiard.connection |
| 38 |
import billiard.managers |
| 39 |
import billiard.heap |
| 40 |
import billiard.pool |
| 41 |
|
| 42 |
from billiard import util |
| 43 |
from billiard.compat import bytes |
| 44 |
|
| 45 |
latin = str |
| 46 |
|
| 47 |
# Constants |
| 48 |
LOG_LEVEL = util.SUBWARNING |
| 49 |
|
| 50 |
DELTA = 0.1 |
| 51 |
|
| 52 |
# making true makes tests take a lot longer |
| 53 |
# and can sometimes cause some non-serious |
| 54 |
# failures because some calls block a bit |
| 55 |
# longer than expected |
| 56 |
CHECK_TIMINGS = False |
| 57 |
|
| 58 |
if CHECK_TIMINGS: |
| 59 |
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4 |
| 60 |
else: |
| 61 |
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1 |
| 62 |
|
| 63 |
HAVE_GETVALUE = not getattr(_billiard, |
| 64 |
'HAVE_BROKEN_SEM_GETVALUE', False) |
| 65 |
|
| 66 |
WIN32 = (sys.platform == "win32") |
| 67 |
|
| 68 |
# Some tests require ctypes |
| 69 |
try: |
| 70 |
from ctypes import Structure, c_int, c_double |
| 71 |
except ImportError: |
| 72 |
Structure = object |
| 73 |
c_int = c_double = None |
| 74 |
|
| 75 |
try: |
| 76 |
from ctypes import Value |
| 77 |
except ImportError: |
| 78 |
Value = None |
| 79 |
|
| 80 |
try: |
| 81 |
from ctypes import copy as ctypes_copy |
| 82 |
except ImportError: |
| 83 |
ctypes_copy = None |
| 84 |
|
| 85 |
|
| 86 |
class TimingWrapper: |
| 87 |
"""Creates a wrapper for a function which records the |
| 88 |
time it takes to finish""" |
| 89 |
|
| 90 |
def __init__(self, func): |
| 91 |
self.func = func |
| 92 |
self.elapsed = None |
| 93 |
|
| 94 |
def __call__(self, *args, **kwds): |
| 95 |
t = time.time() |
| 96 |
try: |
| 97 |
return self.func(*args, **kwds) |
| 98 |
finally: |
| 99 |
self.elapsed = time.time() - t |
| 100 |
|
| 101 |
|
| 102 |
class BaseTestCase: |
| 103 |
"""Base class for test cases""" |
| 104 |
ALLOWED_TYPES = ('processes', 'manager', 'threads') |
| 105 |
|
| 106 |
def assertTimingAlmostEqual(self, a, b): |
| 107 |
if CHECK_TIMINGS: |
| 108 |
self.assertAlmostEqual(a, b, 1) |
| 109 |
|
| 110 |
def assertReturnsIfImplemented(self, value, func, *args): |
| 111 |
try: |
| 112 |
res = func(*args) |
| 113 |
except NotImplementedError: |
| 114 |
pass |
| 115 |
else: |
| 116 |
return self.assertEqual(value, res) |
| 117 |
|
| 118 |
|
| 119 |
def get_value(self): |
| 120 |
"""Return the value of a semaphore""" |
| 121 |
try: |
| 122 |
return self.get_value() |
| 123 |
except AttributeError: |
| 124 |
try: |
| 125 |
return self._Semaphore__value |
| 126 |
except AttributeError: |
| 127 |
try: |
| 128 |
return self._value |
| 129 |
except AttributeError: |
| 130 |
raise NotImplementedError |
| 131 |
|
| 132 |
|
| 133 |
class _TestProcesses(BaseTestCase): |
| 134 |
|
| 135 |
ALLOWED_TYPES = ('processes', 'threads') |
| 136 |
|
| 137 |
def test_current(self): |
| 138 |
if self.TYPE == 'threads': |
| 139 |
return |
| 140 |
|
| 141 |
current = self.current_process() |
| 142 |
authkey = current.authkey |
| 143 |
|
| 144 |
self.assertTrue(current.is_alive()) |
| 145 |
self.assertTrue(not current.daemon) |
| 146 |
self.assertIsInstance(authkey, bytes) |
| 147 |
self.assertTrue(len(authkey) > 0) |
| 148 |
self.assertEqual(current.ident, os.getpid()) |
| 149 |
self.assertEqual(current.exitcode, None) |
| 150 |
|
| 151 |
def _test(self, q, *args, **kwds): |
| 152 |
current = self.current_process() |
| 153 |
q.put(args) |
| 154 |
q.put(kwds) |
| 155 |
q.put(current.name) |
| 156 |
if self.TYPE != 'threads': |
| 157 |
q.put(bytes(current.authkey, 'ascii')) |
| 158 |
q.put(current.pid) |
| 159 |
|
| 160 |
def test_process(self): |
| 161 |
q = self.Queue(1) |
| 162 |
e = self.Event() # noqa |
| 163 |
args = (q, 1, 2) |
| 164 |
kwargs = {'hello': 23, 'bye': 2.54} |
| 165 |
name = 'SomeProcess' |
| 166 |
p = self.Process( |
| 167 |
target=self._test, args=args, kwargs=kwargs, name=name |
| 168 |
) |
| 169 |
p.daemon = True |
| 170 |
current = self.current_process() |
| 171 |
|
| 172 |
if self.TYPE != 'threads': |
| 173 |
self.assertEqual(p.authkey, current.authkey) |
| 174 |
self.assertEqual(p.is_alive(), False) |
| 175 |
self.assertEqual(p.daemon, True) |
| 176 |
self.assertNotIn(p, self.active_children()) |
| 177 |
self.assertTrue(type(self.active_children()) is list) |
| 178 |
self.assertEqual(p.exitcode, None) |
| 179 |
|
| 180 |
p.start() |
| 181 |
|
| 182 |
self.assertEqual(p.exitcode, None) |
| 183 |
self.assertEqual(p.is_alive(), True) |
| 184 |
self.assertIn(p, self.active_children()) |
| 185 |
|
| 186 |
self.assertEqual(q.get(), args[1:]) |
| 187 |
self.assertEqual(q.get(), kwargs) |
| 188 |
self.assertEqual(q.get(), p.name) |
| 189 |
if self.TYPE != 'threads': |
| 190 |
self.assertEqual(q.get(), current.authkey) |
| 191 |
self.assertEqual(q.get(), p.pid) |
| 192 |
|
| 193 |
p.join() |
| 194 |
|
| 195 |
self.assertEqual(p.exitcode, 0) |
| 196 |
self.assertEqual(p.is_alive(), False) |
| 197 |
self.assertNotIn(p, self.active_children()) |
| 198 |
|
| 199 |
def _test_terminate(self): |
| 200 |
time.sleep(1000) |
| 201 |
|
| 202 |
def test_terminate(self): |
| 203 |
if self.TYPE == 'threads': |
| 204 |
return |
| 205 |
|
| 206 |
p = self.Process(target=self._test_terminate) |
| 207 |
p.daemon = True |
| 208 |
p.start() |
| 209 |
|
| 210 |
self.assertEqual(p.is_alive(), True) |
| 211 |
self.assertIn(p, self.active_children()) |
| 212 |
self.assertEqual(p.exitcode, None) |
| 213 |
|
| 214 |
p.terminate() |
| 215 |
|
| 216 |
join = TimingWrapper(p.join) |
| 217 |
self.assertEqual(join(), None) |
| 218 |
self.assertTimingAlmostEqual(join.elapsed, 0.0) |
| 219 |
|
| 220 |
self.assertEqual(p.is_alive(), False) |
| 221 |
self.assertNotIn(p, self.active_children()) |
| 222 |
|
| 223 |
p.join() |
| 224 |
|
| 225 |
# XXX sometimes get p.exitcode == 0 on Windows ... |
| 226 |
# self.assertEqual(p.exitcode, -signal.SIGTERM) |
| 227 |
|
| 228 |
def test_cpu_count(self): |
| 229 |
try: |
| 230 |
cpus = billiard.cpu_count() |
| 231 |
except NotImplementedError: |
| 232 |
cpus = 1 |
| 233 |
self.assertTrue(type(cpus) is int) |
| 234 |
self.assertTrue(cpus >= 1) |
| 235 |
|
| 236 |
def test_active_children(self): |
| 237 |
self.assertEqual(type(self.active_children()), list) |
| 238 |
|
| 239 |
p = self.Process(target=time.sleep, args=(DELTA,)) |
| 240 |
self.assertNotIn(p, self.active_children()) |
| 241 |
|
| 242 |
p.start() |
| 243 |
self.assertIn(p, self.active_children()) |
| 244 |
|
| 245 |
p.join() |
| 246 |
self.assertNotIn(p, self.active_children()) |
| 247 |
|
| 248 |
def _test_recursion(self, wconn, id): |
| 249 |
__import__('billiard.forking') |
| 250 |
wconn.send(id) |
| 251 |
if len(id) < 2: |
| 252 |
for i in range(2): |
| 253 |
p = self.Process( |
| 254 |
target=self._test_recursion, args=(wconn, id + [i]) |
| 255 |
) |
| 256 |
p.start() |
| 257 |
p.join() |
| 258 |
|
| 259 |
def test_recursion(self): |
| 260 |
rconn, wconn = self.Pipe(duplex=False) |
| 261 |
self._test_recursion(wconn, []) |
| 262 |
|
| 263 |
time.sleep(DELTA) |
| 264 |
result = [] |
| 265 |
while rconn.poll(): |
| 266 |
result.append(rconn.recv()) |
| 267 |
|
| 268 |
expected = [ |
| 269 |
[], |
| 270 |
[0], |
| 271 |
[0, 0], |
| 272 |
[0, 1], |
| 273 |
[1], |
| 274 |
[1, 0], |
| 275 |
[1, 1] |
| 276 |
] |
| 277 |
self.assertEqual(result, expected) |
| 278 |
|
| 279 |
|
| 280 |
class _UpperCaser(billiard.Process): |
| 281 |
|
| 282 |
def __init__(self): |
| 283 |
billiard.Process.__init__(self) |
| 284 |
self.child_conn, self.parent_conn = billiard.Pipe() |
| 285 |
|
| 286 |
def run(self): |
| 287 |
self.parent_conn.close() |
| 288 |
for s in iter(self.child_conn.recv, None): |
| 289 |
self.child_conn.send(s.upper()) |
| 290 |
self.child_conn.close() |
| 291 |
|
| 292 |
def submit(self, s): |
| 293 |
assert type(s) is str |
| 294 |
self.parent_conn.send(s) |
| 295 |
return self.parent_conn.recv() |
| 296 |
|
| 297 |
def stop(self): |
| 298 |
self.parent_conn.send(None) |
| 299 |
self.parent_conn.close() |
| 300 |
self.child_conn.close() |
| 301 |
|
| 302 |
|
| 303 |
class _TestSubclassingProcess(BaseTestCase): |
| 304 |
|
| 305 |
ALLOWED_TYPES = ('processes',) |
| 306 |
|
| 307 |
def test_subclassing(self): |
| 308 |
uppercaser = _UpperCaser() |
| 309 |
uppercaser.start() |
| 310 |
self.assertEqual(uppercaser.submit('hello'), 'HELLO') |
| 311 |
self.assertEqual(uppercaser.submit('world'), 'WORLD') |
| 312 |
uppercaser.stop() |
| 313 |
uppercaser.join() |
| 314 |
|
| 315 |
|
| 316 |
def queue_empty(q): |
| 317 |
if hasattr(q, 'empty'): |
| 318 |
return q.empty() |
| 319 |
else: |
| 320 |
return q.qsize() == 0 |
| 321 |
|
| 322 |
|
| 323 |
def queue_full(q, maxsize): |
| 324 |
if hasattr(q, 'full'): |
| 325 |
return q.full() |
| 326 |
else: |
| 327 |
return q.qsize() == maxsize |
| 328 |
|
| 329 |
|
| 330 |
class _TestQueue(BaseTestCase): |
| 331 |
|
| 332 |
def _test_put(self, queue, child_can_start, parent_can_continue): |
| 333 |
child_can_start.wait() |
| 334 |
for i in range(6): |
| 335 |
queue.get() |
| 336 |
parent_can_continue.set() |
| 337 |
|
| 338 |
def test_put(self): |
| 339 |
MAXSIZE = 6 |
| 340 |
queue = self.Queue(maxsize=MAXSIZE) |
| 341 |
child_can_start = self.Event() |
| 342 |
parent_can_continue = self.Event() |
| 343 |
|
| 344 |
proc = self.Process( |
| 345 |
target=self._test_put, |
| 346 |
args=(queue, child_can_start, parent_can_continue) |
| 347 |
) |
| 348 |
proc.daemon = True |
| 349 |
proc.start() |
| 350 |
|
| 351 |
self.assertEqual(queue_empty(queue), True) |
| 352 |
self.assertEqual(queue_full(queue, MAXSIZE), False) |
| 353 |
|
| 354 |
queue.put(1) |
| 355 |
queue.put(2, True) |
| 356 |
queue.put(3, True, None) |
| 357 |
queue.put(4, False) |
| 358 |
queue.put(5, False, None) |
| 359 |
queue.put_nowait(6) |
| 360 |
|
| 361 |
# the values may be in buffer but not yet in pipe so sleep a bit |
| 362 |
time.sleep(DELTA) |
| 363 |
|
| 364 |
self.assertEqual(queue_empty(queue), False) |
| 365 |
self.assertEqual(queue_full(queue, MAXSIZE), True) |
| 366 |
|
| 367 |
put = TimingWrapper(queue.put) |
| 368 |
put_nowait = TimingWrapper(queue.put_nowait) |
| 369 |
|
| 370 |
self.assertRaises(Queue.Full, put, 7, False) |
| 371 |
self.assertTimingAlmostEqual(put.elapsed, 0) |
| 372 |
|
| 373 |
self.assertRaises(Queue.Full, put, 7, False, None) |
| 374 |
self.assertTimingAlmostEqual(put.elapsed, 0) |
| 375 |
|
| 376 |
self.assertRaises(Queue.Full, put_nowait, 7) |
| 377 |
self.assertTimingAlmostEqual(put_nowait.elapsed, 0) |
| 378 |
|
| 379 |
self.assertRaises(Queue.Full, put, 7, True, TIMEOUT1) |
| 380 |
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT1) |
| 381 |
|
| 382 |
self.assertRaises(Queue.Full, put, 7, False, TIMEOUT2) |
| 383 |
self.assertTimingAlmostEqual(put.elapsed, 0) |
| 384 |
|
| 385 |
self.assertRaises(Queue.Full, put, 7, True, timeout=TIMEOUT3) |
| 386 |
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT3) |
| 387 |
|
| 388 |
child_can_start.set() |
| 389 |
parent_can_continue.wait() |
| 390 |
|
| 391 |
self.assertEqual(queue_empty(queue), True) |
| 392 |
self.assertEqual(queue_full(queue, MAXSIZE), False) |
| 393 |
|
| 394 |
proc.join() |
| 395 |
|
| 396 |
def _test_get(self, queue, child_can_start, parent_can_continue): |
| 397 |
child_can_start.wait() |
| 398 |
queue.put(2) |
| 399 |
queue.put(3) |
| 400 |
queue.put(4) |
| 401 |
queue.put(5) |
| 402 |
parent_can_continue.set() |
| 403 |
|
| 404 |
def test_get(self): |
| 405 |
queue = self.Queue() |
| 406 |
child_can_start = self.Event() |
| 407 |
parent_can_continue = self.Event() |
| 408 |
|
| 409 |
proc = self.Process( |
| 410 |
target=self._test_get, |
| 411 |
args=(queue, child_can_start, parent_can_continue) |
| 412 |
) |
| 413 |
proc.daemon = True |
| 414 |
proc.start() |
| 415 |
|
| 416 |
self.assertEqual(queue_empty(queue), True) |
| 417 |
|
| 418 |
child_can_start.set() |
| 419 |
parent_can_continue.wait() |
| 420 |
|
| 421 |
time.sleep(DELTA) |
| 422 |
self.assertEqual(queue_empty(queue), False) |
| 423 |
|
| 424 |
# ## Hangs unexpectedly, remove for now |
| 425 |
# self.assertEqual(queue.get(), 1) |
| 426 |
self.assertEqual(queue.get(True, None), 2) |
| 427 |
self.assertEqual(queue.get(True), 3) |
| 428 |
self.assertEqual(queue.get(timeout=1), 4) |
| 429 |
self.assertEqual(queue.get_nowait(), 5) |
| 430 |
|
| 431 |
self.assertEqual(queue_empty(queue), True) |
| 432 |
|
| 433 |
get = TimingWrapper(queue.get) |
| 434 |
get_nowait = TimingWrapper(queue.get_nowait) |
| 435 |
|
| 436 |
self.assertRaises(Queue.Empty, get, False) |
| 437 |
self.assertTimingAlmostEqual(get.elapsed, 0) |
| 438 |
|
| 439 |
self.assertRaises(Queue.Empty, get, False, None) |
| 440 |
self.assertTimingAlmostEqual(get.elapsed, 0) |
| 441 |
|
| 442 |
self.assertRaises(Queue.Empty, get_nowait) |
| 443 |
self.assertTimingAlmostEqual(get_nowait.elapsed, 0) |
| 444 |
|
| 445 |
self.assertRaises(Queue.Empty, get, True, TIMEOUT1) |
| 446 |
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) |
| 447 |
|
| 448 |
self.assertRaises(Queue.Empty, get, False, TIMEOUT2) |
| 449 |
self.assertTimingAlmostEqual(get.elapsed, 0) |
| 450 |
|
| 451 |
self.assertRaises(Queue.Empty, get, timeout=TIMEOUT3) |
| 452 |
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT3) |
| 453 |
|
| 454 |
proc.join() |
| 455 |
|
| 456 |
def _test_fork(self, queue): |
| 457 |
for i in range(10, 20): |
| 458 |
queue.put(i) |
| 459 |
# note that at this point the items may only be buffered, so the |
| 460 |
# process cannot shutdown until the feeder thread has finished |
| 461 |
# pushing items onto the pipe. |
| 462 |
|
| 463 |
def test_fork(self): |
| 464 |
# Old versions of Queue would fail to create a new feeder |
| 465 |
# thread for a forked process if the original process had its |
| 466 |
# own feeder thread. This test checks that this no longer |
| 467 |
# happens. |
| 468 |
|
| 469 |
queue = self.Queue() |
| 470 |
|
| 471 |
# put items on queue so that main process starts a feeder thread |
| 472 |
for i in range(10): |
| 473 |
queue.put(i) |
| 474 |
|
| 475 |
# wait to make sure thread starts before we fork a new process |
| 476 |
time.sleep(DELTA) |
| 477 |
|
| 478 |
# fork process |
| 479 |
p = self.Process(target=self._test_fork, args=(queue,)) |
| 480 |
p.start() |
| 481 |
|
| 482 |
# check that all expected items are in the queue |
| 483 |
for i in range(20): |
| 484 |
self.assertEqual(queue.get(), i) |
| 485 |
self.assertRaises(Queue.Empty, queue.get, False) |
| 486 |
|
| 487 |
p.join() |
| 488 |
|
| 489 |
def test_qsize(self): |
| 490 |
q = self.Queue() |
| 491 |
try: |
| 492 |
self.assertEqual(q.qsize(), 0) |
| 493 |
except NotImplementedError: |
| 494 |
return |
| 495 |
q.put(1) |
| 496 |
self.assertEqual(q.qsize(), 1) |
| 497 |
q.put(5) |
| 498 |
self.assertEqual(q.qsize(), 2) |
| 499 |
q.get() |
| 500 |
self.assertEqual(q.qsize(), 1) |
| 501 |
q.get() |
| 502 |
self.assertEqual(q.qsize(), 0) |
| 503 |
|
| 504 |
def _test_task_done(self, q): |
| 505 |
for obj in iter(q.get, None): |
| 506 |
time.sleep(DELTA) |
| 507 |
q.task_done() |
| 508 |
|
| 509 |
def test_task_done(self): |
| 510 |
queue = self.JoinableQueue() |
| 511 |
|
| 512 |
if sys.version_info < (2, 5) and not hasattr(queue, 'task_done'): |
| 513 |
pytest.skip("requires 'queue.task_done()' method") |
| 514 |
|
| 515 |
workers = [self.Process(target=self._test_task_done, args=(queue,)) |
| 516 |
for i in xrange(4)] |
| 517 |
|
| 518 |
for p in workers: |
| 519 |
p.start() |
| 520 |
|
| 521 |
for i in xrange(10): |
| 522 |
queue.put(i) |
| 523 |
|
| 524 |
queue.join() |
| 525 |
|
| 526 |
for p in workers: |
| 527 |
queue.put(None) |
| 528 |
|
| 529 |
for p in workers: |
| 530 |
p.join() |
| 531 |
|
| 532 |
|
| 533 |
class _TestLock(BaseTestCase): |
| 534 |
|
| 535 |
def test_lock(self): |
| 536 |
lock = self.Lock() |
| 537 |
self.assertEqual(lock.acquire(), True) |
| 538 |
self.assertEqual(lock.acquire(False), False) |
| 539 |
self.assertEqual(lock.release(), None) |
| 540 |
self.assertRaises((ValueError, threading.ThreadError), lock.release) |
| 541 |
|
| 542 |
def test_rlock(self): |
| 543 |
lock = self.RLock() |
| 544 |
self.assertEqual(lock.acquire(), True) |
| 545 |
self.assertEqual(lock.acquire(), True) |
| 546 |
self.assertEqual(lock.acquire(), True) |
| 547 |
self.assertEqual(lock.release(), None) |
| 548 |
self.assertEqual(lock.release(), None) |
| 549 |
self.assertEqual(lock.release(), None) |
| 550 |
self.assertRaises((AssertionError, RuntimeError), lock.release) |
| 551 |
|
| 552 |
def test_lock_context(self): |
| 553 |
with self.Lock(): |
| 554 |
pass |
| 555 |
|
| 556 |
|
| 557 |
class _TestSemaphore(BaseTestCase): |
| 558 |
|
| 559 |
def _test_semaphore(self, sem): |
| 560 |
self.assertReturnsIfImplemented(2, get_value, sem) |
| 561 |
self.assertEqual(sem.acquire(), True) |
| 562 |
self.assertReturnsIfImplemented(1, get_value, sem) |
| 563 |
self.assertEqual(sem.acquire(), True) |
| 564 |
self.assertReturnsIfImplemented(0, get_value, sem) |
| 565 |
self.assertEqual(sem.acquire(False), False) |
| 566 |
self.assertReturnsIfImplemented(0, get_value, sem) |
| 567 |
self.assertEqual(sem.release(), None) |
| 568 |
self.assertReturnsIfImplemented(1, get_value, sem) |
| 569 |
self.assertEqual(sem.release(), None) |
| 570 |
self.assertReturnsIfImplemented(2, get_value, sem) |
| 571 |
|
| 572 |
def test_semaphore(self): |
| 573 |
sem = self.Semaphore(2) |
| 574 |
self._test_semaphore(sem) |
| 575 |
self.assertEqual(sem.release(), None) |
| 576 |
self.assertReturnsIfImplemented(3, get_value, sem) |
| 577 |
self.assertEqual(sem.release(), None) |
| 578 |
self.assertReturnsIfImplemented(4, get_value, sem) |
| 579 |
|
| 580 |
def test_bounded_semaphore(self): |
| 581 |
sem = self.BoundedSemaphore(2) |
| 582 |
self._test_semaphore(sem) |
| 583 |
# ## Currently fails on OS/X |
| 584 |
# if HAVE_GETVALUE: |
| 585 |
# self.assertRaises(ValueError, sem.release) |
| 586 |
# self.assertReturnsIfImplemented(2, get_value, sem) |
| 587 |
|
| 588 |
def test_timeout(self): |
| 589 |
if self.TYPE != 'processes': |
| 590 |
return |
| 591 |
|
| 592 |
sem = self.Semaphore(0) |
| 593 |
acquire = TimingWrapper(sem.acquire) |
| 594 |
|
| 595 |
self.assertEqual(acquire(False), False) |
| 596 |
self.assertTimingAlmostEqual(acquire.elapsed, 0.0) |
| 597 |
|
| 598 |
self.assertEqual(acquire(False, None), False) |
| 599 |
self.assertTimingAlmostEqual(acquire.elapsed, 0.0) |
| 600 |
|
| 601 |
self.assertEqual(acquire(False, TIMEOUT1), False) |
| 602 |
self.assertTimingAlmostEqual(acquire.elapsed, 0) |
| 603 |
|
| 604 |
self.assertEqual(acquire(True, TIMEOUT2), False) |
| 605 |
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT2) |
| 606 |
|
| 607 |
self.assertEqual(acquire(timeout=TIMEOUT3), False) |
| 608 |
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT3) |
| 609 |
|
| 610 |
|
| 611 |
class _TestCondition(BaseTestCase): |
| 612 |
|
| 613 |
def f(self, cond, sleeping, woken, timeout=None): |
| 614 |
cond.acquire() |
| 615 |
sleeping.release() |
| 616 |
cond.wait(timeout) |
| 617 |
woken.release() |
| 618 |
cond.release() |
| 619 |
|
| 620 |
def check_invariant(self, cond): |
| 621 |
# this is only supposed to succeed when there are no sleepers |
| 622 |
if self.TYPE == 'processes': |
| 623 |
try: |
| 624 |
sleepers = (cond._sleeping_count.get_value() - |
| 625 |
cond._woken_count.get_value()) |
| 626 |
self.assertEqual(sleepers, 0) |
| 627 |
self.assertEqual(cond._wait_semaphore.get_value(), 0) |
| 628 |
except NotImplementedError: |
| 629 |
pass |
| 630 |
|
| 631 |
def test_notify(self): |
| 632 |
cond = self.Condition() |
| 633 |
sleeping = self.Semaphore(0) |
| 634 |
woken = self.Semaphore(0) |
| 635 |
|
| 636 |
p = self.Process(target=self.f, args=(cond, sleeping, woken)) |
| 637 |
p.daemon = True |
| 638 |
p.start() |
| 639 |
|
| 640 |
p = threading.Thread(target=self.f, args=(cond, sleeping, woken)) |
| 641 |
p.daemon = True |
| 642 |
p.start() |
| 643 |
|
| 644 |
# wait for both children to start sleeping |
| 645 |
sleeping.acquire() |
| 646 |
sleeping.acquire() |
| 647 |
|
| 648 |
# check no process/thread has woken up |
| 649 |
time.sleep(DELTA) |
| 650 |
self.assertReturnsIfImplemented(0, get_value, woken) |
| 651 |
|
| 652 |
# wake up one process/thread |
| 653 |
cond.acquire() |
| 654 |
cond.notify() |
| 655 |
cond.release() |
| 656 |
|
| 657 |
# check one process/thread has woken up |
| 658 |
time.sleep(DELTA) |
| 659 |
self.assertReturnsIfImplemented(1, get_value, woken) |
| 660 |
|
| 661 |
# wake up another |
| 662 |
cond.acquire() |
| 663 |
cond.notify() |
| 664 |
cond.release() |
| 665 |
|
| 666 |
# check other has woken up |
| 667 |
time.sleep(DELTA) |
| 668 |
self.assertReturnsIfImplemented(2, get_value, woken) |
| 669 |
|
| 670 |
# check state is not mucked up |
| 671 |
self.check_invariant(cond) |
| 672 |
p.join() |
| 673 |
|
| 674 |
def test_notify_all(self): |
| 675 |
cond = self.Condition() |
| 676 |
sleeping = self.Semaphore(0) |
| 677 |
woken = self.Semaphore(0) |
| 678 |
|
| 679 |
# start some threads/processes which will timeout |
| 680 |
for i in range(3): |
| 681 |
p = self.Process(target=self.f, |
| 682 |
args=(cond, sleeping, woken, TIMEOUT1)) |
| 683 |
p.daemon = True |
| 684 |
p.start() |
| 685 |
|
| 686 |
t = threading.Thread(target=self.f, |
| 687 |
args=(cond, sleeping, woken, TIMEOUT1)) |
| 688 |
t.daemon = True |
| 689 |
t.start() |
| 690 |
|
| 691 |
# wait for them all to sleep |
| 692 |
for i in xrange(6): |
| 693 |
sleeping.acquire() |
| 694 |
|
| 695 |
# check they have all timed out |
| 696 |
for i in xrange(6): |
| 697 |
woken.acquire() |
| 698 |
self.assertReturnsIfImplemented(0, get_value, woken) |
| 699 |
|
| 700 |
# check state is not mucked up |
| 701 |
self.check_invariant(cond) |
| 702 |
|
| 703 |
# start some more threads/processes |
| 704 |
for i in range(3): |
| 705 |
p = self.Process(target=self.f, args=(cond, sleeping, woken)) |
| 706 |
p.daemon = True |
| 707 |
p.start() |
| 708 |
|
| 709 |
t = threading.Thread(target=self.f, args=(cond, sleeping, woken)) |
| 710 |
t.daemon = True |
| 711 |
t.start() |
| 712 |
|
| 713 |
# wait for them to all sleep |
| 714 |
for i in xrange(6): |
| 715 |
sleeping.acquire() |
| 716 |
|
| 717 |
# check no process/thread has woken up |
| 718 |
time.sleep(DELTA) |
| 719 |
self.assertReturnsIfImplemented(0, get_value, woken) |
| 720 |
|
| 721 |
# wake them all up |
| 722 |
cond.acquire() |
| 723 |
cond.notify_all() |
| 724 |
cond.release() |
| 725 |
|
| 726 |
# check they have all woken |
| 727 |
time.sleep(DELTA) |
| 728 |
self.assertReturnsIfImplemented(6, get_value, woken) |
| 729 |
|
| 730 |
# check state is not mucked up |
| 731 |
self.check_invariant(cond) |
| 732 |
|
| 733 |
def test_timeout(self): |
| 734 |
cond = self.Condition() |
| 735 |
wait = TimingWrapper(cond.wait) |
| 736 |
cond.acquire() |
| 737 |
res = wait(TIMEOUT1) |
| 738 |
cond.release() |
| 739 |
self.assertEqual(res, None) |
| 740 |
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1) |
| 741 |
|
| 742 |
|
| 743 |
class _TestEvent(BaseTestCase): |
| 744 |
|
| 745 |
def _test_event(self, event): |
| 746 |
time.sleep(TIMEOUT2) |
| 747 |
event.set() |
| 748 |
|
| 749 |
def test_event(self): |
| 750 |
event = self.Event() |
| 751 |
wait = TimingWrapper(event.wait) |
| 752 |
|
| 753 |
# Removed temporarily, due to API shear, this does not |
| 754 |
# work with threading._Event objects. is_set == isSet |
| 755 |
self.assertEqual(event.is_set(), False) |
| 756 |
|
| 757 |
# Removed, threading.Event.wait() will return the value of the __flag |
| 758 |
# instead of None. API Shear with the semaphore backed mp.Event |
| 759 |
self.assertEqual(wait(0.0), False) |
| 760 |
self.assertTimingAlmostEqual(wait.elapsed, 0.0) |
| 761 |
self.assertEqual(wait(TIMEOUT1), False) |
| 762 |
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1) |
| 763 |
|
| 764 |
event.set() |
| 765 |
|
| 766 |
# See note above on the API differences |
| 767 |
self.assertEqual(event.is_set(), True) |
| 768 |
self.assertEqual(wait(), True) |
| 769 |
self.assertTimingAlmostEqual(wait.elapsed, 0.0) |
| 770 |
self.assertEqual(wait(TIMEOUT1), True) |
| 771 |
self.assertTimingAlmostEqual(wait.elapsed, 0.0) |
| 772 |
# self.assertEqual(event.is_set(), True) |
| 773 |
|
| 774 |
event.clear() |
| 775 |
|
| 776 |
# self.assertEqual(event.is_set(), False) |
| 777 |
|
| 778 |
self.Process(target=self._test_event, args=(event,)).start() |
| 779 |
self.assertEqual(wait(), True) |
| 780 |
|
| 781 |
|
| 782 |
class _TestValue(BaseTestCase): |
| 783 |
|
| 784 |
ALLOWED_TYPES = ('processes',) |
| 785 |
|
| 786 |
codes_values = [ |
| 787 |
('i', 4343, 24234), |
| 788 |
('d', 3.625, -4.25), |
| 789 |
('h', -232, 234), |
| 790 |
('c', latin('x'), latin('y')) |
| 791 |
] |
| 792 |
|
| 793 |
def _test(self, values): |
| 794 |
for sv, cv in zip(values, self.codes_values): |
| 795 |
sv.value = cv[2] |
| 796 |
|
| 797 |
@unittest.skipIf(c_int is None, "requires _ctypes") |
| 798 |
def test_value(self, raw=False): |
| 799 |
if raw: |
| 800 |
values = [self.RawValue(code, value) |
| 801 |
for code, value, _ in self.codes_values] |
| 802 |
else: |
| 803 |
values = [self.Value(code, value) |
| 804 |
for code, value, _ in self.codes_values] |
| 805 |
|
| 806 |
for sv, cv in zip(values, self.codes_values): |
| 807 |
self.assertEqual(sv.value, cv[1]) |
| 808 |
|
| 809 |
proc = self.Process(target=self._test, args=(values,)) |
| 810 |
proc.start() |
| 811 |
proc.join() |
| 812 |
|
| 813 |
for sv, cv in zip(values, self.codes_values): |
| 814 |
self.assertEqual(sv.value, cv[2]) |
| 815 |
|
| 816 |
@unittest.skipIf(c_int is None, "requires _ctypes") |
| 817 |
def test_rawvalue(self): |
| 818 |
self.test_value(raw=True) |
| 819 |
|
| 820 |
@unittest.skipIf(c_int is None, "requires _ctypes") |
| 821 |
def test_getobj_getlock(self): |
| 822 |
val1 = self.Value('i', 5) |
| 823 |
lock1 = val1.get_lock() # noqa |
| 824 |
obj1 = val1.get_obj() # noqa |
| 825 |
|
| 826 |
val2 = self.Value('i', 5, lock=None) |
| 827 |
lock2 = val2.get_lock() # noqa |
| 828 |
obj2 = val2.get_obj() # noqa |
| 829 |
|
| 830 |
lock = self.Lock() |
| 831 |
val3 = self.Value('i', 5, lock=lock) |
| 832 |
lock3 = val3.get_lock() # noqa |
| 833 |
obj3 = val3.get_obj() # noqa |
| 834 |
self.assertEqual(lock, lock3) |
| 835 |
|
| 836 |
arr4 = self.Value('i', 5, lock=False) |
| 837 |
self.assertFalse(hasattr(arr4, 'get_lock')) |
| 838 |
self.assertFalse(hasattr(arr4, 'get_obj')) |
| 839 |
|
| 840 |
self.assertRaises(AttributeError, self.Value, 'i', 5, lock='navalue') |
| 841 |
|
| 842 |
arr5 = self.RawValue('i', 5) |
| 843 |
self.assertFalse(hasattr(arr5, 'get_lock')) |
| 844 |
self.assertFalse(hasattr(arr5, 'get_obj')) |
| 845 |
|
| 846 |
|
| 847 |
class _TestArray(BaseTestCase): |
| 848 |
|
| 849 |
ALLOWED_TYPES = ('processes',) |
| 850 |
|
| 851 |
def f(self, seq): |
| 852 |
for i in range(1, len(seq)): |
| 853 |
seq[i] += seq[i - 1] |
| 854 |
|
| 855 |
@unittest.skipIf(c_int is None, "requires _ctypes") |
| 856 |
def test_array(self, raw=False): |
| 857 |
seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831] |
| 858 |
if raw: |
| 859 |
arr = self.RawArray('i', seq) |
| 860 |
else: |
| 861 |
arr = self.Array('i', seq) |
| 862 |
|
| 863 |
self.assertEqual(len(arr), len(seq)) |
| 864 |
self.assertEqual(arr[3], seq[3]) |
| 865 |
self.assertEqual(list(arr[2:7]), list(seq[2:7])) |
| 866 |
|
| 867 |
arr[4:8] = seq[4:8] = array.array('i', [1, 2, 3, 4]) |
| 868 |
|
| 869 |
self.assertEqual(list(arr[:]), seq) |
| 870 |
|
| 871 |
self.f(seq) |
| 872 |
|
| 873 |
p = self.Process(target=self.f, args=(arr,)) |
| 874 |
p.start() |
| 875 |
p.join() |
| 876 |
|
| 877 |
self.assertEqual(list(arr[:]), seq) |
| 878 |
|
| 879 |
@unittest.skipIf(c_int is None, "requires _ctypes") |
| 880 |
def test_rawarray(self): |
| 881 |
self.test_array(raw=True) |
| 882 |
|
| 883 |
@unittest.skipIf(c_int is None, "requires _ctypes") |
| 884 |
def test_getobj_getlock_obj(self): |
| 885 |
arr1 = self.Array('i', range(10)) |
| 886 |
lock1 = arr1.get_lock() # noqa |
| 887 |
obj1 = arr1.get_obj() # noqa |
| 888 |
|
| 889 |
arr2 = self.Array('i', range(10), lock=None) |
| 890 |
lock2 = arr2.get_lock() # noqa |
| 891 |
obj2 = arr2.get_obj() # noqa |
| 892 |
|
| 893 |
lock = self.Lock() |
| 894 |
arr3 = self.Array('i', range(10), lock=lock) |
| 895 |
lock3 = arr3.get_lock() |
| 896 |
obj3 = arr3.get_obj() # noqa |
| 897 |
self.assertEqual(lock, lock3) |
| 898 |
|
| 899 |
arr4 = self.Array('i', range(10), lock=False) |
| 900 |
self.assertFalse(hasattr(arr4, 'get_lock')) |
| 901 |
self.assertFalse(hasattr(arr4, 'get_obj')) |
| 902 |
self.assertRaises(AttributeError, |
| 903 |
self.Array, 'i', range(10), lock='notalock') |
| 904 |
|
| 905 |
arr5 = self.RawArray('i', range(10)) |
| 906 |
self.assertFalse(hasattr(arr5, 'get_lock')) |
| 907 |
self.assertFalse(hasattr(arr5, 'get_obj')) |
| 908 |
|
| 909 |
|
| 910 |
class _TestContainers(BaseTestCase): |
| 911 |
|
| 912 |
ALLOWED_TYPES = ('manager',) |
| 913 |
|
| 914 |
def test_list(self): |
| 915 |
a = self.list(range(10)) |
| 916 |
self.assertEqual(a[:], range(10)) |
| 917 |
|
| 918 |
b = self.list() |
| 919 |
self.assertEqual(b[:], []) |
| 920 |
|
| 921 |
b.extend(range(5)) |
| 922 |
self.assertEqual(b[:], range(5)) |
| 923 |
|
| 924 |
self.assertEqual(b[2], 2) |
| 925 |
self.assertEqual(b[2:10], [2, 3, 4]) |
| 926 |
|
| 927 |
b *= 2 |
| 928 |
self.assertEqual(b[:], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]) |
| 929 |
|
| 930 |
self.assertEqual(b + [5, 6], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6]) |
| 931 |
|
| 932 |
self.assertEqual(a[:], range(10)) |
| 933 |
|
| 934 |
d = [a, b] |
| 935 |
e = self.list(d) |
| 936 |
self.assertEqual( |
| 937 |
e[:], |
| 938 |
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]] |
| 939 |
) |
| 940 |
|
| 941 |
f = self.list([a]) |
| 942 |
a.append('hello') |
| 943 |
self.assertEqual(f[:], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello']]) |
| 944 |
|
| 945 |
def test_dict(self): |
| 946 |
d = self.dict() |
| 947 |
indices = range(65, 70) |
| 948 |
for i in indices: |
| 949 |
d[i] = chr(i) |
| 950 |
self.assertEqual(d.copy(), dict((j, chr(j)) for j in indices)) |
| 951 |
self.assertEqual(sorted(d.keys()), indices) |
| 952 |
self.assertEqual(sorted(d.values()), [chr(z) for z in indices]) |
| 953 |
self.assertEqual(sorted(d.items()), [(x, chr(x)) for x in indices]) |
| 954 |
|
| 955 |
def test_namespace(self): |
| 956 |
n = self.Namespace() |
| 957 |
n.name = 'Bob' |
| 958 |
n.job = 'Builder' |
| 959 |
n._hidden = 'hidden' |
| 960 |
self.assertEqual((n.name, n.job), ('Bob', 'Builder')) |
| 961 |
del n.job |
| 962 |
self.assertEqual(str(n), "Namespace(name='Bob')") |
| 963 |
self.assertTrue(hasattr(n, 'name')) |
| 964 |
self.assertTrue(not hasattr(n, 'job')) |
| 965 |
|
| 966 |
|
| 967 |
def sqr(x, wait=0.0): |
| 968 |
time.sleep(wait) |
| 969 |
return x * x |
| 970 |
|
| 971 |
|
| 972 |
class _TestPool(BaseTestCase): |
| 973 |
|
| 974 |
def test_apply(self): |
| 975 |
papply = self.pool.apply |
| 976 |
self.assertEqual(papply(sqr, (5,)), sqr(5)) |
| 977 |
self.assertEqual(papply(sqr, (), {'x': 3}), sqr(x=3)) |
| 978 |
|
| 979 |
def test_map(self): |
| 980 |
pmap = self.pool.map |
| 981 |
self.assertEqual(pmap(sqr, range(10)), map(sqr, range(10))) |
| 982 |
self.assertEqual(pmap(sqr, range(100), chunksize=20), |
| 983 |
map(sqr, range(100))) |
| 984 |
|
| 985 |
def test_map_chunksize(self): |
| 986 |
try: |
| 987 |
self.pool.map_async(sqr, [], chunksize=1).get(timeout=TIMEOUT1) |
| 988 |
except billiard.TimeoutError: |
| 989 |
self.fail("pool.map_async with chunksize stalled on null list") |
| 990 |
|
| 991 |
def test_async(self): |
| 992 |
res = self.pool.apply_async(sqr, (7, TIMEOUT1,)) |
| 993 |
get = TimingWrapper(res.get) |
| 994 |
self.assertEqual(get(), 49) |
| 995 |
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) |
| 996 |
|
| 997 |
def test_async_timeout(self): |
| 998 |
res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 0.2)) |
| 999 |
get = TimingWrapper(res.get) |
| 1000 |
self.assertRaises(billiard.TimeoutError, get, timeout=TIMEOUT2) |
| 1001 |
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2) |
| 1002 |
|
| 1003 |
def test_imap(self): |
| 1004 |
it = self.pool.imap(sqr, range(10)) |
| 1005 |
self.assertEqual(list(it), map(sqr, range(10))) |
| 1006 |
|
| 1007 |
it = self.pool.imap(sqr, range(10)) |
| 1008 |
for i in range(10): |
| 1009 |
self.assertEqual(it.next(), i * i) |
| 1010 |
self.assertRaises(StopIteration, it.next) |
| 1011 |
|
| 1012 |
it = self.pool.imap(sqr, range(1000), chunksize=100) |
| 1013 |
for i in range(1000): |
| 1014 |
self.assertEqual(it.next(), i * i) |
| 1015 |
self.assertRaises(StopIteration, it.next) |
| 1016 |
|
| 1017 |
def test_imap_unordered(self): |
| 1018 |
it = self.pool.imap_unordered(sqr, range(1000)) |
| 1019 |
self.assertEqual(sorted(it), map(sqr, range(1000))) |
| 1020 |
|
| 1021 |
it = self.pool.imap_unordered(sqr, range(1000), chunksize=53) |
| 1022 |
self.assertEqual(sorted(it), map(sqr, range(1000))) |
| 1023 |
|
| 1024 |
def test_make_pool(self): |
| 1025 |
p = billiard.Pool(3) |
| 1026 |
self.assertEqual(3, len(p._pool)) |
| 1027 |
p.close() |
| 1028 |
p.join() |
| 1029 |
|
| 1030 |
def test_terminate(self): |
| 1031 |
if self.TYPE == 'manager': |
| 1032 |
# On Unix a forked process increfs each shared object to |
| 1033 |
# which its parent process held a reference. If the |
| 1034 |
# forked process gets terminated then there is likely to |
| 1035 |
# be a reference leak. So to prevent |
| 1036 |
# _TestZZZNumberOfObjects from failing we skip this test |
| 1037 |
# when using a manager. |
| 1038 |
return |
| 1039 |
|
| 1040 |
self.pool.map_async( |
| 1041 |
time.sleep, [0.1 for i in range(10000)], chunksize=1 |
| 1042 |
) |
| 1043 |
self.pool.terminate() |
| 1044 |
join = TimingWrapper(self.pool.join) |
| 1045 |
join() |
| 1046 |
self.assertTrue(join.elapsed < 0.2) |
| 1047 |
|
| 1048 |
|
| 1049 |
class _TestPoolWorkerLifetime(BaseTestCase): |
| 1050 |
ALLOWED_TYPES = ('processes', ) |
| 1051 |
|
| 1052 |
def test_pool_worker_lifetime(self): |
| 1053 |
p = billiard.Pool(3, maxtasksperchild=10) |
| 1054 |
self.assertEqual(3, len(p._pool)) |
| 1055 |
origworkerpids = [w.pid for w in p._pool] |
| 1056 |
# Run many tasks so each worker gets replaced (hopefully) |
| 1057 |
results = [] |
| 1058 |
for i in range(100): |
| 1059 |
results.append(p.apply_async(sqr, (i, ))) |
| 1060 |
# Fetch the results and verify we got the right answers, |
| 1061 |
# also ensuring all the tasks have completed. |
| 1062 |
for (j, res) in enumerate(results): |
| 1063 |
self.assertEqual(res.get(), sqr(j)) |
| 1064 |
# Refill the pool |
| 1065 |
p._repopulate_pool() |
| 1066 |
# Wait until all workers are alive |
| 1067 |
countdown = 5 |
| 1068 |
while countdown and not all(w.is_alive() for w in p._pool): |
| 1069 |
countdown -= 1 |
| 1070 |
time.sleep(DELTA) |
| 1071 |
finalworkerpids = [worker.pid for worker in p._pool] |
| 1072 |
# All pids should be assigned. See issue #7805. |
| 1073 |
self.assertNotIn(None, origworkerpids) |
| 1074 |
self.assertNotIn(None, finalworkerpids) |
| 1075 |
# Finally, check that the worker pids have changed |
| 1076 |
self.assertNotEqual(sorted(origworkerpids), sorted(finalworkerpids)) |
| 1077 |
p.close() |
| 1078 |
p.join() |
| 1079 |
|
| 1080 |
|
| 1081 |
class _TestZZZNumberOfObjects(BaseTestCase): |
| 1082 |
# Test that manager has expected number of shared objects left |
| 1083 |
|
| 1084 |
# Because test cases are sorted alphabetically, this one will get |
| 1085 |
# run after all the other tests for the manager. It tests that |
| 1086 |
# there have been no "reference leaks" for the manager's shared |
| 1087 |
# objects. Note the comment in _TestPool.test_terminate(). |
| 1088 |
ALLOWED_TYPES = ('manager',) |
| 1089 |
|
| 1090 |
def test_number_of_objects(self): |
| 1091 |
EXPECTED_NUMBER = 1 # the pool object is still alive |
| 1092 |
billiard.active_children() # discard dead process objs |
| 1093 |
gc.collect() # do garbage collection |
| 1094 |
refs = self.manager._number_of_objects() |
| 1095 |
debug_info = self.manager._debug_info() |
| 1096 |
if refs != EXPECTED_NUMBER: |
| 1097 |
print(self.manager._debug_info()) |
| 1098 |
print(debug_info) |
| 1099 |
|
| 1100 |
self.assertEqual(refs, EXPECTED_NUMBER) |
| 1101 |
|
| 1102 |
# Test of creating a customized manager class |
| 1103 |
from billiard.managers import BaseManager, BaseProxy, RemoteError # noqa |
| 1104 |
|
| 1105 |
|
| 1106 |
class FooBar: |
| 1107 |
|
| 1108 |
def f(self): |
| 1109 |
return 'f()' |
| 1110 |
|
| 1111 |
def g(self): |
| 1112 |
raise ValueError |
| 1113 |
|
| 1114 |
def _h(self): |
| 1115 |
return '_h()' |
| 1116 |
|
| 1117 |
|
| 1118 |
def baz(): |
| 1119 |
for i in xrange(10): |
| 1120 |
yield i * i |
| 1121 |
|
| 1122 |
|
| 1123 |
class IteratorProxy(BaseProxy): |
| 1124 |
_exposed_ = ('next', '__next__') |
| 1125 |
|
| 1126 |
def __iter__(self): |
| 1127 |
return self |
| 1128 |
|
| 1129 |
def next(self): |
| 1130 |
return self._callmethod('next') |
| 1131 |
|
| 1132 |
def __next__(self): |
| 1133 |
return self._callmethod('__next__') |
| 1134 |
|
| 1135 |
|
| 1136 |
class MyManager(BaseManager): |
| 1137 |
pass |
| 1138 |
|
| 1139 |
MyManager.register('Foo', callable=FooBar) |
| 1140 |
MyManager.register('Bar', callable=FooBar, exposed=('f', '_h')) |
| 1141 |
MyManager.register('baz', callable=baz, proxytype=IteratorProxy) |
| 1142 |
|
| 1143 |
|
| 1144 |
class _TestMyManager(BaseTestCase): |
| 1145 |
|
| 1146 |
ALLOWED_TYPES = ('manager',) |
| 1147 |
|
| 1148 |
def test_mymanager(self): |
| 1149 |
manager = MyManager() |
| 1150 |
manager.start() |
| 1151 |
|
| 1152 |
foo = manager.Foo() |
| 1153 |
bar = manager.Bar() |
| 1154 |
baz = manager.baz() |
| 1155 |
|
| 1156 |
foo_methods = [name for name in ('f', 'g', '_h') if hasattr(foo, name)] |
| 1157 |
bar_methods = [name for name in ('f', 'g', '_h') if hasattr(bar, name)] |
| 1158 |
|
| 1159 |
self.assertEqual(foo_methods, ['f', 'g']) |
| 1160 |
self.assertEqual(bar_methods, ['f', '_h']) |
| 1161 |
|
| 1162 |
self.assertEqual(foo.f(), 'f()') |
| 1163 |
self.assertRaises(ValueError, foo.g) |
| 1164 |
self.assertEqual(foo._callmethod('f'), 'f()') |
| 1165 |
self.assertRaises(RemoteError, foo._callmethod, '_h') |
| 1166 |
|
| 1167 |
self.assertEqual(bar.f(), 'f()') |
| 1168 |
self.assertEqual(bar._h(), '_h()') |
| 1169 |
self.assertEqual(bar._callmethod('f'), 'f()') |
| 1170 |
self.assertEqual(bar._callmethod('_h'), '_h()') |
| 1171 |
|
| 1172 |
self.assertEqual(list(baz), [i * i for i in range(10)]) |
| 1173 |
|
| 1174 |
manager.shutdown() |
| 1175 |
|
| 1176 |
_queue = Queue.Queue() |
| 1177 |
|
| 1178 |
|
| 1179 |
# Test of connecting to a remote server and using xmlrpclib for serialization |
| 1180 |
def get_queue(): |
| 1181 |
return _queue |
| 1182 |
|
| 1183 |
|
| 1184 |
class QueueManager(BaseManager): |
| 1185 |
'''manager class used by server process''' |
| 1186 |
QueueManager.register('get_queue', callable=get_queue) |
| 1187 |
|
| 1188 |
|
| 1189 |
class QueueManager2(BaseManager): |
| 1190 |
'''manager class which specifies the same interface as QueueManager''' |
| 1191 |
QueueManager2.register('get_queue') |
| 1192 |
|
| 1193 |
|
| 1194 |
SERIALIZER = 'xmlrpclib' |
| 1195 |
|
| 1196 |
|
| 1197 |
class _TestRemoteManager(BaseTestCase): |
| 1198 |
|
| 1199 |
ALLOWED_TYPES = ('manager',) |
| 1200 |
|
| 1201 |
def _putter(self, address, authkey): |
| 1202 |
manager = QueueManager2( |
| 1203 |
address=address, authkey=authkey, serializer=SERIALIZER |
| 1204 |
) |
| 1205 |
manager.connect() |
| 1206 |
queue = manager.get_queue() |
| 1207 |
queue.put(('hello world', None, True, 2.25)) |
| 1208 |
|
| 1209 |
def test_remote(self): |
| 1210 |
authkey = os.urandom(32) |
| 1211 |
|
| 1212 |
manager = QueueManager( |
| 1213 |
address=('localhost', 0), authkey=authkey, serializer=SERIALIZER |
| 1214 |
) |
| 1215 |
manager.start() |
| 1216 |
|
| 1217 |
p = self.Process(target=self._putter, args=(manager.address, authkey)) |
| 1218 |
p.start() |
| 1219 |
|
| 1220 |
manager2 = QueueManager2( |
| 1221 |
address=manager.address, authkey=authkey, serializer=SERIALIZER |
| 1222 |
) |
| 1223 |
manager2.connect() |
| 1224 |
queue = manager2.get_queue() |
| 1225 |
|
| 1226 |
# Note that xmlrpclib will deserialize object as a list not a tuple |
| 1227 |
self.assertEqual(queue.get(), ['hello world', None, True, 2.25]) |
| 1228 |
|
| 1229 |
# Because we are using xmlrpclib for serialization instead of |
| 1230 |
# pickle this will cause a serialization error. |
| 1231 |
self.assertRaises(Exception, queue.put, time.sleep) |
| 1232 |
|
| 1233 |
# Make queue finalizer run before the server is stopped |
| 1234 |
del queue |
| 1235 |
manager.shutdown() |
| 1236 |
|
| 1237 |
|
| 1238 |
class _TestManagerRestart(BaseTestCase): |
| 1239 |
|
| 1240 |
def _putter(self, address, authkey): |
| 1241 |
manager = QueueManager( |
| 1242 |
address=address, authkey=authkey, serializer=SERIALIZER) |
| 1243 |
manager.connect() |
| 1244 |
queue = manager.get_queue() |
| 1245 |
queue.put('hello world') |
| 1246 |
|
| 1247 |
def test_rapid_restart(self): |
| 1248 |
authkey = os.urandom(32) |
| 1249 |
manager = QueueManager( |
| 1250 |
address=('localhost', 0), authkey=authkey, serializer=SERIALIZER) |
| 1251 |
addr = manager.get_server().address |
| 1252 |
manager.start() |
| 1253 |
|
| 1254 |
p = self.Process(target=self._putter, args=(manager.address, authkey)) |
| 1255 |
p.start() |
| 1256 |
queue = manager.get_queue() |
| 1257 |
self.assertEqual(queue.get(), 'hello world') |
| 1258 |
del queue |
| 1259 |
manager.shutdown() |
| 1260 |
manager = QueueManager( |
| 1261 |
address=addr, authkey=authkey, serializer=SERIALIZER) |
| 1262 |
manager.start() |
| 1263 |
manager.shutdown() |
| 1264 |
|
| 1265 |
SENTINEL = latin('') |
| 1266 |
|
| 1267 |
|
| 1268 |
class _TestConnection(BaseTestCase): |
| 1269 |
|
| 1270 |
ALLOWED_TYPES = ('processes', 'threads') |
| 1271 |
|
| 1272 |
def _echo(self, conn): |
| 1273 |
for msg in iter(conn.recv_bytes, SENTINEL): |
| 1274 |
conn.send_bytes(msg) |
| 1275 |
conn.close() |
| 1276 |
|
| 1277 |
def test_connection(self): |
| 1278 |
conn, child_conn = self.Pipe() |
| 1279 |
|
| 1280 |
p = self.Process(target=self._echo, args=(child_conn,)) |
| 1281 |
p.daemon = True |
| 1282 |
p.start() |
| 1283 |
|
| 1284 |
seq = [1, 2.25, None] |
| 1285 |
msg = latin('hello world') |
| 1286 |
longmsg = msg * 10 |
| 1287 |
arr = array.array('i', range(4)) |
| 1288 |
|
| 1289 |
if self.TYPE == 'processes': |
| 1290 |
self.assertEqual(type(conn.fileno()), int) |
| 1291 |
|
| 1292 |
self.assertEqual(conn.send(seq), None) |
| 1293 |
self.assertEqual(conn.recv(), seq) |
| 1294 |
|
| 1295 |
self.assertEqual(conn.send_bytes(msg), None) |
| 1296 |
self.assertEqual(conn.recv_bytes(), msg) |
| 1297 |
|
| 1298 |
if self.TYPE == 'processes': |
| 1299 |
buffer = array.array('i', [0] * 10) |
| 1300 |
expected = list(arr) + [0] * (10 - len(arr)) |
| 1301 |
self.assertEqual(conn.send_bytes(arr), None) |
| 1302 |
self.assertEqual(conn.recv_bytes_into(buffer), |
| 1303 |
len(arr) * buffer.itemsize) |
| 1304 |
self.assertEqual(list(buffer), expected) |
| 1305 |
|
| 1306 |
buffer = array.array('i', [0] * 10) |
| 1307 |
expected = [0] * 3 + list(arr) + [0] * (10 - 3 - len(arr)) |
| 1308 |
self.assertEqual(conn.send_bytes(arr), None) |
| 1309 |
self.assertEqual(conn.recv_bytes_into(buffer, 3 * buffer.itemsize), |
| 1310 |
len(arr) * buffer.itemsize) |
| 1311 |
self.assertEqual(list(buffer), expected) |
| 1312 |
|
| 1313 |
buffer = bytearray(latin(' ' * 40)) |
| 1314 |
self.assertEqual(conn.send_bytes(longmsg), None) |
| 1315 |
try: |
| 1316 |
res = conn.recv_bytes_into(buffer) |
| 1317 |
except billiard.BufferTooShort as exc: |
| 1318 |
self.assertEqual(exc.args, (longmsg,)) |
| 1319 |
else: |
| 1320 |
self.fail('expected BufferTooShort, got %s' % res) |
| 1321 |
|
| 1322 |
poll = TimingWrapper(conn.poll) |
| 1323 |
|
| 1324 |
self.assertEqual(poll(), False) |
| 1325 |
self.assertTimingAlmostEqual(poll.elapsed, 0) |
| 1326 |
|
| 1327 |
self.assertEqual(poll(TIMEOUT1), False) |
| 1328 |
self.assertTimingAlmostEqual(poll.elapsed, TIMEOUT1) |
| 1329 |
|
| 1330 |
conn.send(None) |
| 1331 |
|
| 1332 |
self.assertEqual(poll(TIMEOUT1), True) |
| 1333 |
self.assertTimingAlmostEqual(poll.elapsed, 0) |
| 1334 |
|
| 1335 |
self.assertEqual(conn.recv(), None) |
| 1336 |
|
| 1337 |
really_big_msg = latin('X') * (1024 * 1024 * 16) # 16Mb |
| 1338 |
conn.send_bytes(really_big_msg) |
| 1339 |
self.assertEqual(conn.recv_bytes(), really_big_msg) |
| 1340 |
|
| 1341 |
conn.send_bytes(SENTINEL) # tell child to quit |
| 1342 |
child_conn.close() |
| 1343 |
|
| 1344 |
if self.TYPE == 'processes': |
| 1345 |
self.assertEqual(conn.readable, True) |
| 1346 |
self.assertEqual(conn.writable, True) |
| 1347 |
self.assertRaises(EOFError, conn.recv) |
| 1348 |
self.assertRaises(EOFError, conn.recv_bytes) |
| 1349 |
|
| 1350 |
p.join() |
| 1351 |
|
| 1352 |
def test_duplex_false(self): |
| 1353 |
reader, writer = self.Pipe(duplex=False) |
| 1354 |
self.assertEqual(writer.send(1), None) |
| 1355 |
self.assertEqual(reader.recv(), 1) |
| 1356 |
if self.TYPE == 'processes': |
| 1357 |
self.assertEqual(reader.readable, True) |
| 1358 |
self.assertEqual(reader.writable, False) |
| 1359 |
self.assertEqual(writer.readable, False) |
| 1360 |
self.assertEqual(writer.writable, True) |
| 1361 |
self.assertRaises(IOError, reader.send, 2) |
| 1362 |
self.assertRaises(IOError, writer.recv) |
| 1363 |
self.assertRaises(IOError, writer.poll) |
| 1364 |
|
| 1365 |
def test_spawn_close(self): |
| 1366 |
# We test that a pipe connection can be closed by parent |
| 1367 |
# process immediately after child is spawned. On Windows this |
| 1368 |
# would have sometimes failed on old versions because |
| 1369 |
# child_conn would be closed before the child got a chance to |
| 1370 |
# duplicate it. |
| 1371 |
conn, child_conn = self.Pipe() |
| 1372 |
|
| 1373 |
p = self.Process(target=self._echo, args=(child_conn,)) |
| 1374 |
p.start() |
| 1375 |
child_conn.close() # this might complete before child initializes |
| 1376 |
|
| 1377 |
msg = latin('hello') |
| 1378 |
conn.send_bytes(msg) |
| 1379 |
self.assertEqual(conn.recv_bytes(), msg) |
| 1380 |
|
| 1381 |
conn.send_bytes(SENTINEL) |
| 1382 |
conn.close() |
| 1383 |
p.join() |
| 1384 |
|
| 1385 |
def test_sendbytes(self): |
| 1386 |
if self.TYPE != 'processes': |
| 1387 |
return |
| 1388 |
|
| 1389 |
msg = latin('abcdefghijklmnopqrstuvwxyz') |
| 1390 |
a, b = self.Pipe() |
| 1391 |
|
| 1392 |
a.send_bytes(msg) |
| 1393 |
self.assertEqual(b.recv_bytes(), msg) |
| 1394 |
|
| 1395 |
a.send_bytes(msg, 5) |
| 1396 |
self.assertEqual(b.recv_bytes(), msg[5:]) |
| 1397 |
|
| 1398 |
a.send_bytes(msg, 7, 8) |
| 1399 |
self.assertEqual(b.recv_bytes(), msg[7:7 + 8]) |
| 1400 |
|
| 1401 |
a.send_bytes(msg, 26) |
| 1402 |
self.assertEqual(b.recv_bytes(), latin('')) |
| 1403 |
|
| 1404 |
a.send_bytes(msg, 26, 0) |
| 1405 |
self.assertEqual(b.recv_bytes(), latin('')) |
| 1406 |
|
| 1407 |
self.assertRaises(ValueError, a.send_bytes, msg, 27) |
| 1408 |
self.assertRaises(ValueError, a.send_bytes, msg, 22, 5) |
| 1409 |
self.assertRaises(ValueError, a.send_bytes, msg, 26, 1) |
| 1410 |
self.assertRaises(ValueError, a.send_bytes, msg, -1) |
| 1411 |
self.assertRaises(ValueError, a.send_bytes, msg, 4, -1) |
| 1412 |
|
| 1413 |
|
| 1414 |
class _TestListenerClient(BaseTestCase): |
| 1415 |
|
| 1416 |
ALLOWED_TYPES = ('processes', 'threads') |
| 1417 |
|
| 1418 |
def _test(self, address): |
| 1419 |
conn = self.connection.Client(address) |
| 1420 |
conn.send('hello') |
| 1421 |
conn.close() |
| 1422 |
|
| 1423 |
def test_listener_client(self): |
| 1424 |
for family in self.connection.families: |
| 1425 |
l = self.connection.Listener(family=family) |
| 1426 |
p = self.Process(target=self._test, args=(l.address,)) |
| 1427 |
p.daemon = True |
| 1428 |
p.start() |
| 1429 |
conn = l.accept() |
| 1430 |
self.assertEqual(conn.recv(), 'hello') |
| 1431 |
p.join() |
| 1432 |
l.close() |
| 1433 |
''' |
| 1434 |
class _TestPicklingConnections(BaseTestCase): |
| 1435 |
"""Test of sending connection and socket objects between processes""" |
| 1436 |
|
| 1437 |
ALLOWED_TYPES = ('processes',) |
| 1438 |
|
| 1439 |
def _listener(self, conn, families): |
| 1440 |
for fam in families: |
| 1441 |
l = self.connection.Listener(family=fam) |
| 1442 |
conn.send(l.address) |
| 1443 |
new_conn = l.accept() |
| 1444 |
conn.send(new_conn) |
| 1445 |
|
| 1446 |
if self.TYPE == 'processes': |
| 1447 |
l = socket.socket() |
| 1448 |
l.bind(('localhost', 0)) |
| 1449 |
conn.send(l.getsockname()) |
| 1450 |
l.listen(1) |
| 1451 |
new_conn, addr = l.accept() |
| 1452 |
conn.send(new_conn) |
| 1453 |
|
| 1454 |
conn.recv() |
| 1455 |
|
| 1456 |
def _remote(self, conn): |
| 1457 |
for (address, msg) in iter(conn.recv, None): |
| 1458 |
client = self.connection.Client(address) |
| 1459 |
client.send(msg.upper()) |
| 1460 |
client.close() |
| 1461 |
|
| 1462 |
if self.TYPE == 'processes': |
| 1463 |
address, msg = conn.recv() |
| 1464 |
client = socket.socket() |
| 1465 |
client.connect(address) |
| 1466 |
client.sendall(msg.upper()) |
| 1467 |
client.close() |
| 1468 |
|
| 1469 |
conn.close() |
| 1470 |
|
| 1471 |
def test_pickling(self): |
| 1472 |
try: |
| 1473 |
billiard.allow_connection_pickling() |
| 1474 |
except ImportError: |
| 1475 |
return |
| 1476 |
|
| 1477 |
families = self.connection.families |
| 1478 |
|
| 1479 |
lconn, lconn0 = self.Pipe() |
| 1480 |
lp = self.Process(target=self._listener, args=(lconn0, families)) |
| 1481 |
lp.start() |
| 1482 |
lconn0.close() |
| 1483 |
|
| 1484 |
rconn, rconn0 = self.Pipe() |
| 1485 |
rp = self.Process(target=self._remote, args=(rconn0,)) |
| 1486 |
rp.start() |
| 1487 |
rconn0.close() |
| 1488 |
|
| 1489 |
for fam in families: |
| 1490 |
msg = ('This connection uses family %s' % fam).encode('ascii') |
| 1491 |
address = lconn.recv() |
| 1492 |
rconn.send((address, msg)) |
| 1493 |
new_conn = lconn.recv() |
| 1494 |
self.assertEqual(new_conn.recv(), msg.upper()) |
| 1495 |
|
| 1496 |
rconn.send(None) |
| 1497 |
|
| 1498 |
if self.TYPE == 'processes': |
| 1499 |
msg = latin('This connection uses a normal socket') |
| 1500 |
address = lconn.recv() |
| 1501 |
rconn.send((address, msg)) |
| 1502 |
if hasattr(socket, 'fromfd'): |
| 1503 |
new_conn = lconn.recv() |
| 1504 |
self.assertEqual(new_conn.recv(100), msg.upper()) |
| 1505 |
else: |
| 1506 |
# XXX On Windows with Py2.6 need to backport fromfd() |
| 1507 |
discard = lconn.recv_bytes() |
| 1508 |
|
| 1509 |
lconn.send(None) |
| 1510 |
|
| 1511 |
rconn.close() |
| 1512 |
lconn.close() |
| 1513 |
|
| 1514 |
lp.join() |
| 1515 |
rp.join() |
| 1516 |
|
| 1517 |
''' |
| 1518 |
|
| 1519 |
|
| 1520 |
class _TestHeap(BaseTestCase): |
| 1521 |
|
| 1522 |
ALLOWED_TYPES = ('processes',) |
| 1523 |
|
| 1524 |
def test_heap(self): |
| 1525 |
iterations = 5000 |
| 1526 |
maxblocks = 50 |
| 1527 |
blocks = [] |
| 1528 |
|
| 1529 |
# create and destroy lots of blocks of different sizes |
| 1530 |
for i in xrange(iterations): |
| 1531 |
size = int(random.lognormvariate(0, 1) * 1000) |
| 1532 |
b = billiard.heap.BufferWrapper(size) |
| 1533 |
blocks.append(b) |
| 1534 |
if len(blocks) > maxblocks: |
| 1535 |
i = random.randrange(maxblocks) |
| 1536 |
del blocks[i] |
| 1537 |
|
| 1538 |
# get the heap object |
| 1539 |
heap = billiard.heap.BufferWrapper._heap |
| 1540 |
|
| 1541 |
# verify the state of the heap |
| 1542 |
all = [] |
| 1543 |
occupied = 0 |
| 1544 |
for L in heap._len_to_seq.values(): |
| 1545 |
for arena, start, stop in L: |
| 1546 |
all.append((heap._arenas.index(arena), start, stop, |
| 1547 |
stop - start, 'free')) |
| 1548 |
for arena, start, stop in heap._allocated_blocks: |
| 1549 |
all.append((heap._arenas.index(arena), start, stop, |
| 1550 |
stop - start, 'occupied')) |
| 1551 |
occupied += stop - start |
| 1552 |
|
| 1553 |
all.sort() |
| 1554 |
|
| 1555 |
for i in range(len(all) - 1): |
| 1556 |
(arena, start, stop) = all[i][:3] |
| 1557 |
(narena, nstart, nstop) = all[i + 1][:3] |
| 1558 |
self.assertTrue((arena != narena and nstart == 0) or |
| 1559 |
(stop == nstart)) |
| 1560 |
|
| 1561 |
|
| 1562 |
class _Foo(Structure): |
| 1563 |
_fields_ = [ |
| 1564 |
('x', c_int), |
| 1565 |
('y', c_double) |
| 1566 |
] |
| 1567 |
|
| 1568 |
|
| 1569 |
class _TestSharedCTypes(BaseTestCase): |
| 1570 |
|
| 1571 |
ALLOWED_TYPES = ('processes', ) |
| 1572 |
|
| 1573 |
def _double(self, x, y, foo, arr, string): |
| 1574 |
x.value *= 2 |
| 1575 |
y.value *= 2 |
| 1576 |
foo.x *= 2 |
| 1577 |
foo.y *= 2 |
| 1578 |
string.value *= 2 |
| 1579 |
for i in range(len(arr)): |
| 1580 |
arr[i] *= 2 |
| 1581 |
|
| 1582 |
@unittest.skipIf(Value is None, "requires ctypes.Value") |
| 1583 |
def test_sharedctypes(self, lock=False): |
| 1584 |
x = Value('i', 7, lock=lock) |
| 1585 |
y = Value(c_double, 1.0 / 3.0, lock=lock) |
| 1586 |
foo = Value(_Foo, 3, 2, lock=lock) |
| 1587 |
arr = self.Array('d', range(10), lock=lock) |
| 1588 |
string = self.Array('c', 20, lock=lock) |
| 1589 |
string.value = 'hello' |
| 1590 |
|
| 1591 |
p = self.Process(target=self._double, args=(x, y, foo, arr, string)) |
| 1592 |
p.start() |
| 1593 |
p.join() |
| 1594 |
|
| 1595 |
self.assertEqual(x.value, 14) |
| 1596 |
self.assertAlmostEqual(y.value, 2.0 / 3.0) |
| 1597 |
self.assertEqual(foo.x, 6) |
| 1598 |
self.assertAlmostEqual(foo.y, 4.0) |
| 1599 |
for i in range(10): |
| 1600 |
self.assertAlmostEqual(arr[i], i * 2) |
| 1601 |
self.assertEqual(string.value, latin('hellohello')) |
| 1602 |
|
| 1603 |
@unittest.skipIf(Value is None, "requires ctypes.Value") |
| 1604 |
def test_synchronize(self): |
| 1605 |
self.test_sharedctypes(lock=True) |
| 1606 |
|
| 1607 |
@unittest.skipIf(ctypes_copy is None, "requires ctypes.copy") |
| 1608 |
def test_copy(self): |
| 1609 |
foo = _Foo(2, 5.0) |
| 1610 |
bar = ctypes_copy(foo) |
| 1611 |
foo.x = 0 |
| 1612 |
foo.y = 0 |
| 1613 |
self.assertEqual(bar.x, 2) |
| 1614 |
self.assertAlmostEqual(bar.y, 5.0) |
| 1615 |
|
| 1616 |
|
| 1617 |
class _TestFinalize(BaseTestCase): |
| 1618 |
|
| 1619 |
ALLOWED_TYPES = ('processes',) |
| 1620 |
|
| 1621 |
def _test_finalize(self, conn): |
| 1622 |
class Foo(object): |
| 1623 |
pass |
| 1624 |
|
| 1625 |
a = Foo() |
| 1626 |
util.Finalize(a, conn.send, args=('a',)) |
| 1627 |
del a # triggers callback for a |
| 1628 |
|
| 1629 |
b = Foo() |
| 1630 |
close_b = util.Finalize(b, conn.send, args=('b',)) |
| 1631 |
close_b() # triggers callback for b |
| 1632 |
close_b() # does nothing because callback has already been called |
| 1633 |
del b # does nothing because callback has already been called |
| 1634 |
|
| 1635 |
c = Foo() |
| 1636 |
util.Finalize(c, conn.send, args=('c',)) |
| 1637 |
|
| 1638 |
d10 = Foo() |
| 1639 |
util.Finalize(d10, conn.send, args=('d10',), exitpriority=1) |
| 1640 |
|
| 1641 |
d01 = Foo() |
| 1642 |
util.Finalize(d01, conn.send, args=('d01',), exitpriority=0) |
| 1643 |
d02 = Foo() |
| 1644 |
util.Finalize(d02, conn.send, args=('d02',), exitpriority=0) |
| 1645 |
d03 = Foo() |
| 1646 |
util.Finalize(d03, conn.send, args=('d03',), exitpriority=0) |
| 1647 |
|
| 1648 |
util.Finalize(None, conn.send, args=('e',), exitpriority=-10) |
| 1649 |
|
| 1650 |
util.Finalize(None, conn.send, args=('STOP',), exitpriority=-100) |
| 1651 |
|
| 1652 |
# call mutliprocessing's cleanup function then exit process without |
| 1653 |
# garbage collecting locals |
| 1654 |
util._exit_function() |
| 1655 |
conn.close() |
| 1656 |
os._exit(0) |
| 1657 |
|
| 1658 |
def test_finalize(self): |
| 1659 |
conn, child_conn = self.Pipe() |
| 1660 |
|
| 1661 |
p = self.Process(target=self._test_finalize, args=(child_conn,)) |
| 1662 |
p.start() |
| 1663 |
p.join() |
| 1664 |
|
| 1665 |
result = [obj for obj in iter(conn.recv, 'STOP')] |
| 1666 |
self.assertEqual(result, ['a', 'b', 'd10', 'd03', 'd02', 'd01', 'e']) |
| 1667 |
|
| 1668 |
|
| 1669 |
class _TestImportStar(BaseTestCase): |
| 1670 |
"""Test that from ... import * works for each module""" |
| 1671 |
ALLOWED_TYPES = ('processes',) |
| 1672 |
|
| 1673 |
def test_import(self): |
| 1674 |
modules = [ |
| 1675 |
'billiard', 'billiard.connection', |
| 1676 |
'billiard.heap', 'billiard.managers', |
| 1677 |
'billiard.pool', 'billiard.process', |
| 1678 |
'billiard.reduction', |
| 1679 |
'billiard.synchronize', 'billiard.util' |
| 1680 |
] |
| 1681 |
|
| 1682 |
if c_int is not None: |
| 1683 |
# This module requires _ctypes |
| 1684 |
modules.append('billiard.sharedctypes') |
| 1685 |
|
| 1686 |
for name in modules: |
| 1687 |
__import__(name) |
| 1688 |
mod = sys.modules[name] |
| 1689 |
|
| 1690 |
for attr in getattr(mod, '__all__', ()): |
| 1691 |
self.assertTrue( |
| 1692 |
hasattr(mod, attr), |
| 1693 |
'%r does not have attribute %r' % (mod, attr) |
| 1694 |
) |
| 1695 |
|
| 1696 |
|
| 1697 |
class _TestLogging(BaseTestCase): |
| 1698 |
"""Quick test that logging works -- does not test logging output""" |
| 1699 |
ALLOWED_TYPES = ('processes',) |
| 1700 |
|
| 1701 |
def test_enable_logging(self): |
| 1702 |
logger = billiard.get_logger() |
| 1703 |
logger.setLevel(util.SUBWARNING) |
| 1704 |
self.assertTrue(logger is not None) |
| 1705 |
logger.debug('this will not be printed') |
| 1706 |
logger.info('nor will this') |
| 1707 |
logger.setLevel(LOG_LEVEL) |
| 1708 |
|
| 1709 |
def _test_level(self, conn): |
| 1710 |
logger = billiard.get_logger() |
| 1711 |
conn.send(logger.getEffectiveLevel()) |
| 1712 |
|
| 1713 |
def test_level(self): |
| 1714 |
LEVEL1 = 32 |
| 1715 |
LEVEL2 = 37 |
| 1716 |
|
| 1717 |
logger = billiard.get_logger() |
| 1718 |
root_logger = logging.getLogger() |
| 1719 |
root_level = root_logger.level |
| 1720 |
|
| 1721 |
reader, writer = billiard.Pipe(duplex=False) |
| 1722 |
|
| 1723 |
logger.setLevel(LEVEL1) |
| 1724 |
self.Process(target=self._test_level, args=(writer,)).start() |
| 1725 |
self.assertEqual(LEVEL1, reader.recv()) |
| 1726 |
|
| 1727 |
logger.setLevel(logging.NOTSET) |
| 1728 |
root_logger.setLevel(LEVEL2) |
| 1729 |
self.Process(target=self._test_level, args=(writer,)).start() |
| 1730 |
self.assertEqual(LEVEL2, reader.recv()) |
| 1731 |
|
| 1732 |
root_logger.setLevel(root_level) |
| 1733 |
logger.setLevel(level=LOG_LEVEL) |
| 1734 |
|
| 1735 |
|
| 1736 |
# class _TestLoggingProcessName(BaseTestCase): |
| 1737 |
# |
| 1738 |
# def handle(self, record): |
| 1739 |
# assert record.processName == billiard.current_process().name |
| 1740 |
# self.__handled = True |
| 1741 |
# |
| 1742 |
# def test_logging(self): |
| 1743 |
# handler = logging.Handler() |
| 1744 |
# handler.handle = self.handle |
| 1745 |
# self.__handled = False |
| 1746 |
# # Bypass getLogger() and side-effects |
| 1747 |
# logger = logging.getLoggerClass()( |
| 1748 |
# 'billiard.test.TestLoggingProcessName') |
| 1749 |
# logger.addHandler(handler) |
| 1750 |
# logger.propagate = False |
| 1751 |
# |
| 1752 |
# logger.warn('foo') |
| 1753 |
# assert self.__handled |
| 1754 |
|
| 1755 |
# |
| 1756 |
# Test to verify handle verification, see issue 3321 |
| 1757 |
# |
| 1758 |
|
| 1759 |
|
| 1760 |
class TestInvalidHandle(unittest.TestCase): |
| 1761 |
|
| 1762 |
@unittest.skipIf(WIN32, "skipped on Windows") |
| 1763 |
def test_invalid_handles(self): |
| 1764 |
conn = _billiard.Connection(44977608) |
| 1765 |
self.assertRaises(IOError, conn.poll) |
| 1766 |
self.assertRaises(IOError, _billiard.Connection, -1) |
| 1767 |
|
| 1768 |
|
| 1769 |
def get_attributes(Source, names): |
| 1770 |
d = {} |
| 1771 |
for name in names: |
| 1772 |
obj = getattr(Source, name) |
| 1773 |
if type(obj) == type(get_attributes): |
| 1774 |
obj = staticmethod(obj) |
| 1775 |
d[name] = obj |
| 1776 |
return d |
| 1777 |
|
| 1778 |
|
| 1779 |
def create_test_cases(Mixin, type): |
| 1780 |
result = {} |
| 1781 |
glob = globals() |
| 1782 |
Type = type.capitalize() |
| 1783 |
|
| 1784 |
for name in glob.keys(): |
| 1785 |
if name.startswith('_Test'): |
| 1786 |
base = glob[name] |
| 1787 |
if type in base.ALLOWED_TYPES: |
| 1788 |
newname = 'With' + Type + name[1:] |
| 1789 |
|
| 1790 |
class Temp(base, unittest.TestCase, Mixin): |
| 1791 |
pass |
| 1792 |
|
| 1793 |
result[newname] = Temp |
| 1794 |
Temp.__name__ = newname |
| 1795 |
Temp.__module__ = Mixin.__module__ |
| 1796 |
return result |
| 1797 |
|
| 1798 |
|
| 1799 |
class ProcessesMixin: |
| 1800 |
TYPE = 'processes' |
| 1801 |
Process = billiard.Process |
| 1802 |
locals().update(get_attributes(billiard, ( |
| 1803 |
'Queue', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', |
| 1804 |
'Condition', 'Event', 'Value', 'Array', 'RawValue', |
| 1805 |
'RawArray', 'current_process', 'active_children', 'Pipe', |
| 1806 |
'connection', 'JoinableQueue' |
| 1807 |
))) |
| 1808 |
|
| 1809 |
testcases_processes = create_test_cases(ProcessesMixin, type='processes') |
| 1810 |
globals().update(testcases_processes) |
| 1811 |
|
| 1812 |
|
| 1813 |
class ManagerMixin: |
| 1814 |
TYPE = 'manager' |
| 1815 |
Process = billiard.Process |
| 1816 |
manager = object.__new__(billiard.managers.SyncManager) |
| 1817 |
locals().update(get_attributes(manager, ( |
| 1818 |
'Queue', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', |
| 1819 |
'Condition', 'Event', 'Value', 'Array', 'list', 'dict', |
| 1820 |
'Namespace', 'JoinableQueue' |
| 1821 |
))) |
| 1822 |
|
| 1823 |
testcases_manager = create_test_cases(ManagerMixin, type='manager') |
| 1824 |
globals().update(testcases_manager) |
| 1825 |
|
| 1826 |
|
| 1827 |
class ThreadsMixin: |
| 1828 |
TYPE = 'threads' |
| 1829 |
Process = billiard.dummy.Process |
| 1830 |
locals().update(get_attributes(billiard.dummy, ( |
| 1831 |
'Queue', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', |
| 1832 |
'Condition', 'Event', 'Value', 'Array', 'current_process', |
| 1833 |
'active_children', 'Pipe', 'connection', 'dict', 'list', |
| 1834 |
'Namespace', 'JoinableQueue' |
| 1835 |
))) |
| 1836 |
|
| 1837 |
testcases_threads = create_test_cases(ThreadsMixin, type='threads') |
| 1838 |
globals().update(testcases_threads) |
| 1839 |
|
| 1840 |
|
| 1841 |
class OtherTest(unittest.TestCase): |
| 1842 |
# TODO: add more tests for deliver/answer challenge. |
| 1843 |
def test_deliver_challenge_auth_failure(self): |
| 1844 |
|
| 1845 |
class _FakeConnection(object): |
| 1846 |
|
| 1847 |
def recv_bytes(self, size): |
| 1848 |
return bytes('something bogus') |
| 1849 |
|
| 1850 |
def send_bytes(self, data): |
| 1851 |
pass |
| 1852 |
self.assertRaises(billiard.AuthenticationError, |
| 1853 |
billiard.connection.deliver_challenge, |
| 1854 |
_FakeConnection(), bytes('abc')) |
| 1855 |
|
| 1856 |
def test_answer_challenge_auth_failure(self): |
| 1857 |
|
| 1858 |
class _FakeConnection: |
| 1859 |
|
| 1860 |
def __init__(self): |
| 1861 |
self.count = 0 |
| 1862 |
|
| 1863 |
def recv_bytes(self, size): |
| 1864 |
self.count += 1 |
| 1865 |
if self.count == 1: |
| 1866 |
return billiard.connection.CHALLENGE |
| 1867 |
elif self.count == 2: |
| 1868 |
return bytes('something bogus') |
| 1869 |
return bytes('') |
| 1870 |
|
| 1871 |
def send_bytes(self, data): |
| 1872 |
pass |
| 1873 |
self.assertRaises(billiard.AuthenticationError, |
| 1874 |
billiard.connection.answer_challenge, |
| 1875 |
_FakeConnection(), bytes('abc')) |
| 1876 |
|
| 1877 |
|
| 1878 |
def initializer(ns): |
| 1879 |
ns.test += 1 |
| 1880 |
|
| 1881 |
|
| 1882 |
class TestInitializers(unittest.TestCase): |
| 1883 |
"""Test Manager.start()/Pool.__init__() initializer feature |
| 1884 |
|
| 1885 |
- see issue 5585 |
| 1886 |
|
| 1887 |
""" |
| 1888 |
def setUp(self): |
| 1889 |
self.mgr = billiard.Manager() |
| 1890 |
self.ns = self.mgr.Namespace() |
| 1891 |
self.ns.test = 0 |
| 1892 |
|
| 1893 |
def tearDown(self): |
| 1894 |
self.mgr.shutdown() |
| 1895 |
|
| 1896 |
def test_manager_initializer(self): |
| 1897 |
m = billiard.managers.SyncManager() |
| 1898 |
self.assertRaises(TypeError, m.start, 1) |
| 1899 |
m.start(initializer, (self.ns,)) |
| 1900 |
self.assertEqual(self.ns.test, 1) |
| 1901 |
m.shutdown() |
| 1902 |
|
| 1903 |
def test_pool_initializer(self): |
| 1904 |
self.assertRaises(TypeError, billiard.Pool, initializer=1) |
| 1905 |
p = billiard.Pool(1, initializer, (self.ns,)) |
| 1906 |
p.close() |
| 1907 |
p.join() |
| 1908 |
self.assertEqual(self.ns.test, 1) |
| 1909 |
|
| 1910 |
|
| 1911 |
def _ThisSubProcess(q): |
| 1912 |
try: |
| 1913 |
q.get(block=False) |
| 1914 |
except Queue.Empty: |
| 1915 |
pass |
| 1916 |
|
| 1917 |
|
| 1918 |
def _TestProcess(q): |
| 1919 |
"""Issue 5155, 5313, 5331: Test process in processes |
| 1920 |
|
| 1921 |
Verifies os.close(sys.stdin.fileno) vs. sys.stdin.close() behavior |
| 1922 |
|
| 1923 |
""" |
| 1924 |
queue = billiard.Queue() |
| 1925 |
subProc = billiard.Process(target=_ThisSubProcess, args=(queue,)) |
| 1926 |
subProc.start() |
| 1927 |
subProc.join() |
| 1928 |
|
| 1929 |
|
| 1930 |
def _afunc(x): |
| 1931 |
return x * x |
| 1932 |
|
| 1933 |
|
| 1934 |
def pool_in_process(): |
| 1935 |
pool = billiard.Pool(processes=4) |
| 1936 |
pool.map(_afunc, [1, 2, 3, 4, 5, 6, 7]) |
| 1937 |
|
| 1938 |
|
| 1939 |
class _file_like: |
| 1940 |
def __init__(self, delegate): |
| 1941 |
self._delegate = delegate |
| 1942 |
self._pid = None |
| 1943 |
|
| 1944 |
@property |
| 1945 |
def cache(self): |
| 1946 |
pid = os.getpid() |
| 1947 |
# There are no race conditions since fork keeps only the running thread |
| 1948 |
if pid != self._pid: |
| 1949 |
self._pid = pid |
| 1950 |
self._cache = [] |
| 1951 |
return self._cache |
| 1952 |
|
| 1953 |
def write(self, data): |
| 1954 |
self.cache.append(data) |
| 1955 |
|
| 1956 |
def flush(self): |
| 1957 |
self._delegate.write(''.join(self.cache)) |
| 1958 |
self._cache = [] |
| 1959 |
|
| 1960 |
|
| 1961 |
class TestStdinBadfiledescriptor(unittest.TestCase): |
| 1962 |
|
| 1963 |
def test_queue_in_process(self): |
| 1964 |
queue = billiard.Queue() |
| 1965 |
proc = billiard.Process(target=_TestProcess, args=(queue,)) |
| 1966 |
proc.start() |
| 1967 |
proc.join() |
| 1968 |
|
| 1969 |
def test_pool_in_process(self): |
| 1970 |
p = billiard.Process(target=pool_in_process) |
| 1971 |
p.start() |
| 1972 |
p.join() |
| 1973 |
|
| 1974 |
def test_flushing(self): |
| 1975 |
sio = StringIO() |
| 1976 |
flike = _file_like(sio) |
| 1977 |
flike.write('foo') |
| 1978 |
proc = billiard.Process(target=lambda: flike.flush()) |
| 1979 |
self.assertTrue(proc) |
| 1980 |
flike.flush() |
| 1981 |
assert sio.getvalue() == 'foo' |
| 1982 |
|
| 1983 |
testcases_other = [OtherTest, TestInvalidHandle, TestInitializers, |
| 1984 |
TestStdinBadfiledescriptor] |
| 1985 |
|
| 1986 |
|
| 1987 |
def test_main(run=None): |
| 1988 |
if sys.platform.startswith("linux"): |
| 1989 |
try: |
| 1990 |
billiard.RLock() |
| 1991 |
except OSError: |
| 1992 |
raise pytest.skip("OSError raises on RLock creation, see issue 3111!") |
| 1993 |
|
| 1994 |
if run is None: |
| 1995 |
from test.test_support import run_unittest as run |
| 1996 |
|
| 1997 |
util.get_temp_dir() # creates temp directory for use by all processes |
| 1998 |
|
| 1999 |
billiard.get_logger().setLevel(LOG_LEVEL) |
| 2000 |
|
| 2001 |
ProcessesMixin.pool = billiard.Pool(4) |
| 2002 |
ThreadsMixin.pool = billiard.dummy.Pool(4) |
| 2003 |
ManagerMixin.manager.__init__() |
| 2004 |
ManagerMixin.manager.start() |
| 2005 |
ManagerMixin.pool = ManagerMixin.manager.Pool(4) |
| 2006 |
|
| 2007 |
testcases = ( |
| 2008 |
sorted(testcases_processes.values(), key=lambda tc: tc.__name__) + |
| 2009 |
sorted(testcases_threads.values(), key=lambda tc: tc.__name__) + |
| 2010 |
sorted(testcases_manager.values(), key=lambda tc: tc.__name__) + |
| 2011 |
testcases_other |
| 2012 |
) |
| 2013 |
|
| 2014 |
loadTestsFromTestCase = unittest.defaultTestLoader.loadTestsFromTestCase |
| 2015 |
suite = unittest.TestSuite(loadTestsFromTestCase(tc) for tc in testcases) |
| 2016 |
# (ncoghlan): Whether or not sys.exc_clear is executed by the threading |
| 2017 |
# module during these tests is at least platform dependent and possibly |
| 2018 |
# non-deterministic on any given platform. So we don't mind if the listed |
| 2019 |
# warnings aren't actually raised. |
| 2020 |
with test_support.check_py3k_warnings( |
| 2021 |
(".+__(get|set)slice__ has been removed", DeprecationWarning), |
| 2022 |
(r"sys.exc_clear\(\) not supported", DeprecationWarning), |
| 2023 |
quiet=True): |
| 2024 |
run(suite) |
| 2025 |
|
| 2026 |
ThreadsMixin.pool.terminate() |
| 2027 |
ProcessesMixin.pool.terminate() |
| 2028 |
ManagerMixin.pool.terminate() |
| 2029 |
ManagerMixin.manager.shutdown() |
| 2030 |
|
| 2031 |
del ProcessesMixin.pool, ThreadsMixin.pool, ManagerMixin.pool |
| 2032 |
|
| 2033 |
|
| 2034 |
def main(): |
| 2035 |
test_main(unittest.TextTestRunner(verbosity=2).run) |
| 2036 |
|
| 2037 |
if __name__ == '__main__': |
| 2038 |
main() |