| 1 |
"""Supporting definitions for the Python regression tests.""" |
| 2 |
|
| 3 |
if __name__ != 'test.support': |
| 4 |
raise ImportError('test.support must be imported from the test package') |
| 5 |
|
| 6 |
import contextlib |
| 7 |
import errno |
| 8 |
import fnmatch |
| 9 |
import functools |
| 10 |
import gc |
| 11 |
import socket |
| 12 |
import stat |
| 13 |
import sys |
| 14 |
import os |
| 15 |
import platform |
| 16 |
import shutil |
| 17 |
import warnings |
| 18 |
import unittest |
| 19 |
import importlib |
| 20 |
import UserDict |
| 21 |
import re |
| 22 |
import time |
| 23 |
import struct |
| 24 |
import sysconfig |
| 25 |
import types |
| 26 |
|
| 27 |
try: |
| 28 |
import thread |
| 29 |
except ImportError: |
| 30 |
thread = None |
| 31 |
|
| 32 |
__all__ = ["Error", "TestFailed", "TestDidNotRun", "ResourceDenied", "import_module", |
| 33 |
"verbose", "use_resources", "max_memuse", "record_original_stdout", |
| 34 |
"get_original_stdout", "unload", "unlink", "rmtree", "forget", |
| 35 |
"is_resource_enabled", "requires", "requires_mac_ver", |
| 36 |
"find_unused_port", "bind_port", |
| 37 |
"fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ", |
| 38 |
"SAVEDCWD", "temp_cwd", "findfile", "sortdict", "check_syntax_error", |
| 39 |
"open_urlresource", "check_warnings", "check_py3k_warnings", |
| 40 |
"CleanImport", "EnvironmentVarGuard", "captured_output", |
| 41 |
"captured_stdout", "TransientResource", "transient_internet", |
| 42 |
"run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest", |
| 43 |
"BasicTestRunner", "run_unittest", "run_doctest", "threading_setup", |
| 44 |
"threading_cleanup", "reap_threads", "start_threads", "cpython_only", |
| 45 |
"check_impl_detail", "get_attribute", "py3k_bytes", |
| 46 |
"import_fresh_module", "threading_cleanup", "reap_children", |
| 47 |
"strip_python_stderr", "IPV6_ENABLED", "run_with_tz", |
| 48 |
"SuppressCrashReport"] |
| 49 |
|
| 50 |
class Error(Exception): |
| 51 |
"""Base class for regression test exceptions.""" |
| 52 |
|
| 53 |
class TestFailed(Error): |
| 54 |
"""Test failed.""" |
| 55 |
|
| 56 |
class TestDidNotRun(Error): |
| 57 |
"""Test did not run any subtests.""" |
| 58 |
|
| 59 |
class ResourceDenied(unittest.SkipTest): |
| 60 |
"""Test skipped because it requested a disallowed resource. |
| 61 |
|
| 62 |
This is raised when a test calls requires() for a resource that |
| 63 |
has not been enabled. It is used to distinguish between expected |
| 64 |
and unexpected skips. |
| 65 |
""" |
| 66 |
|
| 67 |
@contextlib.contextmanager |
| 68 |
def _ignore_deprecated_imports(ignore=True): |
| 69 |
"""Context manager to suppress package and module deprecation |
| 70 |
warnings when importing them. |
| 71 |
|
| 72 |
If ignore is False, this context manager has no effect.""" |
| 73 |
if ignore: |
| 74 |
with warnings.catch_warnings(): |
| 75 |
warnings.filterwarnings("ignore", ".+ (module|package)", |
| 76 |
DeprecationWarning) |
| 77 |
yield |
| 78 |
else: |
| 79 |
yield |
| 80 |
|
| 81 |
|
| 82 |
def import_module(name, deprecated=False): |
| 83 |
"""Import and return the module to be tested, raising SkipTest if |
| 84 |
it is not available. |
| 85 |
|
| 86 |
If deprecated is True, any module or package deprecation messages |
| 87 |
will be suppressed.""" |
| 88 |
with _ignore_deprecated_imports(deprecated): |
| 89 |
try: |
| 90 |
return importlib.import_module(name) |
| 91 |
except ImportError, msg: |
| 92 |
raise unittest.SkipTest(str(msg)) |
| 93 |
|
| 94 |
|
| 95 |
def _save_and_remove_module(name, orig_modules): |
| 96 |
"""Helper function to save and remove a module from sys.modules |
| 97 |
|
| 98 |
Raise ImportError if the module can't be imported.""" |
| 99 |
|
| 100 |
if name not in sys.modules: |
| 101 |
__import__(name) |
| 102 |
del sys.modules[name] |
| 103 |
for modname in list(sys.modules): |
| 104 |
if modname == name or modname.startswith(name + '.'): |
| 105 |
orig_modules[modname] = sys.modules[modname] |
| 106 |
del sys.modules[modname] |
| 107 |
|
| 108 |
def _save_and_block_module(name, orig_modules): |
| 109 |
"""Helper function to save and block a module in sys.modules |
| 110 |
|
| 111 |
Return True if the module was in sys.modules, False otherwise.""" |
| 112 |
saved = True |
| 113 |
try: |
| 114 |
orig_modules[name] = sys.modules[name] |
| 115 |
except KeyError: |
| 116 |
saved = False |
| 117 |
sys.modules[name] = None |
| 118 |
return saved |
| 119 |
|
| 120 |
|
| 121 |
def import_fresh_module(name, fresh=(), blocked=(), deprecated=False): |
| 122 |
"""Imports and returns a module, deliberately bypassing the sys.modules cache |
| 123 |
and importing a fresh copy of the module. Once the import is complete, |
| 124 |
the sys.modules cache is restored to its original state. |
| 125 |
|
| 126 |
Modules named in fresh are also imported anew if needed by the import. |
| 127 |
If one of these modules can't be imported, None is returned. |
| 128 |
|
| 129 |
Importing of modules named in blocked is prevented while the fresh import |
| 130 |
takes place. |
| 131 |
|
| 132 |
If deprecated is True, any module or package deprecation messages |
| 133 |
will be suppressed.""" |
| 134 |
|
| 135 |
|
| 136 |
with _ignore_deprecated_imports(deprecated): |
| 137 |
|
| 138 |
|
| 139 |
orig_modules = {} |
| 140 |
names_to_remove = [] |
| 141 |
_save_and_remove_module(name, orig_modules) |
| 142 |
try: |
| 143 |
for fresh_name in fresh: |
| 144 |
_save_and_remove_module(fresh_name, orig_modules) |
| 145 |
for blocked_name in blocked: |
| 146 |
if not _save_and_block_module(blocked_name, orig_modules): |
| 147 |
names_to_remove.append(blocked_name) |
| 148 |
fresh_module = importlib.import_module(name) |
| 149 |
except ImportError: |
| 150 |
fresh_module = None |
| 151 |
finally: |
| 152 |
for orig_name, module in orig_modules.items(): |
| 153 |
sys.modules[orig_name] = module |
| 154 |
for name_to_remove in names_to_remove: |
| 155 |
del sys.modules[name_to_remove] |
| 156 |
return fresh_module |
| 157 |
|
| 158 |
|
| 159 |
def get_attribute(obj, name): |
| 160 |
"""Get an attribute, raising SkipTest if AttributeError is raised.""" |
| 161 |
try: |
| 162 |
attribute = getattr(obj, name) |
| 163 |
except AttributeError: |
| 164 |
if isinstance(obj, types.ModuleType): |
| 165 |
msg = "module %r has no attribute %r" % (obj.__name__, name) |
| 166 |
elif isinstance(obj, types.ClassType): |
| 167 |
msg = "class %s has no attribute %r" % (obj.__name__, name) |
| 168 |
elif isinstance(obj, types.InstanceType): |
| 169 |
msg = "%s instance has no attribute %r" % (obj.__class__.__name__, name) |
| 170 |
elif isinstance(obj, type): |
| 171 |
msg = "type object %r has no attribute %r" % (obj.__name__, name) |
| 172 |
else: |
| 173 |
msg = "%r object has no attribute %r" % (type(obj).__name__, name) |
| 174 |
raise unittest.SkipTest(msg) |
| 175 |
else: |
| 176 |
return attribute |
| 177 |
|
| 178 |
|
| 179 |
verbose = 1 |
| 180 |
use_resources = None |
| 181 |
max_memuse = 0 |
| 182 |
|
| 183 |
real_max_memuse = 0 |
| 184 |
failfast = False |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
_original_stdout = None |
| 190 |
def record_original_stdout(stdout): |
| 191 |
global _original_stdout |
| 192 |
_original_stdout = stdout |
| 193 |
|
| 194 |
def get_original_stdout(): |
| 195 |
return _original_stdout or sys.stdout |
| 196 |
|
| 197 |
def unload(name): |
| 198 |
try: |
| 199 |
del sys.modules[name] |
| 200 |
except KeyError: |
| 201 |
pass |
| 202 |
|
| 203 |
def _force_run(path, func, *args): |
| 204 |
try: |
| 205 |
return func(*args) |
| 206 |
except EnvironmentError as err: |
| 207 |
if verbose >= 2: |
| 208 |
print('%s: %s' % (err.__class__.__name__, err)) |
| 209 |
print('re-run %s%r' % (func.__name__, args)) |
| 210 |
os.chmod(path, stat.S_IRWXU) |
| 211 |
return func(*args) |
| 212 |
|
| 213 |
if sys.platform.startswith("win"): |
| 214 |
def _waitfor(func, pathname, waitall=False): |
| 215 |
|
| 216 |
func(pathname) |
| 217 |
|
| 218 |
if waitall: |
| 219 |
dirname = pathname |
| 220 |
else: |
| 221 |
dirname, name = os.path.split(pathname) |
| 222 |
dirname = dirname or '.' |
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
timeout = 0.001 |
| 230 |
while timeout < 1.0: |
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
L = os.listdir(dirname) |
| 239 |
if not (L if waitall else name in L): |
| 240 |
return |
| 241 |
|
| 242 |
time.sleep(timeout) |
| 243 |
timeout *= 2 |
| 244 |
warnings.warn('tests may fail, delete still pending for ' + pathname, |
| 245 |
RuntimeWarning, stacklevel=4) |
| 246 |
|
| 247 |
def _unlink(filename): |
| 248 |
_waitfor(os.unlink, filename) |
| 249 |
|
| 250 |
def _rmdir(dirname): |
| 251 |
_waitfor(os.rmdir, dirname) |
| 252 |
|
| 253 |
def _rmtree(path): |
| 254 |
def _rmtree_inner(path): |
| 255 |
for name in _force_run(path, os.listdir, path): |
| 256 |
fullname = os.path.join(path, name) |
| 257 |
if os.path.isdir(fullname): |
| 258 |
_waitfor(_rmtree_inner, fullname, waitall=True) |
| 259 |
_force_run(fullname, os.rmdir, fullname) |
| 260 |
else: |
| 261 |
_force_run(fullname, os.unlink, fullname) |
| 262 |
_waitfor(_rmtree_inner, path, waitall=True) |
| 263 |
_waitfor(lambda p: _force_run(p, os.rmdir, p), path) |
| 264 |
else: |
| 265 |
_unlink = os.unlink |
| 266 |
_rmdir = os.rmdir |
| 267 |
|
| 268 |
def _rmtree(path): |
| 269 |
try: |
| 270 |
shutil.rmtree(path) |
| 271 |
return |
| 272 |
except EnvironmentError: |
| 273 |
pass |
| 274 |
|
| 275 |
def _rmtree_inner(path): |
| 276 |
for name in _force_run(path, os.listdir, path): |
| 277 |
fullname = os.path.join(path, name) |
| 278 |
try: |
| 279 |
mode = os.lstat(fullname).st_mode |
| 280 |
except EnvironmentError: |
| 281 |
mode = 0 |
| 282 |
if stat.S_ISDIR(mode): |
| 283 |
_rmtree_inner(fullname) |
| 284 |
_force_run(path, os.rmdir, fullname) |
| 285 |
else: |
| 286 |
_force_run(path, os.unlink, fullname) |
| 287 |
_rmtree_inner(path) |
| 288 |
os.rmdir(path) |
| 289 |
|
| 290 |
def unlink(filename): |
| 291 |
try: |
| 292 |
_unlink(filename) |
| 293 |
except OSError as exc: |
| 294 |
if exc.errno not in (errno.ENOENT, errno.ENOTDIR): |
| 295 |
raise |
| 296 |
|
| 297 |
def rmdir(dirname): |
| 298 |
try: |
| 299 |
_rmdir(dirname) |
| 300 |
except OSError as error: |
| 301 |
|
| 302 |
if error.errno != errno.ENOENT: |
| 303 |
raise |
| 304 |
|
| 305 |
def rmtree(path): |
| 306 |
try: |
| 307 |
_rmtree(path) |
| 308 |
except OSError, e: |
| 309 |
|
| 310 |
if e.errno not in (errno.ENOENT, errno.ESRCH): |
| 311 |
raise |
| 312 |
|
| 313 |
def forget(modname): |
| 314 |
'''"Forget" a module was ever imported by removing it from sys.modules and |
| 315 |
deleting any .pyc and .pyo files.''' |
| 316 |
unload(modname) |
| 317 |
for dirname in sys.path: |
| 318 |
unlink(os.path.join(dirname, modname + os.extsep + 'pyc')) |
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) |
| 323 |
|
| 324 |
|
| 325 |
def _is_gui_available(): |
| 326 |
if hasattr(_is_gui_available, 'result'): |
| 327 |
return _is_gui_available.result |
| 328 |
reason = None |
| 329 |
if sys.platform.startswith('win'): |
| 330 |
|
| 331 |
|
| 332 |
import ctypes |
| 333 |
import ctypes.wintypes |
| 334 |
UOI_FLAGS = 1 |
| 335 |
WSF_VISIBLE = 0x0001 |
| 336 |
class USEROBJECTFLAGS(ctypes.Structure): |
| 337 |
_fields_ = [("fInherit", ctypes.wintypes.BOOL), |
| 338 |
("fReserved", ctypes.wintypes.BOOL), |
| 339 |
("dwFlags", ctypes.wintypes.DWORD)] |
| 340 |
dll = ctypes.windll.user32 |
| 341 |
h = dll.GetProcessWindowStation() |
| 342 |
if not h: |
| 343 |
raise ctypes.WinError() |
| 344 |
uof = USEROBJECTFLAGS() |
| 345 |
needed = ctypes.wintypes.DWORD() |
| 346 |
res = dll.GetUserObjectInformationW(h, |
| 347 |
UOI_FLAGS, |
| 348 |
ctypes.byref(uof), |
| 349 |
ctypes.sizeof(uof), |
| 350 |
ctypes.byref(needed)) |
| 351 |
if not res: |
| 352 |
raise ctypes.WinError() |
| 353 |
if not bool(uof.dwFlags & WSF_VISIBLE): |
| 354 |
reason = "gui not available (WSF_VISIBLE flag not set)" |
| 355 |
elif sys.platform == 'darwin': |
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
from ctypes import cdll, c_int, pointer, Structure |
| 363 |
from ctypes.util import find_library |
| 364 |
|
| 365 |
app_services = cdll.LoadLibrary(find_library("ApplicationServices")) |
| 366 |
|
| 367 |
if app_services.CGMainDisplayID() == 0: |
| 368 |
reason = "gui tests cannot run without OS X window manager" |
| 369 |
else: |
| 370 |
class ProcessSerialNumber(Structure): |
| 371 |
_fields_ = [("highLongOfPSN", c_int), |
| 372 |
("lowLongOfPSN", c_int)] |
| 373 |
psn = ProcessSerialNumber() |
| 374 |
psn_p = pointer(psn) |
| 375 |
if ( (app_services.GetCurrentProcess(psn_p) < 0) or |
| 376 |
(app_services.SetFrontProcess(psn_p) < 0) ): |
| 377 |
reason = "cannot run without OS X gui process" |
| 378 |
|
| 379 |
|
| 380 |
if not reason: |
| 381 |
try: |
| 382 |
from Tkinter import Tk |
| 383 |
root = Tk() |
| 384 |
root.withdraw() |
| 385 |
root.update() |
| 386 |
root.destroy() |
| 387 |
except Exception as e: |
| 388 |
err_string = str(e) |
| 389 |
if len(err_string) > 50: |
| 390 |
err_string = err_string[:50] + ' [...]' |
| 391 |
reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__, |
| 392 |
err_string) |
| 393 |
|
| 394 |
_is_gui_available.reason = reason |
| 395 |
_is_gui_available.result = not reason |
| 396 |
|
| 397 |
return _is_gui_available.result |
| 398 |
|
| 399 |
def is_resource_enabled(resource): |
| 400 |
"""Test whether a resource is enabled. |
| 401 |
|
| 402 |
Known resources are set by regrtest.py. If not running under regrtest.py, |
| 403 |
all resources are assumed enabled unless use_resources has been set. |
| 404 |
""" |
| 405 |
return use_resources is None or resource in use_resources |
| 406 |
|
| 407 |
def requires(resource, msg=None): |
| 408 |
"""Raise ResourceDenied if the specified resource is not available.""" |
| 409 |
if not is_resource_enabled(resource): |
| 410 |
if msg is None: |
| 411 |
msg = "Use of the `%s' resource not enabled" % resource |
| 412 |
raise ResourceDenied(msg) |
| 413 |
if resource == 'gui' and not _is_gui_available(): |
| 414 |
raise ResourceDenied(_is_gui_available.reason) |
| 415 |
|
| 416 |
def requires_mac_ver(*min_version): |
| 417 |
"""Decorator raising SkipTest if the OS is Mac OS X and the OS X |
| 418 |
version if less than min_version. |
| 419 |
|
| 420 |
For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version |
| 421 |
is lesser than 10.5. |
| 422 |
""" |
| 423 |
def decorator(func): |
| 424 |
@functools.wraps(func) |
| 425 |
def wrapper(*args, **kw): |
| 426 |
if sys.platform == 'darwin': |
| 427 |
version_txt = platform.mac_ver()[0] |
| 428 |
try: |
| 429 |
version = tuple(map(int, version_txt.split('.'))) |
| 430 |
except ValueError: |
| 431 |
pass |
| 432 |
else: |
| 433 |
if version < min_version: |
| 434 |
min_version_txt = '.'.join(map(str, min_version)) |
| 435 |
raise unittest.SkipTest( |
| 436 |
"Mac OS X %s or higher required, not %s" |
| 437 |
% (min_version_txt, version_txt)) |
| 438 |
return func(*args, **kw) |
| 439 |
wrapper.min_version = min_version |
| 440 |
return wrapper |
| 441 |
return decorator |
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
HOST = "127.0.0.1" |
| 447 |
HOSTv6 = "::1" |
| 448 |
|
| 449 |
|
| 450 |
def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): |
| 451 |
"""Returns an unused port that should be suitable for binding. This is |
| 452 |
achieved by creating a temporary socket with the same family and type as |
| 453 |
the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to |
| 454 |
the specified host address (defaults to 0.0.0.0) with the port set to 0, |
| 455 |
eliciting an unused ephemeral port from the OS. The temporary socket is |
| 456 |
then closed and deleted, and the ephemeral port is returned. |
| 457 |
|
| 458 |
Either this method or bind_port() should be used for any tests where a |
| 459 |
server socket needs to be bound to a particular port for the duration of |
| 460 |
the test. Which one to use depends on whether the calling code is creating |
| 461 |
a python socket, or if an unused port needs to be provided in a constructor |
| 462 |
or passed to an external program (i.e. the -accept argument to openssl's |
| 463 |
s_server mode). Always prefer bind_port() over find_unused_port() where |
| 464 |
possible. Hard coded ports should *NEVER* be used. As soon as a server |
| 465 |
socket is bound to a hard coded port, the ability to run multiple instances |
| 466 |
of the test simultaneously on the same host is compromised, which makes the |
| 467 |
test a ticking time bomb in a buildbot environment. On Unix buildbots, this |
| 468 |
may simply manifest as a failed test, which can be recovered from without |
| 469 |
intervention in most cases, but on Windows, the entire python process can |
| 470 |
completely and utterly wedge, requiring someone to log in to the buildbot |
| 471 |
and manually kill the affected process. |
| 472 |
|
| 473 |
(This is easy to reproduce on Windows, unfortunately, and can be traced to |
| 474 |
the SO_REUSEADDR socket option having different semantics on Windows versus |
| 475 |
Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, |
| 476 |
listen and then accept connections on identical host/ports. An EADDRINUSE |
| 477 |
socket.error will be raised at some point (depending on the platform and |
| 478 |
the order bind and listen were called on each socket). |
| 479 |
|
| 480 |
However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE |
| 481 |
will ever be raised when attempting to bind two identical host/ports. When |
| 482 |
accept() is called on each socket, the second caller's process will steal |
| 483 |
the port from the first caller, leaving them both in an awkwardly wedged |
| 484 |
state where they'll no longer respond to any signals or graceful kills, and |
| 485 |
must be forcibly killed via OpenProcess()/TerminateProcess(). |
| 486 |
|
| 487 |
The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option |
| 488 |
instead of SO_REUSEADDR, which effectively affords the same semantics as |
| 489 |
SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open |
| 490 |
Source world compared to Windows ones, this is a common mistake. A quick |
| 491 |
look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when |
| 492 |
openssl.exe is called with the 's_server' option, for example. See |
| 493 |
http://bugs.python.org/issue2550 for more info. The following site also |
| 494 |
has a very thorough description about the implications of both REUSEADDR |
| 495 |
and EXCLUSIVEADDRUSE on Windows: |
| 496 |
http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) |
| 497 |
|
| 498 |
XXX: although this approach is a vast improvement on previous attempts to |
| 499 |
elicit unused ports, it rests heavily on the assumption that the ephemeral |
| 500 |
port returned to us by the OS won't immediately be dished back out to some |
| 501 |
other process when we close and delete our temporary socket but before our |
| 502 |
calling code has a chance to bind the returned port. We can deal with this |
| 503 |
issue if/when we come across it.""" |
| 504 |
tempsock = socket.socket(family, socktype) |
| 505 |
port = bind_port(tempsock) |
| 506 |
tempsock.close() |
| 507 |
del tempsock |
| 508 |
return port |
| 509 |
|
| 510 |
def bind_port(sock, host=HOST): |
| 511 |
"""Bind the socket to a free port and return the port number. Relies on |
| 512 |
ephemeral ports in order to ensure we are using an unbound port. This is |
| 513 |
important as many tests may be running simultaneously, especially in a |
| 514 |
buildbot environment. This method raises an exception if the sock.family |
| 515 |
is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR |
| 516 |
or SO_REUSEPORT set on it. Tests should *never* set these socket options |
| 517 |
for TCP/IP sockets. The only case for setting these options is testing |
| 518 |
multicasting via multiple UDP sockets. |
| 519 |
|
| 520 |
Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. |
| 521 |
on Windows), it will be set on the socket. This will prevent anyone else |
| 522 |
from bind()'ing to our host/port for the duration of the test. |
| 523 |
""" |
| 524 |
if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: |
| 525 |
if hasattr(socket, 'SO_REUSEADDR'): |
| 526 |
if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: |
| 527 |
raise TestFailed("tests should never set the SO_REUSEADDR " \ |
| 528 |
"socket option on TCP/IP sockets!") |
| 529 |
if hasattr(socket, 'SO_REUSEPORT'): |
| 530 |
try: |
| 531 |
if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: |
| 532 |
raise TestFailed("tests should never set the SO_REUSEPORT " \ |
| 533 |
"socket option on TCP/IP sockets!") |
| 534 |
except EnvironmentError: |
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
pass |
| 539 |
if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): |
| 540 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) |
| 541 |
|
| 542 |
sock.bind((host, 0)) |
| 543 |
port = sock.getsockname()[1] |
| 544 |
return port |
| 545 |
|
| 546 |
def _is_ipv6_enabled(): |
| 547 |
"""Check whether IPv6 is enabled on this host.""" |
| 548 |
if socket.has_ipv6: |
| 549 |
sock = None |
| 550 |
try: |
| 551 |
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) |
| 552 |
sock.bind((HOSTv6, 0)) |
| 553 |
return True |
| 554 |
except socket.error: |
| 555 |
pass |
| 556 |
finally: |
| 557 |
if sock: |
| 558 |
sock.close() |
| 559 |
return False |
| 560 |
|
| 561 |
IPV6_ENABLED = _is_ipv6_enabled() |
| 562 |
|
| 563 |
def system_must_validate_cert(f): |
| 564 |
"""Skip the test on TLS certificate validation failures.""" |
| 565 |
@functools.wraps(f) |
| 566 |
def dec(*args, **kwargs): |
| 567 |
try: |
| 568 |
f(*args, **kwargs) |
| 569 |
except IOError as e: |
| 570 |
if "CERTIFICATE_VERIFY_FAILED" in str(e): |
| 571 |
raise unittest.SkipTest("system does not contain " |
| 572 |
"necessary certificates") |
| 573 |
raise |
| 574 |
return dec |
| 575 |
|
| 576 |
FUZZ = 1e-6 |
| 577 |
|
| 578 |
def fcmp(x, y): |
| 579 |
if isinstance(x, float) or isinstance(y, float): |
| 580 |
try: |
| 581 |
fuzz = (abs(x) + abs(y)) * FUZZ |
| 582 |
if abs(x-y) <= fuzz: |
| 583 |
return 0 |
| 584 |
except: |
| 585 |
pass |
| 586 |
elif type(x) == type(y) and isinstance(x, (tuple, list)): |
| 587 |
for i in range(min(len(x), len(y))): |
| 588 |
outcome = fcmp(x[i], y[i]) |
| 589 |
if outcome != 0: |
| 590 |
return outcome |
| 591 |
return (len(x) > len(y)) - (len(x) < len(y)) |
| 592 |
return (x > y) - (x < y) |
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1 |
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1 |
| 608 |
|
| 609 |
is_jython = sys.platform.startswith('java') |
| 610 |
|
| 611 |
try: |
| 612 |
unicode |
| 613 |
have_unicode = True |
| 614 |
except NameError: |
| 615 |
have_unicode = False |
| 616 |
|
| 617 |
requires_unicode = unittest.skipUnless(have_unicode, 'no unicode support') |
| 618 |
|
| 619 |
def u(s): |
| 620 |
return unicode(s, 'unicode-escape') |
| 621 |
|
| 622 |
|
| 623 |
|
| 624 |
FS_NONASCII = None |
| 625 |
if have_unicode: |
| 626 |
for character in ( |
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
unichr(0x00E6), |
| 633 |
|
| 634 |
unichr(0x0130), |
| 635 |
|
| 636 |
unichr(0x0141), |
| 637 |
|
| 638 |
unichr(0x03C6), |
| 639 |
|
| 640 |
unichr(0x041A), |
| 641 |
|
| 642 |
unichr(0x05D0), |
| 643 |
|
| 644 |
unichr(0x060C), |
| 645 |
|
| 646 |
unichr(0x062A), |
| 647 |
|
| 648 |
unichr(0x0E01), |
| 649 |
|
| 650 |
|
| 651 |
|
| 652 |
|
| 653 |
|
| 654 |
|
| 655 |
unichr(0x00A0), |
| 656 |
|
| 657 |
unichr(0x20AC), |
| 658 |
): |
| 659 |
try: |
| 660 |
|
| 661 |
|
| 662 |
if character.encode(sys.getfilesystemencoding())\ |
| 663 |
.decode(sys.getfilesystemencoding())\ |
| 664 |
!= character: |
| 665 |
raise UnicodeError |
| 666 |
except UnicodeError: |
| 667 |
pass |
| 668 |
else: |
| 669 |
FS_NONASCII = character |
| 670 |
break |
| 671 |
|
| 672 |
|
| 673 |
if os.name == 'java': |
| 674 |
|
| 675 |
TESTFN = '$test' |
| 676 |
elif os.name == 'riscos': |
| 677 |
TESTFN = 'testfile' |
| 678 |
else: |
| 679 |
TESTFN = '@test' |
| 680 |
|
| 681 |
if have_unicode: |
| 682 |
|
| 683 |
|
| 684 |
|
| 685 |
if isinstance('', unicode): |
| 686 |
|
| 687 |
|
| 688 |
TESTFN_UNICODE = "@test-\xe0\xf2" |
| 689 |
else: |
| 690 |
|
| 691 |
TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1") |
| 692 |
TESTFN_ENCODING = sys.getfilesystemencoding() |
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
if (not hasattr(sys, "getwindowsversion") or |
| 698 |
sys.getwindowsversion()[3] < 2): |
| 699 |
TESTFN_UNENCODABLE = None |
| 700 |
else: |
| 701 |
|
| 702 |
TESTFN_UNENCODABLE = eval('u"@test-\u5171\u6709\u3055\u308c\u308b"') |
| 703 |
try: |
| 704 |
|
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
TESTFN_UNENCODABLE.encode("Latin1") |
| 710 |
except UnicodeEncodeError: |
| 711 |
pass |
| 712 |
else: |
| 713 |
print \ |
| 714 |
'WARNING: The filename %r CAN be encoded by the filesystem. ' \ |
| 715 |
'Unicode filename tests may not be effective' \ |
| 716 |
% TESTFN_UNENCODABLE |
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid()) |
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
TEST_HTTP_URL = "http://www.pythontest.net" |
| 726 |
|
| 727 |
|
| 728 |
SAVEDCWD = os.getcwd() |
| 729 |
|
| 730 |
@contextlib.contextmanager |
| 731 |
def temp_dir(path=None, quiet=False): |
| 732 |
"""Return a context manager that creates a temporary directory. |
| 733 |
|
| 734 |
Arguments: |
| 735 |
|
| 736 |
path: the directory to create temporarily. If omitted or None, |
| 737 |
defaults to creating a temporary directory using tempfile.mkdtemp. |
| 738 |
|
| 739 |
quiet: if False (the default), the context manager raises an exception |
| 740 |
on error. Otherwise, if the path is specified and cannot be |
| 741 |
created, only a warning is issued. |
| 742 |
|
| 743 |
""" |
| 744 |
dir_created = False |
| 745 |
if path is None: |
| 746 |
import tempfile |
| 747 |
path = tempfile.mkdtemp() |
| 748 |
dir_created = True |
| 749 |
path = os.path.realpath(path) |
| 750 |
else: |
| 751 |
if (have_unicode and isinstance(path, unicode) and |
| 752 |
not os.path.supports_unicode_filenames): |
| 753 |
try: |
| 754 |
path = path.encode(sys.getfilesystemencoding() or 'ascii') |
| 755 |
except UnicodeEncodeError: |
| 756 |
if not quiet: |
| 757 |
raise unittest.SkipTest('unable to encode the cwd name with ' |
| 758 |
'the filesystem encoding.') |
| 759 |
try: |
| 760 |
os.mkdir(path) |
| 761 |
dir_created = True |
| 762 |
except OSError: |
| 763 |
if not quiet: |
| 764 |
raise |
| 765 |
warnings.warn('tests may fail, unable to create temp dir: ' + path, |
| 766 |
RuntimeWarning, stacklevel=3) |
| 767 |
if dir_created: |
| 768 |
pid = os.getpid() |
| 769 |
try: |
| 770 |
yield path |
| 771 |
finally: |
| 772 |
|
| 773 |
|
| 774 |
if dir_created and pid == os.getpid(): |
| 775 |
rmtree(path) |
| 776 |
|
| 777 |
@contextlib.contextmanager |
| 778 |
def change_cwd(path, quiet=False): |
| 779 |
"""Return a context manager that changes the current working directory. |
| 780 |
|
| 781 |
Arguments: |
| 782 |
|
| 783 |
path: the directory to use as the temporary current working directory. |
| 784 |
|
| 785 |
quiet: if False (the default), the context manager raises an exception |
| 786 |
on error. Otherwise, it issues only a warning and keeps the current |
| 787 |
working directory the same. |
| 788 |
|
| 789 |
""" |
| 790 |
saved_dir = os.getcwd() |
| 791 |
try: |
| 792 |
os.chdir(path) |
| 793 |
except OSError: |
| 794 |
if not quiet: |
| 795 |
raise |
| 796 |
warnings.warn('tests may fail, unable to change CWD to: ' + path, |
| 797 |
RuntimeWarning, stacklevel=3) |
| 798 |
try: |
| 799 |
yield os.getcwd() |
| 800 |
finally: |
| 801 |
os.chdir(saved_dir) |
| 802 |
|
| 803 |
|
| 804 |
@contextlib.contextmanager |
| 805 |
def temp_cwd(name='tempcwd', quiet=False): |
| 806 |
""" |
| 807 |
Context manager that temporarily creates and changes the CWD. |
| 808 |
|
| 809 |
The function temporarily changes the current working directory |
| 810 |
after creating a temporary directory in the current directory with |
| 811 |
name *name*. If *name* is None, the temporary directory is |
| 812 |
created using tempfile.mkdtemp. |
| 813 |
|
| 814 |
If *quiet* is False (default) and it is not possible to |
| 815 |
create or change the CWD, an error is raised. If *quiet* is True, |
| 816 |
only a warning is raised and the original CWD is used. |
| 817 |
|
| 818 |
""" |
| 819 |
with temp_dir(path=name, quiet=quiet) as temp_path: |
| 820 |
with change_cwd(temp_path, quiet=quiet) as cwd_dir: |
| 821 |
yield cwd_dir |
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 826 |
TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR) |
| 827 |
|
| 828 |
|
| 829 |
TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data") |
| 830 |
|
| 831 |
def findfile(file, subdir=None): |
| 832 |
"""Try to find a file on sys.path and the working directory. If it is not |
| 833 |
found the argument passed to the function is returned (this does not |
| 834 |
necessarily signal failure; could still be the legitimate path).""" |
| 835 |
if os.path.isabs(file): |
| 836 |
return file |
| 837 |
if subdir is not None: |
| 838 |
file = os.path.join(subdir, file) |
| 839 |
path = [TEST_HOME_DIR] + sys.path |
| 840 |
for dn in path: |
| 841 |
fn = os.path.join(dn, file) |
| 842 |
if os.path.exists(fn): return fn |
| 843 |
return file |
| 844 |
|
| 845 |
def sortdict(dict): |
| 846 |
"Like repr(dict), but in sorted order." |
| 847 |
items = dict.items() |
| 848 |
items.sort() |
| 849 |
reprpairs = ["%r: %r" % pair for pair in items] |
| 850 |
withcommas = ", ".join(reprpairs) |
| 851 |
return "{%s}" % withcommas |
| 852 |
|
| 853 |
def make_bad_fd(): |
| 854 |
""" |
| 855 |
Create an invalid file descriptor by opening and closing a file and return |
| 856 |
its fd. |
| 857 |
""" |
| 858 |
file = open(TESTFN, "wb") |
| 859 |
try: |
| 860 |
return file.fileno() |
| 861 |
finally: |
| 862 |
file.close() |
| 863 |
unlink(TESTFN) |
| 864 |
|
| 865 |
def check_syntax_error(testcase, statement, errtext='', lineno=None, offset=None): |
| 866 |
with testcase.assertRaisesRegexp(SyntaxError, errtext) as cm: |
| 867 |
compile(statement, '<test string>', 'exec') |
| 868 |
err = cm.exception |
| 869 |
if lineno is not None: |
| 870 |
testcase.assertEqual(err.lineno, lineno) |
| 871 |
if offset is not None: |
| 872 |
testcase.assertEqual(err.offset, offset) |
| 873 |
|
| 874 |
def open_urlresource(url, check=None): |
| 875 |
import urlparse, urllib2 |
| 876 |
|
| 877 |
filename = urlparse.urlparse(url)[2].split('/')[-1] |
| 878 |
|
| 879 |
fn = os.path.join(TEST_DATA_DIR, filename) |
| 880 |
|
| 881 |
def check_valid_file(fn): |
| 882 |
f = open(fn) |
| 883 |
if check is None: |
| 884 |
return f |
| 885 |
elif check(f): |
| 886 |
f.seek(0) |
| 887 |
return f |
| 888 |
f.close() |
| 889 |
|
| 890 |
if os.path.exists(fn): |
| 891 |
f = check_valid_file(fn) |
| 892 |
if f is not None: |
| 893 |
return f |
| 894 |
unlink(fn) |
| 895 |
|
| 896 |
|
| 897 |
requires('urlfetch') |
| 898 |
|
| 899 |
print >> get_original_stdout(), '\tfetching %s ...' % url |
| 900 |
f = urllib2.urlopen(url, timeout=15) |
| 901 |
try: |
| 902 |
with open(fn, "wb") as out: |
| 903 |
s = f.read() |
| 904 |
while s: |
| 905 |
out.write(s) |
| 906 |
s = f.read() |
| 907 |
finally: |
| 908 |
f.close() |
| 909 |
|
| 910 |
f = check_valid_file(fn) |
| 911 |
if f is not None: |
| 912 |
return f |
| 913 |
raise TestFailed('invalid resource "%s"' % fn) |
| 914 |
|
| 915 |
|
| 916 |
class WarningsRecorder(object): |
| 917 |
"""Convenience wrapper for the warnings list returned on |
| 918 |
entry to the warnings.catch_warnings() context manager. |
| 919 |
""" |
| 920 |
def __init__(self, warnings_list): |
| 921 |
self._warnings = warnings_list |
| 922 |
self._last = 0 |
| 923 |
|
| 924 |
def __getattr__(self, attr): |
| 925 |
if len(self._warnings) > self._last: |
| 926 |
return getattr(self._warnings[-1], attr) |
| 927 |
elif attr in warnings.WarningMessage._WARNING_DETAILS: |
| 928 |
return None |
| 929 |
raise AttributeError("%r has no attribute %r" % (self, attr)) |
| 930 |
|
| 931 |
@property |
| 932 |
def warnings(self): |
| 933 |
return self._warnings[self._last:] |
| 934 |
|
| 935 |
def reset(self): |
| 936 |
self._last = len(self._warnings) |
| 937 |
|
| 938 |
|
| 939 |
def _filterwarnings(filters, quiet=False): |
| 940 |
"""Catch the warnings, then check if all the expected |
| 941 |
warnings have been raised and re-raise unexpected warnings. |
| 942 |
If 'quiet' is True, only re-raise the unexpected warnings. |
| 943 |
""" |
| 944 |
|
| 945 |
|
| 946 |
frame = sys._getframe(2) |
| 947 |
registry = frame.f_globals.get('__warningregistry__') |
| 948 |
if registry: |
| 949 |
registry.clear() |
| 950 |
with warnings.catch_warnings(record=True) as w: |
| 951 |
|
| 952 |
|
| 953 |
|
| 954 |
sys.modules['warnings'].simplefilter("always") |
| 955 |
yield WarningsRecorder(w) |
| 956 |
|
| 957 |
reraise = [warning.message for warning in w] |
| 958 |
missing = [] |
| 959 |
for msg, cat in filters: |
| 960 |
seen = False |
| 961 |
for exc in reraise[:]: |
| 962 |
message = str(exc) |
| 963 |
|
| 964 |
if (re.match(msg, message, re.I) and |
| 965 |
issubclass(exc.__class__, cat)): |
| 966 |
seen = True |
| 967 |
reraise.remove(exc) |
| 968 |
if not seen and not quiet: |
| 969 |
|
| 970 |
missing.append((msg, cat.__name__)) |
| 971 |
if reraise: |
| 972 |
raise AssertionError("unhandled warning %r" % reraise[0]) |
| 973 |
if missing: |
| 974 |
raise AssertionError("filter (%r, %s) did not catch any warning" % |
| 975 |
missing[0]) |
| 976 |
|
| 977 |
|
| 978 |
@contextlib.contextmanager |
| 979 |
def check_warnings(*filters, **kwargs): |
| 980 |
"""Context manager to silence warnings. |
| 981 |
|
| 982 |
Accept 2-tuples as positional arguments: |
| 983 |
("message regexp", WarningCategory) |
| 984 |
|
| 985 |
Optional argument: |
| 986 |
- if 'quiet' is True, it does not fail if a filter catches nothing |
| 987 |
(default True without argument, |
| 988 |
default False if some filters are defined) |
| 989 |
|
| 990 |
Without argument, it defaults to: |
| 991 |
check_warnings(("", Warning), quiet=True) |
| 992 |
""" |
| 993 |
quiet = kwargs.get('quiet') |
| 994 |
if not filters: |
| 995 |
filters = (("", Warning),) |
| 996 |
|
| 997 |
if quiet is None: |
| 998 |
quiet = True |
| 999 |
return _filterwarnings(filters, quiet) |
| 1000 |
|
| 1001 |
|
| 1002 |
@contextlib.contextmanager |
| 1003 |
def check_py3k_warnings(*filters, **kwargs): |
| 1004 |
"""Context manager to silence py3k warnings. |
| 1005 |
|
| 1006 |
Accept 2-tuples as positional arguments: |
| 1007 |
("message regexp", WarningCategory) |
| 1008 |
|
| 1009 |
Optional argument: |
| 1010 |
- if 'quiet' is True, it does not fail if a filter catches nothing |
| 1011 |
(default False) |
| 1012 |
|
| 1013 |
Without argument, it defaults to: |
| 1014 |
check_py3k_warnings(("", DeprecationWarning), quiet=False) |
| 1015 |
""" |
| 1016 |
if sys.py3kwarning: |
| 1017 |
if not filters: |
| 1018 |
filters = (("", DeprecationWarning),) |
| 1019 |
else: |
| 1020 |
|
| 1021 |
filters = () |
| 1022 |
return _filterwarnings(filters, kwargs.get('quiet')) |
| 1023 |
|
| 1024 |
|
| 1025 |
class CleanImport(object): |
| 1026 |
"""Context manager to force import to return a new module reference. |
| 1027 |
|
| 1028 |
This is useful for testing module-level behaviours, such as |
| 1029 |
the emission of a DeprecationWarning on import. |
| 1030 |
|
| 1031 |
Use like this: |
| 1032 |
|
| 1033 |
with CleanImport("foo"): |
| 1034 |
importlib.import_module("foo") # new reference |
| 1035 |
""" |
| 1036 |
|
| 1037 |
def __init__(self, *module_names): |
| 1038 |
self.original_modules = sys.modules.copy() |
| 1039 |
for module_name in module_names: |
| 1040 |
if module_name in sys.modules: |
| 1041 |
module = sys.modules[module_name] |
| 1042 |
|
| 1043 |
|
| 1044 |
|
| 1045 |
|
| 1046 |
if module.__name__ != module_name: |
| 1047 |
del sys.modules[module.__name__] |
| 1048 |
del sys.modules[module_name] |
| 1049 |
|
| 1050 |
def __enter__(self): |
| 1051 |
return self |
| 1052 |
|
| 1053 |
def __exit__(self, *ignore_exc): |
| 1054 |
sys.modules.update(self.original_modules) |
| 1055 |
|
| 1056 |
|
| 1057 |
class EnvironmentVarGuard(UserDict.DictMixin): |
| 1058 |
|
| 1059 |
"""Class to help protect the environment variable properly. Can be used as |
| 1060 |
a context manager.""" |
| 1061 |
|
| 1062 |
def __init__(self): |
| 1063 |
self._environ = os.environ |
| 1064 |
self._changed = {} |
| 1065 |
|
| 1066 |
def __getitem__(self, envvar): |
| 1067 |
return self._environ[envvar] |
| 1068 |
|
| 1069 |
def __setitem__(self, envvar, value): |
| 1070 |
|
| 1071 |
if envvar not in self._changed: |
| 1072 |
self._changed[envvar] = self._environ.get(envvar) |
| 1073 |
self._environ[envvar] = value |
| 1074 |
|
| 1075 |
def __delitem__(self, envvar): |
| 1076 |
|
| 1077 |
if envvar not in self._changed: |
| 1078 |
self._changed[envvar] = self._environ.get(envvar) |
| 1079 |
if envvar in self._environ: |
| 1080 |
del self._environ[envvar] |
| 1081 |
|
| 1082 |
def keys(self): |
| 1083 |
return self._environ.keys() |
| 1084 |
|
| 1085 |
def set(self, envvar, value): |
| 1086 |
self[envvar] = value |
| 1087 |
|
| 1088 |
def unset(self, envvar): |
| 1089 |
del self[envvar] |
| 1090 |
|
| 1091 |
def __enter__(self): |
| 1092 |
return self |
| 1093 |
|
| 1094 |
def __exit__(self, *ignore_exc): |
| 1095 |
for (k, v) in self._changed.items(): |
| 1096 |
if v is None: |
| 1097 |
if k in self._environ: |
| 1098 |
del self._environ[k] |
| 1099 |
else: |
| 1100 |
self._environ[k] = v |
| 1101 |
os.environ = self._environ |
| 1102 |
|
| 1103 |
|
| 1104 |
class DirsOnSysPath(object): |
| 1105 |
"""Context manager to temporarily add directories to sys.path. |
| 1106 |
|
| 1107 |
This makes a copy of sys.path, appends any directories given |
| 1108 |
as positional arguments, then reverts sys.path to the copied |
| 1109 |
settings when the context ends. |
| 1110 |
|
| 1111 |
Note that *all* sys.path modifications in the body of the |
| 1112 |
context manager, including replacement of the object, |
| 1113 |
will be reverted at the end of the block. |
| 1114 |
""" |
| 1115 |
|
| 1116 |
def __init__(self, *paths): |
| 1117 |
self.original_value = sys.path[:] |
| 1118 |
self.original_object = sys.path |
| 1119 |
sys.path.extend(paths) |
| 1120 |
|
| 1121 |
def __enter__(self): |
| 1122 |
return self |
| 1123 |
|
| 1124 |
def __exit__(self, *ignore_exc): |
| 1125 |
sys.path = self.original_object |
| 1126 |
sys.path[:] = self.original_value |
| 1127 |
|
| 1128 |
|
| 1129 |
class TransientResource(object): |
| 1130 |
|
| 1131 |
"""Raise ResourceDenied if an exception is raised while the context manager |
| 1132 |
is in effect that matches the specified exception and attributes.""" |
| 1133 |
|
| 1134 |
def __init__(self, exc, **kwargs): |
| 1135 |
self.exc = exc |
| 1136 |
self.attrs = kwargs |
| 1137 |
|
| 1138 |
def __enter__(self): |
| 1139 |
return self |
| 1140 |
|
| 1141 |
def __exit__(self, type_=None, value=None, traceback=None): |
| 1142 |
"""If type_ is a subclass of self.exc and value has attributes matching |
| 1143 |
self.attrs, raise ResourceDenied. Otherwise let the exception |
| 1144 |
propagate (if any).""" |
| 1145 |
if type_ is not None and issubclass(self.exc, type_): |
| 1146 |
for attr, attr_value in self.attrs.iteritems(): |
| 1147 |
if not hasattr(value, attr): |
| 1148 |
break |
| 1149 |
if getattr(value, attr) != attr_value: |
| 1150 |
break |
| 1151 |
else: |
| 1152 |
raise ResourceDenied("an optional resource is not available") |
| 1153 |
|
| 1154 |
|
| 1155 |
@contextlib.contextmanager |
| 1156 |
def transient_internet(resource_name, timeout=30.0, errnos=()): |
| 1157 |
"""Return a context manager that raises ResourceDenied when various issues |
| 1158 |
with the Internet connection manifest themselves as exceptions.""" |
| 1159 |
default_errnos = [ |
| 1160 |
('ECONNREFUSED', 111), |
| 1161 |
('ECONNRESET', 104), |
| 1162 |
('EHOSTUNREACH', 113), |
| 1163 |
('ENETUNREACH', 101), |
| 1164 |
('ETIMEDOUT', 110), |
| 1165 |
|
| 1166 |
|
| 1167 |
('EADDRNOTAVAIL', 99), |
| 1168 |
] |
| 1169 |
default_gai_errnos = [ |
| 1170 |
('EAI_AGAIN', -3), |
| 1171 |
('EAI_FAIL', -4), |
| 1172 |
('EAI_NONAME', -2), |
| 1173 |
('EAI_NODATA', -5), |
| 1174 |
|
| 1175 |
|
| 1176 |
('WSANO_DATA', 11004), |
| 1177 |
] |
| 1178 |
|
| 1179 |
denied = ResourceDenied("Resource '%s' is not available" % resource_name) |
| 1180 |
captured_errnos = errnos |
| 1181 |
gai_errnos = [] |
| 1182 |
if not captured_errnos: |
| 1183 |
captured_errnos = [getattr(errno, name, num) |
| 1184 |
for (name, num) in default_errnos] |
| 1185 |
gai_errnos = [getattr(socket, name, num) |
| 1186 |
for (name, num) in default_gai_errnos] |
| 1187 |
|
| 1188 |
def filter_error(err): |
| 1189 |
n = getattr(err, 'errno', None) |
| 1190 |
if (isinstance(err, socket.timeout) or |
| 1191 |
(isinstance(err, socket.gaierror) and n in gai_errnos) or |
| 1192 |
n in captured_errnos): |
| 1193 |
if not verbose: |
| 1194 |
sys.stderr.write(denied.args[0] + "\n") |
| 1195 |
raise denied |
| 1196 |
|
| 1197 |
old_timeout = socket.getdefaulttimeout() |
| 1198 |
try: |
| 1199 |
if timeout is not None: |
| 1200 |
socket.setdefaulttimeout(timeout) |
| 1201 |
yield |
| 1202 |
except IOError as err: |
| 1203 |
|
| 1204 |
|
| 1205 |
while True: |
| 1206 |
a = err.args |
| 1207 |
if len(a) >= 1 and isinstance(a[0], IOError): |
| 1208 |
err = a[0] |
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 1212 |
elif len(a) >= 2 and isinstance(a[1], IOError): |
| 1213 |
err = a[1] |
| 1214 |
else: |
| 1215 |
break |
| 1216 |
filter_error(err) |
| 1217 |
raise |
| 1218 |
|
| 1219 |
|
| 1220 |
finally: |
| 1221 |
socket.setdefaulttimeout(old_timeout) |
| 1222 |
|
| 1223 |
|
| 1224 |
@contextlib.contextmanager |
| 1225 |
def captured_output(stream_name): |
| 1226 |
"""Return a context manager used by captured_stdout and captured_stdin |
| 1227 |
that temporarily replaces the sys stream *stream_name* with a StringIO.""" |
| 1228 |
import StringIO |
| 1229 |
orig_stdout = getattr(sys, stream_name) |
| 1230 |
setattr(sys, stream_name, StringIO.StringIO()) |
| 1231 |
try: |
| 1232 |
yield getattr(sys, stream_name) |
| 1233 |
finally: |
| 1234 |
setattr(sys, stream_name, orig_stdout) |
| 1235 |
|
| 1236 |
def captured_stdout(): |
| 1237 |
"""Capture the output of sys.stdout: |
| 1238 |
|
| 1239 |
with captured_stdout() as s: |
| 1240 |
print "hello" |
| 1241 |
self.assertEqual(s.getvalue(), "hello") |
| 1242 |
""" |
| 1243 |
return captured_output("stdout") |
| 1244 |
|
| 1245 |
def captured_stderr(): |
| 1246 |
return captured_output("stderr") |
| 1247 |
|
| 1248 |
def captured_stdin(): |
| 1249 |
return captured_output("stdin") |
| 1250 |
|
| 1251 |
def gc_collect(): |
| 1252 |
"""Force as many objects as possible to be collected. |
| 1253 |
|
| 1254 |
In non-CPython implementations of Python, this is needed because timely |
| 1255 |
deallocation is not guaranteed by the garbage collector. (Even in CPython |
| 1256 |
this can be the case in case of reference cycles.) This means that __del__ |
| 1257 |
methods may be called later than expected and weakrefs may remain alive for |
| 1258 |
longer than expected. This function tries its best to force all garbage |
| 1259 |
objects to disappear. |
| 1260 |
""" |
| 1261 |
gc.collect() |
| 1262 |
if is_jython: |
| 1263 |
time.sleep(0.1) |
| 1264 |
gc.collect() |
| 1265 |
gc.collect() |
| 1266 |
|
| 1267 |
|
| 1268 |
_header = '2P' |
| 1269 |
if hasattr(sys, "gettotalrefcount"): |
| 1270 |
_header = '2P' + _header |
| 1271 |
_vheader = _header + 'P' |
| 1272 |
|
| 1273 |
def calcobjsize(fmt): |
| 1274 |
return struct.calcsize(_header + fmt + '0P') |
| 1275 |
|
| 1276 |
def calcvobjsize(fmt): |
| 1277 |
return struct.calcsize(_vheader + fmt + '0P') |
| 1278 |
|
| 1279 |
|
| 1280 |
_TPFLAGS_HAVE_GC = 1<<14 |
| 1281 |
_TPFLAGS_HEAPTYPE = 1<<9 |
| 1282 |
|
| 1283 |
def check_sizeof(test, o, size): |
| 1284 |
import _testcapi |
| 1285 |
result = sys.getsizeof(o) |
| 1286 |
|
| 1287 |
if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\ |
| 1288 |
((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))): |
| 1289 |
size += _testcapi.SIZEOF_PYGC_HEAD |
| 1290 |
msg = 'wrong size for %s: got %d, expected %d' \ |
| 1291 |
% (type(o), result, size) |
| 1292 |
test.assertEqual(result, size, msg) |
| 1293 |
|
| 1294 |
|
| 1295 |
|
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
def run_with_locale(catstr, *locales): |
| 1300 |
def decorator(func): |
| 1301 |
def inner(*args, **kwds): |
| 1302 |
try: |
| 1303 |
import locale |
| 1304 |
category = getattr(locale, catstr) |
| 1305 |
orig_locale = locale.setlocale(category) |
| 1306 |
except AttributeError: |
| 1307 |
|
| 1308 |
raise |
| 1309 |
except: |
| 1310 |
|
| 1311 |
locale = orig_locale = None |
| 1312 |
else: |
| 1313 |
for loc in locales: |
| 1314 |
try: |
| 1315 |
locale.setlocale(category, loc) |
| 1316 |
break |
| 1317 |
except: |
| 1318 |
pass |
| 1319 |
|
| 1320 |
|
| 1321 |
try: |
| 1322 |
return func(*args, **kwds) |
| 1323 |
finally: |
| 1324 |
if locale and orig_locale: |
| 1325 |
locale.setlocale(category, orig_locale) |
| 1326 |
inner.func_name = func.func_name |
| 1327 |
inner.__doc__ = func.__doc__ |
| 1328 |
return inner |
| 1329 |
return decorator |
| 1330 |
|
| 1331 |
|
| 1332 |
|
| 1333 |
|
| 1334 |
|
| 1335 |
def run_with_tz(tz): |
| 1336 |
def decorator(func): |
| 1337 |
def inner(*args, **kwds): |
| 1338 |
try: |
| 1339 |
tzset = time.tzset |
| 1340 |
except AttributeError: |
| 1341 |
raise unittest.SkipTest("tzset required") |
| 1342 |
if 'TZ' in os.environ: |
| 1343 |
orig_tz = os.environ['TZ'] |
| 1344 |
else: |
| 1345 |
orig_tz = None |
| 1346 |
os.environ['TZ'] = tz |
| 1347 |
tzset() |
| 1348 |
|
| 1349 |
|
| 1350 |
try: |
| 1351 |
return func(*args, **kwds) |
| 1352 |
finally: |
| 1353 |
if orig_tz is None: |
| 1354 |
del os.environ['TZ'] |
| 1355 |
else: |
| 1356 |
os.environ['TZ'] = orig_tz |
| 1357 |
time.tzset() |
| 1358 |
|
| 1359 |
inner.__name__ = func.__name__ |
| 1360 |
inner.__doc__ = func.__doc__ |
| 1361 |
return inner |
| 1362 |
return decorator |
| 1363 |
|
| 1364 |
|
| 1365 |
|
| 1366 |
|
| 1367 |
|
| 1368 |
|
| 1369 |
_1M = 1024*1024 |
| 1370 |
_1G = 1024 * _1M |
| 1371 |
_2G = 2 * _1G |
| 1372 |
_4G = 4 * _1G |
| 1373 |
|
| 1374 |
MAX_Py_ssize_t = sys.maxsize |
| 1375 |
|
| 1376 |
def set_memlimit(limit): |
| 1377 |
global max_memuse |
| 1378 |
global real_max_memuse |
| 1379 |
sizes = { |
| 1380 |
'k': 1024, |
| 1381 |
'm': _1M, |
| 1382 |
'g': _1G, |
| 1383 |
't': 1024*_1G, |
| 1384 |
} |
| 1385 |
m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit, |
| 1386 |
re.IGNORECASE | re.VERBOSE) |
| 1387 |
if m is None: |
| 1388 |
raise ValueError('Invalid memory limit %r' % (limit,)) |
| 1389 |
memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()]) |
| 1390 |
real_max_memuse = memlimit |
| 1391 |
if memlimit > MAX_Py_ssize_t: |
| 1392 |
memlimit = MAX_Py_ssize_t |
| 1393 |
if memlimit < _2G - 1: |
| 1394 |
raise ValueError('Memory limit %r too low to be useful' % (limit,)) |
| 1395 |
max_memuse = memlimit |
| 1396 |
|
| 1397 |
def bigmemtest(minsize, memuse, overhead=5*_1M): |
| 1398 |
"""Decorator for bigmem tests. |
| 1399 |
|
| 1400 |
'minsize' is the minimum useful size for the test (in arbitrary, |
| 1401 |
test-interpreted units.) 'memuse' is the number of 'bytes per size' for |
| 1402 |
the test, or a good estimate of it. 'overhead' specifies fixed overhead, |
| 1403 |
independent of the testsize, and defaults to 5Mb. |
| 1404 |
|
| 1405 |
The decorator tries to guess a good value for 'size' and passes it to |
| 1406 |
the decorated test function. If minsize * memuse is more than the |
| 1407 |
allowed memory use (as defined by max_memuse), the test is skipped. |
| 1408 |
Otherwise, minsize is adjusted upward to use up to max_memuse. |
| 1409 |
""" |
| 1410 |
def decorator(f): |
| 1411 |
def wrapper(self): |
| 1412 |
if not max_memuse: |
| 1413 |
|
| 1414 |
|
| 1415 |
|
| 1416 |
|
| 1417 |
maxsize = 5147 |
| 1418 |
self.assertFalse(maxsize * memuse + overhead > 20 * _1M) |
| 1419 |
else: |
| 1420 |
maxsize = int((max_memuse - overhead) / memuse) |
| 1421 |
if maxsize < minsize: |
| 1422 |
|
| 1423 |
if verbose: |
| 1424 |
sys.stderr.write("Skipping %s because of memory " |
| 1425 |
"constraint\n" % (f.__name__,)) |
| 1426 |
return |
| 1427 |
|
| 1428 |
maxsize = max(maxsize - 50 * _1M, minsize) |
| 1429 |
return f(self, maxsize) |
| 1430 |
wrapper.minsize = minsize |
| 1431 |
wrapper.memuse = memuse |
| 1432 |
wrapper.overhead = overhead |
| 1433 |
return wrapper |
| 1434 |
return decorator |
| 1435 |
|
| 1436 |
def precisionbigmemtest(size, memuse, overhead=5*_1M, dry_run=True): |
| 1437 |
def decorator(f): |
| 1438 |
def wrapper(self): |
| 1439 |
if not real_max_memuse: |
| 1440 |
maxsize = 5147 |
| 1441 |
else: |
| 1442 |
maxsize = size |
| 1443 |
|
| 1444 |
if ((real_max_memuse or not dry_run) |
| 1445 |
and real_max_memuse < maxsize * memuse): |
| 1446 |
if verbose: |
| 1447 |
sys.stderr.write("Skipping %s because of memory " |
| 1448 |
"constraint\n" % (f.__name__,)) |
| 1449 |
return |
| 1450 |
|
| 1451 |
return f(self, maxsize) |
| 1452 |
wrapper.size = size |
| 1453 |
wrapper.memuse = memuse |
| 1454 |
wrapper.overhead = overhead |
| 1455 |
return wrapper |
| 1456 |
return decorator |
| 1457 |
|
| 1458 |
def bigaddrspacetest(f): |
| 1459 |
"""Decorator for tests that fill the address space.""" |
| 1460 |
def wrapper(self): |
| 1461 |
if max_memuse < MAX_Py_ssize_t: |
| 1462 |
if verbose: |
| 1463 |
sys.stderr.write("Skipping %s because of memory " |
| 1464 |
"constraint\n" % (f.__name__,)) |
| 1465 |
else: |
| 1466 |
return f(self) |
| 1467 |
return wrapper |
| 1468 |
|
| 1469 |
|
| 1470 |
|
| 1471 |
|
| 1472 |
class BasicTestRunner: |
| 1473 |
def run(self, test): |
| 1474 |
result = unittest.TestResult() |
| 1475 |
test(result) |
| 1476 |
return result |
| 1477 |
|
| 1478 |
def _id(obj): |
| 1479 |
return obj |
| 1480 |
|
| 1481 |
def requires_resource(resource): |
| 1482 |
if resource == 'gui' and not _is_gui_available(): |
| 1483 |
return unittest.skip(_is_gui_available.reason) |
| 1484 |
if is_resource_enabled(resource): |
| 1485 |
return _id |
| 1486 |
else: |
| 1487 |
return unittest.skip("resource {0!r} is not enabled".format(resource)) |
| 1488 |
|
| 1489 |
def cpython_only(test): |
| 1490 |
""" |
| 1491 |
Decorator for tests only applicable on CPython. |
| 1492 |
""" |
| 1493 |
return impl_detail(cpython=True)(test) |
| 1494 |
|
| 1495 |
def impl_detail(msg=None, **guards): |
| 1496 |
if check_impl_detail(**guards): |
| 1497 |
return _id |
| 1498 |
if msg is None: |
| 1499 |
guardnames, default = _parse_guards(guards) |
| 1500 |
if default: |
| 1501 |
msg = "implementation detail not available on {0}" |
| 1502 |
else: |
| 1503 |
msg = "implementation detail specific to {0}" |
| 1504 |
guardnames = sorted(guardnames.keys()) |
| 1505 |
msg = msg.format(' or '.join(guardnames)) |
| 1506 |
return unittest.skip(msg) |
| 1507 |
|
| 1508 |
def _parse_guards(guards): |
| 1509 |
|
| 1510 |
if not guards: |
| 1511 |
return ({'cpython': True}, False) |
| 1512 |
is_true = guards.values()[0] |
| 1513 |
assert guards.values() == [is_true] * len(guards) |
| 1514 |
return (guards, not is_true) |
| 1515 |
|
| 1516 |
|
| 1517 |
|
| 1518 |
def check_impl_detail(**guards): |
| 1519 |
"""This function returns True or False depending on the host platform. |
| 1520 |
Examples: |
| 1521 |
if check_impl_detail(): # only on CPython (default) |
| 1522 |
if check_impl_detail(jython=True): # only on Jython |
| 1523 |
if check_impl_detail(cpython=False): # everywhere except on CPython |
| 1524 |
""" |
| 1525 |
guards, default = _parse_guards(guards) |
| 1526 |
return guards.get(platform.python_implementation().lower(), default) |
| 1527 |
|
| 1528 |
|
| 1529 |
def _filter_suite(suite, pred): |
| 1530 |
"""Recursively filter test cases in a suite based on a predicate.""" |
| 1531 |
newtests = [] |
| 1532 |
for test in suite._tests: |
| 1533 |
if isinstance(test, unittest.TestSuite): |
| 1534 |
_filter_suite(test, pred) |
| 1535 |
newtests.append(test) |
| 1536 |
else: |
| 1537 |
if pred(test): |
| 1538 |
newtests.append(test) |
| 1539 |
suite._tests = newtests |
| 1540 |
|
| 1541 |
def _run_suite(suite): |
| 1542 |
"""Run tests from a unittest.TestSuite-derived class.""" |
| 1543 |
if verbose: |
| 1544 |
runner = unittest.TextTestRunner(sys.stdout, verbosity=2, |
| 1545 |
failfast=failfast) |
| 1546 |
else: |
| 1547 |
runner = BasicTestRunner() |
| 1548 |
|
| 1549 |
result = runner.run(suite) |
| 1550 |
if not result.testsRun and not result.skipped: |
| 1551 |
raise TestDidNotRun |
| 1552 |
if not result.wasSuccessful(): |
| 1553 |
if len(result.errors) == 1 and not result.failures: |
| 1554 |
err = result.errors[0][1] |
| 1555 |
elif len(result.failures) == 1 and not result.errors: |
| 1556 |
err = result.failures[0][1] |
| 1557 |
else: |
| 1558 |
err = "multiple errors occurred" |
| 1559 |
if not verbose: |
| 1560 |
err += "; run in verbose mode for details" |
| 1561 |
raise TestFailed(err) |
| 1562 |
|
| 1563 |
|
| 1564 |
|
| 1565 |
_match_test_func = None |
| 1566 |
_match_test_patterns = None |
| 1567 |
|
| 1568 |
|
| 1569 |
def match_test(test): |
| 1570 |
|
| 1571 |
if _match_test_func is None: |
| 1572 |
return True |
| 1573 |
else: |
| 1574 |
return _match_test_func(test.id()) |
| 1575 |
|
| 1576 |
|
| 1577 |
def _is_full_match_test(pattern): |
| 1578 |
|
| 1579 |
|
| 1580 |
|
| 1581 |
|
| 1582 |
|
| 1583 |
|
| 1584 |
return ('.' in pattern) and (not re.search(r'[?*\[\]]', pattern)) |
| 1585 |
|
| 1586 |
|
| 1587 |
def set_match_tests(patterns): |
| 1588 |
global _match_test_func, _match_test_patterns |
| 1589 |
|
| 1590 |
if patterns == _match_test_patterns: |
| 1591 |
|
| 1592 |
return |
| 1593 |
|
| 1594 |
if not patterns: |
| 1595 |
func = None |
| 1596 |
|
| 1597 |
patterns = () |
| 1598 |
elif all(map(_is_full_match_test, patterns)): |
| 1599 |
|
| 1600 |
|
| 1601 |
func = set(patterns).__contains__ |
| 1602 |
else: |
| 1603 |
regex = '|'.join(map(fnmatch.translate, patterns)) |
| 1604 |
|
| 1605 |
|
| 1606 |
regex_match = re.compile(regex).match |
| 1607 |
|
| 1608 |
def match_test_regex(test_id): |
| 1609 |
if regex_match(test_id): |
| 1610 |
|
| 1611 |
|
| 1612 |
return True |
| 1613 |
else: |
| 1614 |
|
| 1615 |
|
| 1616 |
|
| 1617 |
return any(map(regex_match, test_id.split("."))) |
| 1618 |
|
| 1619 |
func = match_test_regex |
| 1620 |
|
| 1621 |
|
| 1622 |
_match_test_patterns = tuple(patterns) |
| 1623 |
_match_test_func = func |
| 1624 |
|
| 1625 |
|
| 1626 |
|
| 1627 |
def run_unittest(*classes): |
| 1628 |
"""Run tests from unittest.TestCase-derived classes.""" |
| 1629 |
valid_types = (unittest.TestSuite, unittest.TestCase) |
| 1630 |
suite = unittest.TestSuite() |
| 1631 |
for cls in classes: |
| 1632 |
if isinstance(cls, str): |
| 1633 |
if cls in sys.modules: |
| 1634 |
suite.addTest(unittest.findTestCases(sys.modules[cls])) |
| 1635 |
else: |
| 1636 |
raise ValueError("str arguments must be keys in sys.modules") |
| 1637 |
elif isinstance(cls, valid_types): |
| 1638 |
suite.addTest(cls) |
| 1639 |
else: |
| 1640 |
suite.addTest(unittest.makeSuite(cls)) |
| 1641 |
_filter_suite(suite, match_test) |
| 1642 |
_run_suite(suite) |
| 1643 |
|
| 1644 |
|
| 1645 |
|
| 1646 |
|
| 1647 |
HAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or |
| 1648 |
sys.platform == 'win32' or |
| 1649 |
sysconfig.get_config_var('WITH_DOC_STRINGS')) |
| 1650 |
|
| 1651 |
requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS, |
| 1652 |
"test requires docstrings") |
| 1653 |
|
| 1654 |
|
| 1655 |
|
| 1656 |
|
| 1657 |
|
| 1658 |
def run_doctest(module, verbosity=None): |
| 1659 |
"""Run doctest on the given module. Return (#failures, #tests). |
| 1660 |
|
| 1661 |
If optional argument verbosity is not specified (or is None), pass |
| 1662 |
test.support's belief about verbosity on to doctest. Else doctest's |
| 1663 |
usual behavior is used (it searches sys.argv for -v). |
| 1664 |
""" |
| 1665 |
|
| 1666 |
import doctest |
| 1667 |
|
| 1668 |
if verbosity is None: |
| 1669 |
verbosity = verbose |
| 1670 |
else: |
| 1671 |
verbosity = None |
| 1672 |
|
| 1673 |
|
| 1674 |
|
| 1675 |
save_stdout = sys.stdout |
| 1676 |
sys.stdout = get_original_stdout() |
| 1677 |
try: |
| 1678 |
f, t = doctest.testmod(module, verbose=verbosity) |
| 1679 |
if f: |
| 1680 |
raise TestFailed("%d of %d doctests failed" % (f, t)) |
| 1681 |
finally: |
| 1682 |
sys.stdout = save_stdout |
| 1683 |
if verbose: |
| 1684 |
print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t) |
| 1685 |
return f, t |
| 1686 |
|
| 1687 |
|
| 1688 |
|
| 1689 |
|
| 1690 |
|
| 1691 |
|
| 1692 |
|
| 1693 |
|
| 1694 |
|
| 1695 |
|
| 1696 |
environment_altered = False |
| 1697 |
|
| 1698 |
|
| 1699 |
|
| 1700 |
|
| 1701 |
|
| 1702 |
|
| 1703 |
|
| 1704 |
|
| 1705 |
|
| 1706 |
def threading_setup(): |
| 1707 |
if thread: |
| 1708 |
return thread._count(), |
| 1709 |
else: |
| 1710 |
return 1, |
| 1711 |
|
| 1712 |
def threading_cleanup(nb_threads): |
| 1713 |
if not thread: |
| 1714 |
return |
| 1715 |
|
| 1716 |
_MAX_COUNT = 10 |
| 1717 |
for count in range(_MAX_COUNT): |
| 1718 |
n = thread._count() |
| 1719 |
if n == nb_threads: |
| 1720 |
break |
| 1721 |
time.sleep(0.1) |
| 1722 |
|
| 1723 |
|
| 1724 |
def reap_threads(func): |
| 1725 |
"""Use this function when threads are being used. This will |
| 1726 |
ensure that the threads are cleaned up even when the test fails. |
| 1727 |
If threading is unavailable this function does nothing. |
| 1728 |
""" |
| 1729 |
if not thread: |
| 1730 |
return func |
| 1731 |
|
| 1732 |
@functools.wraps(func) |
| 1733 |
def decorator(*args): |
| 1734 |
key = threading_setup() |
| 1735 |
try: |
| 1736 |
return func(*args) |
| 1737 |
finally: |
| 1738 |
threading_cleanup(*key) |
| 1739 |
return decorator |
| 1740 |
|
| 1741 |
|
| 1742 |
@contextlib.contextmanager |
| 1743 |
def wait_threads_exit(timeout=60.0): |
| 1744 |
""" |
| 1745 |
bpo-31234: Context manager to wait until all threads created in the with |
| 1746 |
statement exit. |
| 1747 |
|
| 1748 |
Use thread.count() to check if threads exited. Indirectly, wait until |
| 1749 |
threads exit the internal t_bootstrap() C function of the thread module. |
| 1750 |
|
| 1751 |
threading_setup() and threading_cleanup() are designed to emit a warning |
| 1752 |
if a test leaves running threads in the background. This context manager |
| 1753 |
is designed to cleanup threads started by the thread.start_new_thread() |
| 1754 |
which doesn't allow to wait for thread exit, whereas thread.Thread has a |
| 1755 |
join() method. |
| 1756 |
""" |
| 1757 |
old_count = thread._count() |
| 1758 |
try: |
| 1759 |
yield |
| 1760 |
finally: |
| 1761 |
start_time = time.time() |
| 1762 |
deadline = start_time + timeout |
| 1763 |
while True: |
| 1764 |
count = thread._count() |
| 1765 |
if count <= old_count: |
| 1766 |
break |
| 1767 |
if time.time() > deadline: |
| 1768 |
dt = time.time() - start_time |
| 1769 |
msg = ("wait_threads() failed to cleanup %s " |
| 1770 |
"threads after %.1f seconds " |
| 1771 |
"(count: %s, old count: %s)" |
| 1772 |
% (count - old_count, dt, count, old_count)) |
| 1773 |
raise AssertionError(msg) |
| 1774 |
time.sleep(0.010) |
| 1775 |
gc_collect() |
| 1776 |
|
| 1777 |
|
| 1778 |
def reap_children(): |
| 1779 |
"""Use this function at the end of test_main() whenever sub-processes |
| 1780 |
are started. This will help ensure that no extra children (zombies) |
| 1781 |
stick around to hog resources and create problems when looking |
| 1782 |
for refleaks. |
| 1783 |
""" |
| 1784 |
|
| 1785 |
|
| 1786 |
|
| 1787 |
if hasattr(os, 'waitpid'): |
| 1788 |
any_process = -1 |
| 1789 |
while True: |
| 1790 |
try: |
| 1791 |
|
| 1792 |
pid, status = os.waitpid(any_process, os.WNOHANG) |
| 1793 |
if pid == 0: |
| 1794 |
break |
| 1795 |
except: |
| 1796 |
break |
| 1797 |
|
| 1798 |
@contextlib.contextmanager |
| 1799 |
def start_threads(threads, unlock=None): |
| 1800 |
threads = list(threads) |
| 1801 |
started = [] |
| 1802 |
try: |
| 1803 |
try: |
| 1804 |
for t in threads: |
| 1805 |
t.start() |
| 1806 |
started.append(t) |
| 1807 |
except: |
| 1808 |
if verbose: |
| 1809 |
print("Can't start %d threads, only %d threads started" % |
| 1810 |
(len(threads), len(started))) |
| 1811 |
raise |
| 1812 |
yield |
| 1813 |
finally: |
| 1814 |
if unlock: |
| 1815 |
unlock() |
| 1816 |
endtime = starttime = time.time() |
| 1817 |
for timeout in range(1, 16): |
| 1818 |
endtime += 60 |
| 1819 |
for t in started: |
| 1820 |
t.join(max(endtime - time.time(), 0.01)) |
| 1821 |
started = [t for t in started if t.isAlive()] |
| 1822 |
if not started: |
| 1823 |
break |
| 1824 |
if verbose: |
| 1825 |
print('Unable to join %d threads during a period of ' |
| 1826 |
'%d minutes' % (len(started), timeout)) |
| 1827 |
started = [t for t in started if t.isAlive()] |
| 1828 |
if started: |
| 1829 |
raise AssertionError('Unable to join %d threads' % len(started)) |
| 1830 |
|
| 1831 |
@contextlib.contextmanager |
| 1832 |
def swap_attr(obj, attr, new_val): |
| 1833 |
"""Temporary swap out an attribute with a new object. |
| 1834 |
|
| 1835 |
Usage: |
| 1836 |
with swap_attr(obj, "attr", 5): |
| 1837 |
... |
| 1838 |
|
| 1839 |
This will set obj.attr to 5 for the duration of the with: block, |
| 1840 |
restoring the old value at the end of the block. If `attr` doesn't |
| 1841 |
exist on `obj`, it will be created and then deleted at the end of the |
| 1842 |
block. |
| 1843 |
|
| 1844 |
The old value (or None if it doesn't exist) will be assigned to the |
| 1845 |
target of the "as" clause, if there is one. |
| 1846 |
""" |
| 1847 |
if hasattr(obj, attr): |
| 1848 |
real_val = getattr(obj, attr) |
| 1849 |
setattr(obj, attr, new_val) |
| 1850 |
try: |
| 1851 |
yield real_val |
| 1852 |
finally: |
| 1853 |
setattr(obj, attr, real_val) |
| 1854 |
else: |
| 1855 |
setattr(obj, attr, new_val) |
| 1856 |
try: |
| 1857 |
yield |
| 1858 |
finally: |
| 1859 |
if hasattr(obj, attr): |
| 1860 |
delattr(obj, attr) |
| 1861 |
|
| 1862 |
@contextlib.contextmanager |
| 1863 |
def swap_item(obj, item, new_val): |
| 1864 |
"""Temporary swap out an item with a new object. |
| 1865 |
|
| 1866 |
Usage: |
| 1867 |
with swap_item(obj, "item", 5): |
| 1868 |
... |
| 1869 |
|
| 1870 |
This will set obj["item"] to 5 for the duration of the with: block, |
| 1871 |
restoring the old value at the end of the block. If `item` doesn't |
| 1872 |
exist on `obj`, it will be created and then deleted at the end of the |
| 1873 |
block. |
| 1874 |
|
| 1875 |
The old value (or None if it doesn't exist) will be assigned to the |
| 1876 |
target of the "as" clause, if there is one. |
| 1877 |
""" |
| 1878 |
if item in obj: |
| 1879 |
real_val = obj[item] |
| 1880 |
obj[item] = new_val |
| 1881 |
try: |
| 1882 |
yield real_val |
| 1883 |
finally: |
| 1884 |
obj[item] = real_val |
| 1885 |
else: |
| 1886 |
obj[item] = new_val |
| 1887 |
try: |
| 1888 |
yield |
| 1889 |
finally: |
| 1890 |
if item in obj: |
| 1891 |
del obj[item] |
| 1892 |
|
| 1893 |
def py3k_bytes(b): |
| 1894 |
"""Emulate the py3k bytes() constructor. |
| 1895 |
|
| 1896 |
NOTE: This is only a best effort function. |
| 1897 |
""" |
| 1898 |
try: |
| 1899 |
|
| 1900 |
return b.tobytes() |
| 1901 |
except AttributeError: |
| 1902 |
try: |
| 1903 |
|
| 1904 |
return b"".join(chr(x) for x in b) |
| 1905 |
except TypeError: |
| 1906 |
return bytes(b) |
| 1907 |
|
| 1908 |
requires_type_collecting = unittest.skipIf(hasattr(sys, 'getcounts'), |
| 1909 |
'types are immortal if COUNT_ALLOCS is defined') |
| 1910 |
|
| 1911 |
def args_from_interpreter_flags(): |
| 1912 |
"""Return a list of command-line arguments reproducing the current |
| 1913 |
settings in sys.flags.""" |
| 1914 |
import subprocess |
| 1915 |
return subprocess._args_from_interpreter_flags() |
| 1916 |
|
| 1917 |
def strip_python_stderr(stderr): |
| 1918 |
"""Strip the stderr of a Python process from potential debug output |
| 1919 |
emitted by the interpreter. |
| 1920 |
|
| 1921 |
This will typically be run on the result of the communicate() method |
| 1922 |
of a subprocess.Popen object. |
| 1923 |
""" |
| 1924 |
stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip() |
| 1925 |
return stderr |
| 1926 |
|
| 1927 |
|
| 1928 |
def check_free_after_iterating(test, iter, cls, args=()): |
| 1929 |
class A(cls): |
| 1930 |
def __del__(self): |
| 1931 |
done[0] = True |
| 1932 |
try: |
| 1933 |
next(it) |
| 1934 |
except StopIteration: |
| 1935 |
pass |
| 1936 |
|
| 1937 |
done = [False] |
| 1938 |
it = iter(A(*args)) |
| 1939 |
|
| 1940 |
test.assertRaises(StopIteration, next, it) |
| 1941 |
|
| 1942 |
gc_collect() |
| 1943 |
test.assertTrue(done[0]) |
| 1944 |
|
| 1945 |
@contextlib.contextmanager |
| 1946 |
def disable_gc(): |
| 1947 |
have_gc = gc.isenabled() |
| 1948 |
gc.disable() |
| 1949 |
try: |
| 1950 |
yield |
| 1951 |
finally: |
| 1952 |
if have_gc: |
| 1953 |
gc.enable() |
| 1954 |
|
| 1955 |
|
| 1956 |
def python_is_optimized(): |
| 1957 |
"""Find if Python was built with optimizations.""" |
| 1958 |
cflags = sysconfig.get_config_var('PY_CFLAGS') or '' |
| 1959 |
final_opt = "" |
| 1960 |
for opt in cflags.split(): |
| 1961 |
if opt.startswith('-O'): |
| 1962 |
final_opt = opt |
| 1963 |
return final_opt not in ('', '-O0', '-Og') |
| 1964 |
|
| 1965 |
|
| 1966 |
class SuppressCrashReport: |
| 1967 |
"""Try to prevent a crash report from popping up. |
| 1968 |
|
| 1969 |
On Windows, don't display the Windows Error Reporting dialog. On UNIX, |
| 1970 |
disable the creation of coredump file. |
| 1971 |
""" |
| 1972 |
old_value = None |
| 1973 |
old_modes = None |
| 1974 |
|
| 1975 |
def __enter__(self): |
| 1976 |
"""On Windows, disable Windows Error Reporting dialogs using |
| 1977 |
SetErrorMode. |
| 1978 |
|
| 1979 |
On UNIX, try to save the previous core file size limit, then set |
| 1980 |
soft limit to 0. |
| 1981 |
""" |
| 1982 |
if sys.platform.startswith('win'): |
| 1983 |
|
| 1984 |
|
| 1985 |
|
| 1986 |
import ctypes |
| 1987 |
self._k32 = ctypes.windll.kernel32 |
| 1988 |
SEM_NOGPFAULTERRORBOX = 0x02 |
| 1989 |
self.old_value = self._k32.SetErrorMode(SEM_NOGPFAULTERRORBOX) |
| 1990 |
self._k32.SetErrorMode(self.old_value | SEM_NOGPFAULTERRORBOX) |
| 1991 |
|
| 1992 |
|
| 1993 |
|
| 1994 |
try: |
| 1995 |
import _testcapi |
| 1996 |
_testcapi.CrtSetReportMode |
| 1997 |
except (AttributeError, ImportError): |
| 1998 |
|
| 1999 |
pass |
| 2000 |
else: |
| 2001 |
self.old_modes = {} |
| 2002 |
for report_type in [_testcapi.CRT_WARN, |
| 2003 |
_testcapi.CRT_ERROR, |
| 2004 |
_testcapi.CRT_ASSERT]: |
| 2005 |
old_mode = _testcapi.CrtSetReportMode(report_type, |
| 2006 |
_testcapi.CRTDBG_MODE_FILE) |
| 2007 |
old_file = _testcapi.CrtSetReportFile(report_type, |
| 2008 |
_testcapi.CRTDBG_FILE_STDERR) |
| 2009 |
self.old_modes[report_type] = old_mode, old_file |
| 2010 |
|
| 2011 |
else: |
| 2012 |
try: |
| 2013 |
import resource |
| 2014 |
except ImportError: |
| 2015 |
resource = None |
| 2016 |
|
| 2017 |
if resource is not None: |
| 2018 |
try: |
| 2019 |
self.old_value = resource.getrlimit(resource.RLIMIT_CORE) |
| 2020 |
resource.setrlimit(resource.RLIMIT_CORE, |
| 2021 |
(0, self.old_value[1])) |
| 2022 |
except (ValueError, OSError): |
| 2023 |
pass |
| 2024 |
|
| 2025 |
if sys.platform == 'darwin': |
| 2026 |
|
| 2027 |
|
| 2028 |
|
| 2029 |
|
| 2030 |
|
| 2031 |
|
| 2032 |
import subprocess |
| 2033 |
cmd = ['/usr/bin/defaults', 'read', |
| 2034 |
'com.apple.CrashReporter', 'DialogType'] |
| 2035 |
proc = subprocess.Popen(cmd, |
| 2036 |
stdout=subprocess.PIPE, |
| 2037 |
stderr=subprocess.PIPE) |
| 2038 |
stdout = proc.communicate()[0] |
| 2039 |
if stdout.strip() == b'developer': |
| 2040 |
sys.stdout.write("this test triggers the Crash Reporter, " |
| 2041 |
"that is intentional") |
| 2042 |
sys.stdout.flush() |
| 2043 |
|
| 2044 |
return self |
| 2045 |
|
| 2046 |
def __exit__(self, *ignore_exc): |
| 2047 |
"""Restore Windows ErrorMode or core file behavior to initial value.""" |
| 2048 |
if self.old_value is None: |
| 2049 |
return |
| 2050 |
|
| 2051 |
if sys.platform.startswith('win'): |
| 2052 |
self._k32.SetErrorMode(self.old_value) |
| 2053 |
|
| 2054 |
if self.old_modes: |
| 2055 |
import _testcapi |
| 2056 |
for report_type, (old_mode, old_file) in self.old_modes.items(): |
| 2057 |
_testcapi.CrtSetReportMode(report_type, old_mode) |
| 2058 |
_testcapi.CrtSetReportFile(report_type, old_file) |
| 2059 |
else: |
| 2060 |
import resource |
| 2061 |
try: |
| 2062 |
resource.setrlimit(resource.RLIMIT_CORE, self.old_value) |
| 2063 |
except (ValueError, OSError): |
| 2064 |
pass |
| 2065 |
|
| 2066 |
|
| 2067 |
def _crash_python(): |
| 2068 |
"""Deliberate crash of Python. |
| 2069 |
|
| 2070 |
Python can be killed by a segmentation fault (SIGSEGV), a bus error |
| 2071 |
(SIGBUS), or a different error depending on the platform. |
| 2072 |
|
| 2073 |
Use SuppressCrashReport() to prevent a crash report from popping up. |
| 2074 |
""" |
| 2075 |
|
| 2076 |
import _testcapi |
| 2077 |
with SuppressCrashReport(): |
| 2078 |
_testcapi._read_null() |
| 2079 |
|
| 2080 |
|
| 2081 |
def fd_count(): |
| 2082 |
"""Count the number of open file descriptors. |
| 2083 |
""" |
| 2084 |
if sys.platform.startswith(('linux', 'freebsd')): |
| 2085 |
try: |
| 2086 |
names = os.listdir("/proc/self/fd") |
| 2087 |
|
| 2088 |
|
| 2089 |
return len(names) - 1 |
| 2090 |
except OSError as exc: |
| 2091 |
if exc.errno != errno.ENOENT: |
| 2092 |
raise |
| 2093 |
|
| 2094 |
MAXFD = 256 |
| 2095 |
if hasattr(os, 'sysconf'): |
| 2096 |
try: |
| 2097 |
MAXFD = os.sysconf("SC_OPEN_MAX") |
| 2098 |
except OSError: |
| 2099 |
pass |
| 2100 |
|
| 2101 |
old_modes = None |
| 2102 |
if sys.platform == 'win32': |
| 2103 |
|
| 2104 |
|
| 2105 |
try: |
| 2106 |
import msvcrt |
| 2107 |
msvcrt.CrtSetReportMode |
| 2108 |
except (AttributeError, ImportError): |
| 2109 |
|
| 2110 |
pass |
| 2111 |
else: |
| 2112 |
old_modes = {} |
| 2113 |
for report_type in (msvcrt.CRT_WARN, |
| 2114 |
msvcrt.CRT_ERROR, |
| 2115 |
msvcrt.CRT_ASSERT): |
| 2116 |
old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0) |
| 2117 |
|
| 2118 |
try: |
| 2119 |
count = 0 |
| 2120 |
for fd in range(MAXFD): |
| 2121 |
try: |
| 2122 |
|
| 2123 |
|
| 2124 |
fd2 = os.dup(fd) |
| 2125 |
except OSError as e: |
| 2126 |
if e.errno != errno.EBADF: |
| 2127 |
raise |
| 2128 |
else: |
| 2129 |
os.close(fd2) |
| 2130 |
count += 1 |
| 2131 |
finally: |
| 2132 |
if old_modes is not None: |
| 2133 |
for report_type in (msvcrt.CRT_WARN, |
| 2134 |
msvcrt.CRT_ERROR, |
| 2135 |
msvcrt.CRT_ASSERT): |
| 2136 |
msvcrt.CrtSetReportMode(report_type, old_modes[report_type]) |
| 2137 |
|
| 2138 |
return count |
| 2139 |
|
| 2140 |
|
| 2141 |
class SaveSignals: |
| 2142 |
""" |
| 2143 |
Save an restore signal handlers. |
| 2144 |
|
| 2145 |
This class is only able to save/restore signal handlers registered |
| 2146 |
by the Python signal module: see bpo-13285 for "external" signal |
| 2147 |
handlers. |
| 2148 |
""" |
| 2149 |
|
| 2150 |
def __init__(self): |
| 2151 |
import signal |
| 2152 |
self.signal = signal |
| 2153 |
self.signals = list(range(1, signal.NSIG)) |
| 2154 |
|
| 2155 |
for signame in ('SIGKILL', 'SIGSTOP'): |
| 2156 |
try: |
| 2157 |
signum = getattr(signal, signame) |
| 2158 |
except AttributeError: |
| 2159 |
continue |
| 2160 |
self.signals.remove(signum) |
| 2161 |
self.handlers = {} |
| 2162 |
|
| 2163 |
def save(self): |
| 2164 |
for signum in self.signals: |
| 2165 |
handler = self.signal.getsignal(signum) |
| 2166 |
if handler is None: |
| 2167 |
|
| 2168 |
|
| 2169 |
|
| 2170 |
|
| 2171 |
|
| 2172 |
continue |
| 2173 |
self.handlers[signum] = handler |
| 2174 |
|
| 2175 |
def restore(self): |
| 2176 |
for signum, handler in self.handlers.items(): |
| 2177 |
self.signal.signal(signum, handler) |