Back to index

python3.2  3.2.2
Classes | Functions | Variables
test.support Namespace Reference

Classes

class  Error
class  TestFailed
class  ResourceDenied
class  WarningsRecorder
class  CleanImport
class  EnvironmentVarGuard
class  DirsOnSysPath
class  TransientResource
class  BasicTestRunner
class  TestHandler
class  Matcher

Functions

def _ignore_deprecated_imports
def import_module
def _save_and_remove_module
def _save_and_block_module
def import_fresh_module
def get_attribute
def record_original_stdout
def get_original_stdout
def unload
def unlink
def rmtree
def make_legacy_pyc
def forget
def _is_gui_available
def is_resource_enabled
def requires
def requires_mac_ver
def find_unused_port
def bind_port
def fcmp
def temp_cwd
def temp_umask
def findfile
def sortdict
def make_bad_fd
def check_syntax_error
def open_urlresource
def _filterwarnings
def check_warnings
def transient_internet
def captured_output
def captured_stdout
def captured_stderr
def captured_stdin
def gc_collect
def python_is_optimized
def run_with_locale
def set_memlimit
def bigmemtest
def precisionbigmemtest
def bigaddrspacetest
def _id
def requires_resource
def cpython_only
def impl_detail
def _parse_guards
def check_impl_detail
def _filter_suite
def _run_suite
def run_unittest
def run_doctest
def modules_setup
def modules_cleanup
def threading_setup
def threading_cleanup
def reap_threads
def reap_children
def swap_attr
def swap_item
def strip_python_stderr
def args_from_interpreter_flags
def can_symlink
def skip_unless_symlink
def patch

Variables

 _thread = None
 threading = None
 multiprocessing = None
list __all__
int verbose = 1
 use_resources = None
int max_memuse = 0
int real_max_memuse = 0
 failfast = False
 match_tests = None
 _original_stdout = None
string HOST = 'localhost'
int FUZZ = 1
tuple requires_IEEE_754
tuple is_jython = sys.platform.startswith('java')
string TESTFN = '$test'
string TESTFN_UNICODE = "-\xe0\xf2\u0258\u0141\u011f"
tuple TESTFN_ENCODING = sys.getfilesystemencoding()
 TESTFN_UNENCODABLE = None
tuple SAVEDCWD = os.getcwd()
tuple time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
tuple socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
tuple ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
int _1M = 1024
int _1G = 1024
int _2G = 2
int _4G = 4
 MAX_Py_ssize_t = sys.maxsize
 _can_symlink = None

Detailed Description

Supporting definitions for the Python regression tests.

Class Documentation

class test::support::ResourceDenied
Test skipped because it requested a disallowed resource.

This is raised when a test calls requires() for a resource that
has not be enabled.  It is used to distinguish between expected
and unexpected skips.

Definition at line 65 of file support.py.


Function Documentation

def test.support._filter_suite (   suite,
  pred 
) [private]
Recursively filter test cases in a suite based on a predicate.

Definition at line 1188 of file support.py.

01188 
01189 def _filter_suite(suite, pred):
01190     """Recursively filter test cases in a suite based on a predicate."""
01191     newtests = []
01192     for test in suite._tests:
01193         if isinstance(test, unittest.TestSuite):
01194             _filter_suite(test, pred)
01195             newtests.append(test)
01196         else:
01197             if pred(test):
01198                 newtests.append(test)
01199     suite._tests = newtests
01200 

Here is the caller graph for this function:

def test.support._filterwarnings (   filters,
  quiet = False 
) [private]
Catch the warnings, then check if all the expected
warnings have been raised and re-raise unexpected warnings.
If 'quiet' is True, only re-raise the unexpected warnings.

Definition at line 661 of file support.py.

00661 
00662 def _filterwarnings(filters, quiet=False):
00663     """Catch the warnings, then check if all the expected
00664     warnings have been raised and re-raise unexpected warnings.
00665     If 'quiet' is True, only re-raise the unexpected warnings.
00666     """
00667     # Clear the warning registry of the calling module
00668     # in order to re-raise the warnings.
00669     frame = sys._getframe(2)
00670     registry = frame.f_globals.get('__warningregistry__')
00671     if registry:
00672         registry.clear()
00673     with warnings.catch_warnings(record=True) as w:
00674         # Set filter "always" to record all warnings.  Because
00675         # test_warnings swap the module, we need to look up in
00676         # the sys.modules dictionary.
00677         sys.modules['warnings'].simplefilter("always")
00678         yield WarningsRecorder(w)
00679     # Filter the recorded warnings
00680     reraise = list(w)
00681     missing = []
00682     for msg, cat in filters:
00683         seen = False
00684         for w in reraise[:]:
00685             warning = w.message
00686             # Filter out the matching messages
00687             if (re.match(msg, str(warning), re.I) and
00688                 issubclass(warning.__class__, cat)):
00689                 seen = True
00690                 reraise.remove(w)
00691         if not seen and not quiet:
00692             # This filter caught nothing
00693             missing.append((msg, cat.__name__))
00694     if reraise:
00695         raise AssertionError("unhandled warning %s" % reraise[0])
00696     if missing:
00697         raise AssertionError("filter (%r, %s) did not catch any warning" %
00698                              missing[0])
00699 
00700 
@contextlib.contextmanager

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support._id (   obj) [private]

Definition at line 1137 of file support.py.

01137 
01138 def _id(obj):
01139     return obj

def test.support._ignore_deprecated_imports (   ignore = True) [private]
Context manager to suppress package and module deprecation
warnings when importing them.

If ignore is False, this context manager has no effect.

Definition at line 74 of file support.py.

00074 
00075 def _ignore_deprecated_imports(ignore=True):
00076     """Context manager to suppress package and module deprecation
00077     warnings when importing them.
00078 
00079     If ignore is False, this context manager has no effect."""
00080     if ignore:
00081         with warnings.catch_warnings():
00082             warnings.filterwarnings("ignore", ".+ (module|package)",
00083                                     DeprecationWarning)
00084             yield
00085     else:
00086         yield
00087 

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support._is_gui_available ( ) [private]

Definition at line 253 of file support.py.

00253 
00254     def _is_gui_available():
00255         UOI_FLAGS = 1
00256         WSF_VISIBLE = 0x0001
00257         class USEROBJECTFLAGS(ctypes.Structure):
00258             _fields_ = [("fInherit", ctypes.wintypes.BOOL),
00259                         ("fReserved", ctypes.wintypes.BOOL),
00260                         ("dwFlags", ctypes.wintypes.DWORD)]
00261         dll = ctypes.windll.user32
00262         h = dll.GetProcessWindowStation()
00263         if not h:
00264             raise ctypes.WinError()
00265         uof = USEROBJECTFLAGS()
00266         needed = ctypes.wintypes.DWORD()
00267         res = dll.GetUserObjectInformationW(h,
00268             UOI_FLAGS,
00269             ctypes.byref(uof),
00270             ctypes.sizeof(uof),
00271             ctypes.byref(needed))
00272         if not res:
00273             raise ctypes.WinError()
00274         return bool(uof.dwFlags & WSF_VISIBLE)
else:

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support._parse_guards (   guards) [private]

Definition at line 1167 of file support.py.

01167 
01168 def _parse_guards(guards):
01169     # Returns a tuple ({platform_name: run_me}, default_value)
01170     if not guards:
01171         return ({'cpython': True}, False)
01172     is_true = list(guards.values())[0]
01173     assert list(guards.values()) == [is_true] * len(guards)   # all True or all False
01174     return (guards, not is_true)
01175 
01176 # Use the following check to guard CPython's implementation-specific tests --
# or to run them only on the implementation(s) guarded by the arguments.

Here is the caller graph for this function:

def test.support._run_suite (   suite) [private]
Run tests from a unittest.TestSuite-derived class.

Definition at line 1201 of file support.py.

01201 
01202 def _run_suite(suite):
01203     """Run tests from a unittest.TestSuite-derived class."""
01204     if verbose:
01205         runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
01206                                          failfast=failfast)
01207     else:
01208         runner = BasicTestRunner()
01209 
01210     result = runner.run(suite)
01211     if not result.wasSuccessful():
01212         if len(result.errors) == 1 and not result.failures:
01213             err = result.errors[0][1]
01214         elif len(result.failures) == 1 and not result.errors:
01215             err = result.failures[0][1]
01216         else:
01217             err = "multiple errors occurred"
01218             if not verbose: err += "; run in verbose mode for details"
01219         raise TestFailed(err)
01220 

Here is the caller graph for this function:

def test.support._save_and_block_module (   name,
  orig_modules 
) [private]
Helper function to save and block a module in sys.modules

   Return True if the module was in sys.modules, False otherwise.

Definition at line 114 of file support.py.

00114 
00115 def _save_and_block_module(name, orig_modules):
00116     """Helper function to save and block a module in sys.modules
00117 
00118        Return True if the module was in sys.modules, False otherwise."""
00119     saved = True
00120     try:
00121         orig_modules[name] = sys.modules[name]
00122     except KeyError:
00123         saved = False
00124     sys.modules[name] = None
00125     return saved
00126 

Here is the caller graph for this function:

def test.support._save_and_remove_module (   name,
  orig_modules 
) [private]
Helper function to save and remove a module from sys.modules

   Raise ImportError if the module can't be imported.

Definition at line 101 of file support.py.

00101 
00102 def _save_and_remove_module(name, orig_modules):
00103     """Helper function to save and remove a module from sys.modules
00104 
00105        Raise ImportError if the module can't be imported."""
00106     # try to import the module and raise an error if it can't be imported
00107     if name not in sys.modules:
00108         __import__(name)
00109         del sys.modules[name]
00110     for modname in list(sys.modules):
00111         if modname == name or modname.startswith(name + '.'):
00112             orig_modules[modname] = sys.modules[modname]
00113             del sys.modules[modname]

Here is the call graph for this function:

Here is the caller graph for this function:

Return a list of command-line arguments reproducing the current
settings in sys.flags.

Definition at line 1425 of file support.py.

01425 
01426 def args_from_interpreter_flags():
01427     """Return a list of command-line arguments reproducing the current
01428     settings in sys.flags."""
01429     flag_opt_map = {
01430         'bytes_warning': 'b',
01431         'dont_write_bytecode': 'B',
01432         'ignore_environment': 'E',
01433         'no_user_site': 's',
01434         'no_site': 'S',
01435         'optimize': 'O',
01436         'verbose': 'v',
01437     }
01438     args = []
01439     for flag, opt in flag_opt_map.items():
01440         v = getattr(sys.flags, flag)
01441         if v > 0:
01442             args.append('-' + opt * v)
01443     return args
01444 
01445 #============================================================
01446 # Support for assertions about logging.
01447 #============================================================

Here is the call graph for this function:

Decorator for tests that fill the address space.

Definition at line 1113 of file support.py.

01113 
01114 def bigaddrspacetest(f):
01115     """Decorator for tests that fill the address space."""
01116     def wrapper(self):
01117         if max_memuse < MAX_Py_ssize_t:
01118             if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
01119                 raise unittest.SkipTest(
01120                     "not enough memory: try a 32-bit build instead")
01121             else:
01122                 raise unittest.SkipTest(
01123                     "not enough memory: %.1fG minimum needed"
01124                     % (MAX_Py_ssize_t / (1024 ** 3)))
01125         else:
01126             return f(self)
01127     return wrapper
01128 
01129 #=======================================================================
01130 # unittest integration.

Here is the call graph for this function:

def test.support.bigmemtest (   minsize,
  memuse 
)
Decorator for bigmem tests.

'minsize' is the minimum useful size for the test (in arbitrary,
test-interpreted units.) 'memuse' is the number of 'bytes per size' for
the test, or a good estimate of it.

The decorator tries to guess a good value for 'size' and passes it to
the decorated test function. If minsize * memuse is more than the
allowed memory use (as defined by max_memuse), the test is skipped.
Otherwise, minsize is adjusted upward to use up to max_memuse.

Definition at line 1056 of file support.py.

01056 
01057 def bigmemtest(minsize, memuse):
01058     """Decorator for bigmem tests.
01059 
01060     'minsize' is the minimum useful size for the test (in arbitrary,
01061     test-interpreted units.) 'memuse' is the number of 'bytes per size' for
01062     the test, or a good estimate of it.
01063 
01064     The decorator tries to guess a good value for 'size' and passes it to
01065     the decorated test function. If minsize * memuse is more than the
01066     allowed memory use (as defined by max_memuse), the test is skipped.
01067     Otherwise, minsize is adjusted upward to use up to max_memuse.
01068     """
01069     def decorator(f):
01070         def wrapper(self):
01071             # Retrieve values in case someone decided to adjust them
01072             minsize = wrapper.minsize
01073             memuse = wrapper.memuse
01074             if not max_memuse:
01075                 # If max_memuse is 0 (the default),
01076                 # we still want to run the tests with size set to a few kb,
01077                 # to make sure they work. We still want to avoid using
01078                 # too much memory, though, but we do that noisily.
01079                 maxsize = 5147
01080                 self.assertFalse(maxsize * memuse > 20 * _1M)
01081             else:
01082                 maxsize = int(max_memuse / memuse)
01083                 if maxsize < minsize:
01084                     raise unittest.SkipTest(
01085                         "not enough memory: %.1fG minimum needed"
01086                         % (minsize * memuse / (1024 ** 3)))
01087             return f(self, maxsize)
01088         wrapper.minsize = minsize
01089         wrapper.memuse = memuse
01090         return wrapper
01091     return decorator

Here is the call graph for this function:

def test.support.bind_port (   sock,
  host = HOST 
)
Bind the socket to a free port and return the port number.  Relies on
ephemeral ports in order to ensure we are using an unbound port.  This is
important as many tests may be running simultaneously, especially in a
buildbot environment.  This method raises an exception if the sock.family
is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
or SO_REUSEPORT set on it.  Tests should *never* set these socket options
for TCP/IP sockets.  The only case for setting these options is testing
multicasting via multiple UDP sockets.

Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
on Windows), it will be set on the socket.  This will prevent anyone else
from bind()'ing to our host/port for the duration of the test.

Definition at line 392 of file support.py.

00392 
00393 def bind_port(sock, host=HOST):
00394     """Bind the socket to a free port and return the port number.  Relies on
00395     ephemeral ports in order to ensure we are using an unbound port.  This is
00396     important as many tests may be running simultaneously, especially in a
00397     buildbot environment.  This method raises an exception if the sock.family
00398     is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
00399     or SO_REUSEPORT set on it.  Tests should *never* set these socket options
00400     for TCP/IP sockets.  The only case for setting these options is testing
00401     multicasting via multiple UDP sockets.
00402 
00403     Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
00404     on Windows), it will be set on the socket.  This will prevent anyone else
00405     from bind()'ing to our host/port for the duration of the test.
00406     """
00407 
00408     if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
00409         if hasattr(socket, 'SO_REUSEADDR'):
00410             if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
00411                 raise TestFailed("tests should never set the SO_REUSEADDR "   \
00412                                  "socket option on TCP/IP sockets!")
00413         if hasattr(socket, 'SO_REUSEPORT'):
00414             if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
00415                 raise TestFailed("tests should never set the SO_REUSEPORT "   \
00416                                  "socket option on TCP/IP sockets!")
00417         if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
00418             sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
00419 
00420     sock.bind((host, 0))
00421     port = sock.getsockname()[1]
00422     return port

Here is the caller graph for this function:

Definition at line 1511 of file support.py.

01511 
01512 def can_symlink():
01513     global _can_symlink
01514     if _can_symlink is not None:
01515         return _can_symlink
01516     symlink_path = TESTFN + "can_symlink"
01517     try:
01518         os.symlink(TESTFN, symlink_path)
01519         can = True
01520     except (OSError, NotImplementedError, AttributeError):
01521         can = False
01522     else:
01523         os.remove(symlink_path)
01524     _can_symlink = can
01525     return can

Here is the caller graph for this function:

def test.support.captured_output (   stream_name)
Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.

Definition at line 932 of file support.py.

00932 
00933 def captured_output(stream_name):
00934     """Return a context manager used by captured_stdout/stdin/stderr
00935     that temporarily replaces the sys stream *stream_name* with a StringIO."""
00936     import io
00937     orig_stdout = getattr(sys, stream_name)
00938     setattr(sys, stream_name, io.StringIO())
00939     try:
00940         yield getattr(sys, stream_name)
00941     finally:
00942         setattr(sys, stream_name, orig_stdout)

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 952 of file support.py.

00952 
00953 def captured_stderr():
00954     return captured_output("stderr")

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 955 of file support.py.

00955 
00956 def captured_stdin():
00957     return captured_output("stdin")
00958 

Here is the call graph for this function:

Capture the output of sys.stdout:

   with captured_stdout() as s:
       print("hello")
   self.assertEqual(s.getvalue(), "hello")

Definition at line 943 of file support.py.

00943 
00944 def captured_stdout():
00945     """Capture the output of sys.stdout:
00946 
00947        with captured_stdout() as s:
00948            print("hello")
00949        self.assertEqual(s.getvalue(), "hello")
00950     """
00951     return captured_output("stdout")

Here is the call graph for this function:

Here is the caller graph for this function:

This function returns True or False depending on the host platform.
   Examples:
      if check_impl_detail():               # only on CPython (default)
      if check_impl_detail(jython=True):    # only on Jython
      if check_impl_detail(cpython=False):  # everywhere except on CPython

Definition at line 1177 of file support.py.

01177 
01178 def check_impl_detail(**guards):
01179     """This function returns True or False depending on the host platform.
01180        Examples:
01181           if check_impl_detail():               # only on CPython (default)
01182           if check_impl_detail(jython=True):    # only on Jython
01183           if check_impl_detail(cpython=False):  # everywhere except on CPython
01184     """
01185     guards, default = _parse_guards(guards)
01186     return guards.get(platform.python_implementation().lower(), default)
01187 

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.check_syntax_error (   testcase,
  statement 
)

Definition at line 590 of file support.py.

00590 
00591 def check_syntax_error(testcase, statement):
00592     testcase.assertRaises(SyntaxError, compile, statement,
00593                           '<test string>', 'exec')

Here is the caller graph for this function:

def test.support.check_warnings (   filters,
  kwargs 
)
Context manager to silence warnings.

Accept 2-tuples as positional arguments:
    ("message regexp", WarningCategory)

Optional argument:
 - if 'quiet' is True, it does not fail if a filter catches nothing
    (default True without argument,
     default False if some filters are defined)

Without argument, it defaults to:
    check_warnings(("", Warning), quiet=True)

Definition at line 701 of file support.py.

00701 
00702 def check_warnings(*filters, **kwargs):
00703     """Context manager to silence warnings.
00704 
00705     Accept 2-tuples as positional arguments:
00706         ("message regexp", WarningCategory)
00707 
00708     Optional argument:
00709      - if 'quiet' is True, it does not fail if a filter catches nothing
00710         (default True without argument,
00711          default False if some filters are defined)
00712 
00713     Without argument, it defaults to:
00714         check_warnings(("", Warning), quiet=True)
00715     """
00716     quiet = kwargs.get('quiet')
00717     if not filters:
00718         filters = (("", Warning),)
00719         # Preserve backward compatibility
00720         if quiet is None:
00721             quiet = True
00722     return _filterwarnings(filters, quiet)
00723 

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.cpython_only (   test)
Decorator for tests only applicable on CPython.

Definition at line 1148 of file support.py.

01148 
01149 def cpython_only(test):
01150     """
01151     Decorator for tests only applicable on CPython.
01152     """
01153     return impl_detail(cpython=True)(test)

Here is the call graph for this function:

def test.support.fcmp (   x,
  y 
)

Definition at line 425 of file support.py.

00425 
00426 def fcmp(x, y): # fuzzy comparison function
00427     if isinstance(x, float) or isinstance(y, float):
00428         try:
00429             fuzz = (abs(x) + abs(y)) * FUZZ
00430             if abs(x-y) <= fuzz:
00431                 return 0
00432         except:
00433             pass
00434     elif type(x) == type(y) and isinstance(x, (tuple, list)):
00435         for i in range(min(len(x), len(y))):
00436             outcome = fcmp(x[i], y[i])
00437             if outcome != 0:
00438                 return outcome
00439         return (len(x) > len(y)) - (len(x) < len(y))
00440     return (x > y) - (x < y)
00441 
# decorator for skipping tests on non-IEEE 754 platforms

Here is the caller graph for this function:

def test.support.find_unused_port (   family = socket.AF_INET,
  socktype = socket.SOCK_STREAM 
)
Returns an unused port that should be suitable for binding.  This is
achieved by creating a temporary socket with the same family and type as
the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
the specified host address (defaults to 0.0.0.0) with the port set to 0,
eliciting an unused ephemeral port from the OS.  The temporary socket is
then closed and deleted, and the ephemeral port is returned.

Either this method or bind_port() should be used for any tests where a
server socket needs to be bound to a particular port for the duration of
the test.  Which one to use depends on whether the calling code is creating
a python socket, or if an unused port needs to be provided in a constructor
or passed to an external program (i.e. the -accept argument to openssl's
s_server mode).  Always prefer bind_port() over find_unused_port() where
possible.  Hard coded ports should *NEVER* be used.  As soon as a server
socket is bound to a hard coded port, the ability to run multiple instances
of the test simultaneously on the same host is compromised, which makes the
test a ticking time bomb in a buildbot environment. On Unix buildbots, this
may simply manifest as a failed test, which can be recovered from without
intervention in most cases, but on Windows, the entire python process can
completely and utterly wedge, requiring someone to log in to the buildbot
and manually kill the affected process.

(This is easy to reproduce on Windows, unfortunately, and can be traced to
the SO_REUSEADDR socket option having different semantics on Windows versus
Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
listen and then accept connections on identical host/ports.  An EADDRINUSE
socket.error will be raised at some point (depending on the platform and
the order bind and listen were called on each socket).

However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
will ever be raised when attempting to bind two identical host/ports. When
accept() is called on each socket, the second caller's process will steal
the port from the first caller, leaving them both in an awkwardly wedged
state where they'll no longer respond to any signals or graceful kills, and
must be forcibly killed via OpenProcess()/TerminateProcess().

The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
instead of SO_REUSEADDR, which effectively affords the same semantics as
SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
Source world compared to Windows ones, this is a common mistake.  A quick
look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
openssl.exe is called with the 's_server' option, for example. See
http://bugs.python.org/issue2550 for more info.  The following site also
has a very thorough description about the implications of both REUSEADDR
and EXCLUSIVEADDRUSE on Windows:
http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

XXX: although this approach is a vast improvement on previous attempts to
elicit unused ports, it rests heavily on the assumption that the ephemeral
port returned to us by the OS won't immediately be dished back out to some
other process when we close and delete our temporary socket but before our
calling code has a chance to bind the returned port.  We can deal with this
issue if/when we come across it.

Definition at line 330 of file support.py.

00330 
00331 def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
00332     """Returns an unused port that should be suitable for binding.  This is
00333     achieved by creating a temporary socket with the same family and type as
00334     the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
00335     the specified host address (defaults to 0.0.0.0) with the port set to 0,
00336     eliciting an unused ephemeral port from the OS.  The temporary socket is
00337     then closed and deleted, and the ephemeral port is returned.
00338 
00339     Either this method or bind_port() should be used for any tests where a
00340     server socket needs to be bound to a particular port for the duration of
00341     the test.  Which one to use depends on whether the calling code is creating
00342     a python socket, or if an unused port needs to be provided in a constructor
00343     or passed to an external program (i.e. the -accept argument to openssl's
00344     s_server mode).  Always prefer bind_port() over find_unused_port() where
00345     possible.  Hard coded ports should *NEVER* be used.  As soon as a server
00346     socket is bound to a hard coded port, the ability to run multiple instances
00347     of the test simultaneously on the same host is compromised, which makes the
00348     test a ticking time bomb in a buildbot environment. On Unix buildbots, this
00349     may simply manifest as a failed test, which can be recovered from without
00350     intervention in most cases, but on Windows, the entire python process can
00351     completely and utterly wedge, requiring someone to log in to the buildbot
00352     and manually kill the affected process.
00353 
00354     (This is easy to reproduce on Windows, unfortunately, and can be traced to
00355     the SO_REUSEADDR socket option having different semantics on Windows versus
00356     Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
00357     listen and then accept connections on identical host/ports.  An EADDRINUSE
00358     socket.error will be raised at some point (depending on the platform and
00359     the order bind and listen were called on each socket).
00360 
00361     However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
00362     will ever be raised when attempting to bind two identical host/ports. When
00363     accept() is called on each socket, the second caller's process will steal
00364     the port from the first caller, leaving them both in an awkwardly wedged
00365     state where they'll no longer respond to any signals or graceful kills, and
00366     must be forcibly killed via OpenProcess()/TerminateProcess().
00367 
00368     The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
00369     instead of SO_REUSEADDR, which effectively affords the same semantics as
00370     SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
00371     Source world compared to Windows ones, this is a common mistake.  A quick
00372     look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
00373     openssl.exe is called with the 's_server' option, for example. See
00374     http://bugs.python.org/issue2550 for more info.  The following site also
00375     has a very thorough description about the implications of both REUSEADDR
00376     and EXCLUSIVEADDRUSE on Windows:
00377     http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
00378 
00379     XXX: although this approach is a vast improvement on previous attempts to
00380     elicit unused ports, it rests heavily on the assumption that the ephemeral
00381     port returned to us by the OS won't immediately be dished back out to some
00382     other process when we close and delete our temporary socket but before our
00383     calling code has a chance to bind the returned port.  We can deal with this
00384     issue if/when we come across it.
00385     """
00386 
00387     tempsock = socket.socket(family, socktype)
00388     port = bind_port(tempsock)
00389     tempsock.close()
00390     del tempsock
00391     return port

Here is the call graph for this function:

def test.support.findfile (   file,
  here = __file__,
  subdir = None 
)
Try to find a file on sys.path and the working directory.  If it is not
found the argument passed to the function is returned (this does not
necessarily signal failure; could still be the legitimate path).

Definition at line 556 of file support.py.

00556 
00557 def findfile(file, here=__file__, subdir=None):
00558     """Try to find a file on sys.path and the working directory.  If it is not
00559     found the argument passed to the function is returned (this does not
00560     necessarily signal failure; could still be the legitimate path)."""
00561     if os.path.isabs(file):
00562         return file
00563     if subdir is not None:
00564         file = os.path.join(subdir, file)
00565     path = sys.path
00566     path = [os.path.dirname(here)] + path
00567     for dn in path:
00568         fn = os.path.join(dn, file)
00569         if os.path.exists(fn): return fn
00570     return file

Here is the caller graph for this function:

def test.support.forget (   modname)
'Forget' a module was ever imported.

This removes the module from sys.modules and deletes any PEP 3147 or
legacy .pyc and .pyo files.

Definition at line 232 of file support.py.

00232 
00233 def forget(modname):
00234     """'Forget' a module was ever imported.
00235 
00236     This removes the module from sys.modules and deletes any PEP 3147 or
00237     legacy .pyc and .pyo files.
00238     """
00239     unload(modname)
00240     for dirname in sys.path:
00241         source = os.path.join(dirname, modname + '.py')
00242         # It doesn't matter if they exist or not, unlink all possible
00243         # combinations of PEP 3147 and legacy pyc and pyo files.
00244         unlink(source + 'c')
00245         unlink(source + 'o')
00246         unlink(imp.cache_from_source(source, debug_override=True))
00247         unlink(imp.cache_from_source(source, debug_override=False))
00248 
00249 # On some platforms, should not run gui test even if it is allowed
# in `use_resources'.

Here is the call graph for this function:

Here is the caller graph for this function:

Force as many objects as possible to be collected.

In non-CPython implementations of Python, this is needed because timely
deallocation is not guaranteed by the garbage collector.  (Even in CPython
this can be the case in case of reference cycles.)  This means that __del__
methods may be called later than expected and weakrefs may remain alive for
longer than expected.  This function tries its best to force all garbage
objects to disappear.

Definition at line 959 of file support.py.

00959 
00960 def gc_collect():
00961     """Force as many objects as possible to be collected.
00962 
00963     In non-CPython implementations of Python, this is needed because timely
00964     deallocation is not guaranteed by the garbage collector.  (Even in CPython
00965     this can be the case in case of reference cycles.)  This means that __del__
00966     methods may be called later than expected and weakrefs may remain alive for
00967     longer than expected.  This function tries its best to force all garbage
00968     objects to disappear.
00969     """
00970     gc.collect()
00971     if is_jython:
00972         time.sleep(0.1)
00973     gc.collect()
00974     gc.collect()
00975 

Here is the caller graph for this function:

def test.support.get_attribute (   obj,
  name 
)
Get an attribute, raising SkipTest if AttributeError is raised.

Definition at line 165 of file support.py.

00165 
00166 def get_attribute(obj, name):
00167     """Get an attribute, raising SkipTest if AttributeError is raised."""
00168     try:
00169         attribute = getattr(obj, name)
00170     except AttributeError:
00171         raise unittest.SkipTest("module %s has no attribute %s" % (
00172             obj.__name__, name))
00173     else:
00174         return attribute

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 191 of file support.py.

00191 
00192 def get_original_stdout():
00193     return _original_stdout or sys.stdout

Here is the caller graph for this function:

def test.support.impl_detail (   msg = None,
  guards 
)

Definition at line 1154 of file support.py.

01154 
01155 def impl_detail(msg=None, **guards):
01156     if check_impl_detail(**guards):
01157         return _id
01158     if msg is None:
01159         guardnames, default = _parse_guards(guards)
01160         if default:
01161             msg = "implementation detail not available on {0}"
01162         else:
01163             msg = "implementation detail specific to {0}"
01164         guardnames = sorted(guardnames.keys())
01165         msg = msg.format(' or '.join(guardnames))
01166     return unittest.skip(msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.import_fresh_module (   name,
  fresh = (),
  blocked = (),
  deprecated = False 
)
Imports and returns a module, deliberately bypassing the sys.modules cache
and importing a fresh copy of the module. Once the import is complete,
the sys.modules cache is restored to its original state.

Modules named in fresh are also imported anew if needed by the import.
If one of these modules can't be imported, None is returned.

Importing of modules named in blocked is prevented while the fresh import
takes place.

If deprecated is True, any module or package deprecation messages
will be suppressed.

Definition at line 127 of file support.py.

00127 
00128 def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
00129     """Imports and returns a module, deliberately bypassing the sys.modules cache
00130     and importing a fresh copy of the module. Once the import is complete,
00131     the sys.modules cache is restored to its original state.
00132 
00133     Modules named in fresh are also imported anew if needed by the import.
00134     If one of these modules can't be imported, None is returned.
00135 
00136     Importing of modules named in blocked is prevented while the fresh import
00137     takes place.
00138 
00139     If deprecated is True, any module or package deprecation messages
00140     will be suppressed."""
00141     # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
00142     # to make sure that this utility function is working as expected
00143     with _ignore_deprecated_imports(deprecated):
00144         # Keep track of modules saved for later restoration as well
00145         # as those which just need a blocking entry removed
00146         orig_modules = {}
00147         names_to_remove = []
00148         _save_and_remove_module(name, orig_modules)
00149         try:
00150             for fresh_name in fresh:
00151                 _save_and_remove_module(fresh_name, orig_modules)
00152             for blocked_name in blocked:
00153                 if not _save_and_block_module(blocked_name, orig_modules):
00154                     names_to_remove.append(blocked_name)
00155             fresh_module = importlib.import_module(name)
00156         except ImportError:
00157             fresh_module = None
00158         finally:
00159             for orig_name, module in orig_modules.items():
00160                 sys.modules[orig_name] = module
00161             for name_to_remove in names_to_remove:
00162                 del sys.modules[name_to_remove]
00163         return fresh_module
00164 

Here is the call graph for this function:

def test.support.import_module (   name,
  deprecated = False 
)
Import and return the module to be tested, raising SkipTest if
it is not available.

If deprecated is True, any module or package deprecation messages
will be suppressed.

Definition at line 88 of file support.py.

00088 
00089 def import_module(name, deprecated=False):
00090     """Import and return the module to be tested, raising SkipTest if
00091     it is not available.
00092 
00093     If deprecated is True, any module or package deprecation messages
00094     will be suppressed."""
00095     with _ignore_deprecated_imports(deprecated):
00096         try:
00097             return importlib.import_module(name)
00098         except ImportError as msg:
00099             raise unittest.SkipTest(str(msg))
00100 

Here is the call graph for this function:

Here is the caller graph for this function:

Test whether a resource is enabled.  Known resources are set by
regrtest.py.

Definition at line 278 of file support.py.

00278 
00279 def is_resource_enabled(resource):
00280     """Test whether a resource is enabled.  Known resources are set by
00281     regrtest.py."""
00282     return use_resources is not None and resource in use_resources

Here is the caller graph for this function:

Create an invalid file descriptor by opening and closing a file and return
its fd.

Definition at line 578 of file support.py.

00578 
00579 def make_bad_fd():
00580     """
00581     Create an invalid file descriptor by opening and closing a file and return
00582     its fd.
00583     """
00584     file = open(TESTFN, "wb")
00585     try:
00586         return file.fileno()
00587     finally:
00588         file.close()
00589         unlink(TESTFN)

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.make_legacy_pyc (   source)
Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.

The choice of .pyc or .pyo extension is done based on the __debug__ flag
value.

:param source: The file system path to the source file.  The source file
    does not need to exist, however the PEP 3147 pyc file must exist.
:return: The file system path to the legacy pyc file.

Definition at line 216 of file support.py.

00216 
00217 def make_legacy_pyc(source):
00218     """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
00219 
00220     The choice of .pyc or .pyo extension is done based on the __debug__ flag
00221     value.
00222 
00223     :param source: The file system path to the source file.  The source file
00224         does not need to exist, however the PEP 3147 pyc file must exist.
00225     :return: The file system path to the legacy pyc file.
00226     """
00227     pyc_file = imp.cache_from_source(source)
00228     up_one = os.path.dirname(os.path.abspath(source))
00229     legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
00230     os.rename(pyc_file, legacy_pyc)
00231     return legacy_pyc

Here is the caller graph for this function:

def test.support.modules_cleanup (   oldmodules)

Definition at line 1279 of file support.py.

01279 
01280 def modules_cleanup(oldmodules):
01281     # Encoders/decoders are registered permanently within the internal
01282     # codec cache. If we destroy the corresponding modules their
01283     # globals will be set to None which will trip up the cached functions.
01284     encodings = [(k, v) for k, v in sys.modules.items()
01285                  if k.startswith('encodings.')]
01286     sys.modules.clear()
01287     sys.modules.update(encodings)
01288     # XXX: This kind of problem can affect more than just encodings. In particular
01289     # extension modules (such as _ssl) don't cope with reloading properly.
01290     # Really, test modules should be cleaning out the test specific modules they
01291     # know they added (ala test_runpy) rather than relying on this function (as
01292     # test_importhooks and test_pkg do currently).
01293     # Implicitly imported *real* modules should be left alone (see issue 10556).
01294     sys.modules.update(oldmodules)
01295 
01296 #=======================================================================
01297 # Threading support to prevent reporting refleaks when running regrtest.py -R
01298 
01299 # NOTE: we use thread._count() rather than threading.enumerate() (or the
01300 # moral equivalent thereof) because a threading.Thread object is still alive
01301 # until its __bootstrap() method has returned, even after it has been
01302 # unregistered from the threading module.
01303 # thread._count(), on the other hand, only gets decremented *after* the
01304 # __bootstrap() method has returned, which gives us reliable reference counts
01305 # at the end of a test run.

Definition at line 1276 of file support.py.

01276 
01277 def modules_setup():
01278     return sys.modules.copy(),

def test.support.open_urlresource (   url,
  args,
  kw 
)

Definition at line 594 of file support.py.

00594 
00595 def open_urlresource(url, *args, **kw):
00596     import urllib.request, urllib.parse
00597 
00598     check = kw.pop('check', None)
00599 
00600     filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
00601 
00602     fn = os.path.join(os.path.dirname(__file__), "data", filename)
00603 
00604     def check_valid_file(fn):
00605         f = open(fn, *args, **kw)
00606         if check is None:
00607             return f
00608         elif check(f):
00609             f.seek(0)
00610             return f
00611         f.close()
00612 
00613     if os.path.exists(fn):
00614         f = check_valid_file(fn)
00615         if f is not None:
00616             return f
00617         unlink(fn)
00618 
00619     # Verify the requirement before downloading the file
00620     requires('urlfetch')
00621 
00622     print('\tfetching %s ...' % url, file=get_original_stdout())
00623     f = urllib.request.urlopen(url, timeout=15)
00624     try:
00625         with open(fn, "wb") as out:
00626             s = f.read()
00627             while s:
00628                 out.write(s)
00629                 s = f.read()
00630     finally:
00631         f.close()
00632 
00633     f = check_valid_file(fn)
00634     if f is not None:
00635         return f
00636     raise TestFailed('invalid resource "%s"' % fn)
00637 

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.patch (   test_instance,
  object_to_patch,
  attr_name,
  new_value 
)
Override 'object_to_patch'.'attr_name' with 'new_value'.

Also, add a cleanup procedure to 'test_instance' to restore
'object_to_patch' value for 'attr_name'.
The 'attr_name' should be a valid attribute for 'object_to_patch'.

Definition at line 1532 of file support.py.

01532 
01533 def patch(test_instance, object_to_patch, attr_name, new_value):
01534     """Override 'object_to_patch'.'attr_name' with 'new_value'.
01535 
01536     Also, add a cleanup procedure to 'test_instance' to restore
01537     'object_to_patch' value for 'attr_name'.
01538     The 'attr_name' should be a valid attribute for 'object_to_patch'.
01539 
01540     """
01541     # check that 'attr_name' is a real attribute for 'object_to_patch'
01542     # will raise AttributeError if it does not exist
01543     getattr(object_to_patch, attr_name)
01544 
01545     # keep a copy of the old value
01546     attr_is_local = False
01547     try:
01548         old_value = object_to_patch.__dict__[attr_name]
01549     except (AttributeError, KeyError):
01550         old_value = getattr(object_to_patch, attr_name, None)
01551     else:
01552         attr_is_local = True
01553 
01554     # restore the value when the test is done
01555     def cleanup():
01556         if attr_is_local:
01557             setattr(object_to_patch, attr_name, old_value)
01558         else:
01559             delattr(object_to_patch, attr_name)
01560 
01561     test_instance.addCleanup(cleanup)
01562 
01563     # actually override the attribute
01564     setattr(object_to_patch, attr_name, new_value)

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.precisionbigmemtest (   size,
  memuse 
)

Definition at line 1092 of file support.py.

01092 
01093 def precisionbigmemtest(size, memuse):
01094     def decorator(f):
01095         def wrapper(self):
01096             size = wrapper.size
01097             memuse = wrapper.memuse
01098             if not real_max_memuse:
01099                 maxsize = 5147
01100             else:
01101                 maxsize = size
01102 
01103                 if real_max_memuse and real_max_memuse < maxsize * memuse:
01104                     raise unittest.SkipTest(
01105                         "not enough memory: %.1fG minimum needed"
01106                         % (size * memuse / (1024 ** 3)))
01107 
01108             return f(self, maxsize)
01109         wrapper.size = size
01110         wrapper.memuse = memuse
01111         return wrapper
01112     return decorator

Here is the call graph for this function:

Here is the caller graph for this function:

Find if Python was built with optimizations.

Definition at line 976 of file support.py.

00976 
00977 def python_is_optimized():
00978     """Find if Python was built with optimizations."""
00979     cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
00980     final_opt = ""
00981     for opt in cflags.split():
00982         if opt.startswith('-O'):
00983             final_opt = opt
00984     return final_opt and final_opt != '-O0'
00985 
00986 
00987 #=======================================================================
00988 # Decorator for running a function in a different locale, correctly resetting
00989 # it afterwards.

Here is the call graph for this function:

Here is the caller graph for this function:

Use this function at the end of test_main() whenever sub-processes
are started.  This will help ensure that no extra children (zombies)
stick around to hog resources and create problems when looking
for refleaks.

Definition at line 1341 of file support.py.

01341 
01342 def reap_children():
01343     """Use this function at the end of test_main() whenever sub-processes
01344     are started.  This will help ensure that no extra children (zombies)
01345     stick around to hog resources and create problems when looking
01346     for refleaks.
01347     """
01348 
01349     # Reap all our dead child processes so we don't leave zombies around.
01350     # These hog resources and might be causing some of the buildbots to die.
01351     if hasattr(os, 'waitpid'):
01352         any_process = -1
01353         while True:
01354             try:
01355                 # This will raise an exception on Windows.  That's ok.
01356                 pid, status = os.waitpid(any_process, os.WNOHANG)
01357                 if pid == 0:
01358                     break
01359             except:
01360                 break
01361 
@contextlib.contextmanager

Here is the caller graph for this function:

def test.support.reap_threads (   func)
Use this function when threads are being used.  This will
ensure that the threads are cleaned up even when the test fails.
If threading is unavailable this function does nothing.

Definition at line 1324 of file support.py.

01324 
01325 def reap_threads(func):
01326     """Use this function when threads are being used.  This will
01327     ensure that the threads are cleaned up even when the test fails.
01328     If threading is unavailable this function does nothing.
01329     """
01330     if not _thread:
01331         return func
01332 
01333     @functools.wraps(func)
01334     def decorator(*args):
01335         key = threading_setup()
01336         try:
01337             return func(*args)
01338         finally:
01339             threading_cleanup(*key)
01340     return decorator

Here is the call graph for this function:

Definition at line 187 of file support.py.

00187 
00188 def record_original_stdout(stdout):
00189     global _original_stdout
00190     _original_stdout = stdout

def test.support.requires (   resource,
  msg = None 
)
Raise ResourceDenied if the specified resource is not available.

If the caller's module is __main__ then automatically return True.  The
possibility of False being returned occurs when regrtest.py is
executing.

Definition at line 283 of file support.py.

00283 
00284 def requires(resource, msg=None):
00285     """Raise ResourceDenied if the specified resource is not available.
00286 
00287     If the caller's module is __main__ then automatically return True.  The
00288     possibility of False being returned occurs when regrtest.py is
00289     executing.
00290     """
00291     if resource == 'gui' and not _is_gui_available():
00292         raise unittest.SkipTest("Cannot use the 'gui' resource")
00293     # see if the caller's module is __main__ - if so, treat as if
00294     # the resource was set
00295     if sys._getframe(1).f_globals.get("__name__") == "__main__":
00296         return
00297     if not is_resource_enabled(resource):
00298         if msg is None:
00299             msg = "Use of the `%s' resource not enabled" % resource
00300         raise ResourceDenied(msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.requires_mac_ver (   min_version)
Decorator raising SkipTest if the OS is Mac OS X and the OS X
version if less than min_version.

For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
is lesser than 10.5.

Definition at line 301 of file support.py.

00301 
00302 def requires_mac_ver(*min_version):
00303     """Decorator raising SkipTest if the OS is Mac OS X and the OS X
00304     version if less than min_version.
00305 
00306     For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
00307     is lesser than 10.5.
00308     """
00309     def decorator(func):
00310         @functools.wraps(func)
00311         def wrapper(*args, **kw):
00312             if sys.platform == 'darwin':
00313                 version_txt = platform.mac_ver()[0]
00314                 try:
00315                     version = tuple(map(int, version_txt.split('.')))
00316                 except ValueError:
00317                     pass
00318                 else:
00319                     if version < min_version:
00320                         min_version_txt = '.'.join(map(str, min_version))
00321                         raise unittest.SkipTest(
00322                             "Mac OS X %s or higher required, not %s"
00323                             % (min_version_txt, version_txt))
00324             return func(*args, **kw)
00325         wrapper.min_version = min_version
00326         return wrapper
00327     return decorator

Here is the call graph for this function:

def test.support.requires_resource (   resource)

Definition at line 1140 of file support.py.

01140 
01141 def requires_resource(resource):
01142     if resource == 'gui' and not _is_gui_available():
01143         return unittest.skip("resource 'gui' is not available")
01144     if is_resource_enabled(resource):
01145         return _id
01146     else:
01147         return unittest.skip("resource {0!r} is not enabled".format(resource))

Here is the call graph for this function:

def test.support.rmtree (   path)

Definition at line 208 of file support.py.

00208 
00209 def rmtree(path):
00210     try:
00211         shutil.rmtree(path)
00212     except OSError as error:
00213         # Unix returns ENOENT, Windows returns ESRCH.
00214         if error.errno not in (errno.ENOENT, errno.ESRCH):
00215             raise

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.run_doctest (   module,
  verbosity = None 
)
Run doctest on the given module.  Return (#failures, #tests).

If optional argument verbosity is not specified (or is None), pass
support's belief about verbosity on to doctest.  Else doctest's
usual behavior is used (it searches sys.argv for -v).

Definition at line 1249 of file support.py.

01249 
01250 def run_doctest(module, verbosity=None):
01251     """Run doctest on the given module.  Return (#failures, #tests).
01252 
01253     If optional argument verbosity is not specified (or is None), pass
01254     support's belief about verbosity on to doctest.  Else doctest's
01255     usual behavior is used (it searches sys.argv for -v).
01256     """
01257 
01258     import doctest
01259 
01260     if verbosity is None:
01261         verbosity = verbose
01262     else:
01263         verbosity = None
01264 
01265     f, t = doctest.testmod(module, verbose=verbosity)
01266     if f:
01267         raise TestFailed("%d of %d doctests failed" % (f, t))
01268     if verbose:
01269         print('doctest (%s) ... %d tests with zero failures' %
01270               (module.__name__, t))
01271     return f, t
01272 
01273 
01274 #=======================================================================
01275 # Support for saving and restoring the imported modules.

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.run_unittest (   classes)
Run tests from unittest.TestCase-derived classes.

Definition at line 1221 of file support.py.

01221 
01222 def run_unittest(*classes):
01223     """Run tests from unittest.TestCase-derived classes."""
01224     valid_types = (unittest.TestSuite, unittest.TestCase)
01225     suite = unittest.TestSuite()
01226     for cls in classes:
01227         if isinstance(cls, str):
01228             if cls in sys.modules:
01229                 suite.addTest(unittest.findTestCases(sys.modules[cls]))
01230             else:
01231                 raise ValueError("str arguments must be keys in sys.modules")
01232         elif isinstance(cls, valid_types):
01233             suite.addTest(cls)
01234         else:
01235             suite.addTest(unittest.makeSuite(cls))
01236     def case_pred(test):
01237         if match_tests is None:
01238             return True
01239         for name in test.id().split("."):
01240             if fnmatch.fnmatchcase(name, match_tests):
01241                 return True
01242         return False
01243     _filter_suite(suite, case_pred)
01244     _run_suite(suite)
01245 
01246 
01247 #=======================================================================
01248 # doctest driver.

Here is the call graph for this function:

def test.support.run_with_locale (   catstr,
  locales 
)

Definition at line 990 of file support.py.

00990 
00991 def run_with_locale(catstr, *locales):
00992     def decorator(func):
00993         def inner(*args, **kwds):
00994             try:
00995                 import locale
00996                 category = getattr(locale, catstr)
00997                 orig_locale = locale.setlocale(category)
00998             except AttributeError:
00999                 # if the test author gives us an invalid category string
01000                 raise
01001             except:
01002                 # cannot retrieve original locale, so do nothing
01003                 locale = orig_locale = None
01004             else:
01005                 for loc in locales:
01006                     try:
01007                         locale.setlocale(category, loc)
01008                         break
01009                     except:
01010                         pass
01011 
01012             # now run the function, resetting the locale on exceptions
01013             try:
01014                 return func(*args, **kwds)
01015             finally:
01016                 if locale and orig_locale:
01017                     locale.setlocale(category, orig_locale)
01018         inner.__name__ = func.__name__
01019         inner.__doc__ = func.__doc__
01020         return inner
01021     return decorator
01022 
01023 #=======================================================================
01024 # Big-memory-test support. Separate from 'resources' because memory use
01025 # should be configurable.
01026 
01027 # Some handy shorthands. Note that these are used for byte-limits as well
# as size-limits, in the various bigmem tests

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.set_memlimit (   limit)

Definition at line 1035 of file support.py.

01035 
01036 def set_memlimit(limit):
01037     global max_memuse
01038     global real_max_memuse
01039     sizes = {
01040         'k': 1024,
01041         'm': _1M,
01042         'g': _1G,
01043         't': 1024*_1G,
01044     }
01045     m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
01046                  re.IGNORECASE | re.VERBOSE)
01047     if m is None:
01048         raise ValueError('Invalid memory limit %r' % (limit,))
01049     memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
01050     real_max_memuse = memlimit
01051     if memlimit > MAX_Py_ssize_t:
01052         memlimit = MAX_Py_ssize_t
01053     if memlimit < _2G - 1:
01054         raise ValueError('Memory limit %r too low to be useful' % (limit,))
01055     max_memuse = memlimit

Here is the call graph for this function:

Skip decorator for tests that require functional symlink

Definition at line 1526 of file support.py.

01526 
01527 def skip_unless_symlink(test):
01528     """Skip decorator for tests that require functional symlink"""
01529     ok = can_symlink()
01530     msg = "Requires functional symlink implementation"
01531     return test if ok else unittest.skip(msg)(test)

Here is the call graph for this function:

def test.support.sortdict (   dict)

Definition at line 571 of file support.py.

00571 
00572 def sortdict(dict):
00573     "Like repr(dict), but in sorted order."
00574     items = sorted(dict.items())
00575     reprpairs = ["%r: %r" % pair for pair in items]
00576     withcommas = ", ".join(reprpairs)
00577     return "{%s}" % withcommas

Here is the call graph for this function:

Here is the caller graph for this function:

Strip the stderr of a Python process from potential debug output
emitted by the interpreter.

This will typically be run on the result of the communicate() method
of a subprocess.Popen object.

Definition at line 1415 of file support.py.

01415 
01416 def strip_python_stderr(stderr):
01417     """Strip the stderr of a Python process from potential debug output
01418     emitted by the interpreter.
01419 
01420     This will typically be run on the result of the communicate() method
01421     of a subprocess.Popen object.
01422     """
01423     stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
01424     return stderr

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.swap_attr (   obj,
  attr,
  new_val 
)
Temporary swap out an attribute with a new object.

Usage:
    with swap_attr(obj, "attr", 5):
        ...

    This will set obj.attr to 5 for the duration of the with: block,
    restoring the old value at the end of the block. If `attr` doesn't
    exist on `obj`, it will be created and then deleted at the end of the
    block.

Definition at line 1362 of file support.py.

01362 
01363 def swap_attr(obj, attr, new_val):
01364     """Temporary swap out an attribute with a new object.
01365 
01366     Usage:
01367         with swap_attr(obj, "attr", 5):
01368             ...
01369 
01370         This will set obj.attr to 5 for the duration of the with: block,
01371         restoring the old value at the end of the block. If `attr` doesn't
01372         exist on `obj`, it will be created and then deleted at the end of the
01373         block.
01374     """
01375     if hasattr(obj, attr):
01376         real_val = getattr(obj, attr)
01377         setattr(obj, attr, new_val)
01378         try:
01379             yield
01380         finally:
01381             setattr(obj, attr, real_val)
01382     else:
01383         setattr(obj, attr, new_val)
01384         try:
01385             yield
01386         finally:
01387             delattr(obj, attr)
01388 
@contextlib.contextmanager

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.swap_item (   obj,
  item,
  new_val 
)
Temporary swap out an item with a new object.

Usage:
    with swap_item(obj, "item", 5):
        ...

    This will set obj["item"] to 5 for the duration of the with: block,
    restoring the old value at the end of the block. If `item` doesn't
    exist on `obj`, it will be created and then deleted at the end of the
    block.

Definition at line 1389 of file support.py.

01389 
01390 def swap_item(obj, item, new_val):
01391     """Temporary swap out an item with a new object.
01392 
01393     Usage:
01394         with swap_item(obj, "item", 5):
01395             ...
01396 
01397         This will set obj["item"] to 5 for the duration of the with: block,
01398         restoring the old value at the end of the block. If `item` doesn't
01399         exist on `obj`, it will be created and then deleted at the end of the
01400         block.
01401     """
01402     if item in obj:
01403         real_val = obj[item]
01404         obj[item] = new_val
01405         try:
01406             yield
01407         finally:
01408             obj[item] = real_val
01409     else:
01410         obj[item] = new_val
01411         try:
01412             yield
01413         finally:
01414             del obj[item]

Here is the caller graph for this function:

def test.support.temp_cwd (   name = 'tempcwd',
  quiet = False,
  path = None 
)
Context manager that temporarily changes the CWD.

An existing path may be provided as *path*, in which case this
function makes no changes to the file system.

Otherwise, the new CWD is created in the current directory and it's
named *name*. If *quiet* is False (default) and it's not possible to
create or change the CWD, an error is raised.  If it's True, only a
warning is raised and the original CWD is used.

Definition at line 507 of file support.py.

00507 
00508 def temp_cwd(name='tempcwd', quiet=False, path=None):
00509     """
00510     Context manager that temporarily changes the CWD.
00511 
00512     An existing path may be provided as *path*, in which case this
00513     function makes no changes to the file system.
00514 
00515     Otherwise, the new CWD is created in the current directory and it's
00516     named *name*. If *quiet* is False (default) and it's not possible to
00517     create or change the CWD, an error is raised.  If it's True, only a
00518     warning is raised and the original CWD is used.
00519     """
00520     saved_dir = os.getcwd()
00521     is_temporary = False
00522     if path is None:
00523         path = name
00524         try:
00525             os.mkdir(name)
00526             is_temporary = True
00527         except OSError:
00528             if not quiet:
00529                 raise
00530             warnings.warn('tests may fail, unable to create temp CWD ' + name,
00531                           RuntimeWarning, stacklevel=3)
00532     try:
00533         os.chdir(path)
00534     except OSError:
00535         if not quiet:
00536             raise
00537         warnings.warn('tests may fail, unable to change the CWD to ' + name,
00538                       RuntimeWarning, stacklevel=3)
00539     try:
00540         yield os.getcwd()
00541     finally:
00542         os.chdir(saved_dir)
00543         if is_temporary:
00544             rmtree(name)
00545 
00546 
@contextlib.contextmanager

Here is the call graph for this function:

def test.support.temp_umask (   umask)
Context manager that temporarily sets the process umask.

Definition at line 547 of file support.py.

00547 
00548 def temp_umask(umask):
00549     """Context manager that temporarily sets the process umask."""
00550     oldmask = os.umask(umask)
00551     try:
00552         yield
00553     finally:
00554         os.umask(oldmask)
00555 

Here is the caller graph for this function:

def test.support.threading_cleanup (   original_values)

Definition at line 1312 of file support.py.

01312 
01313 def threading_cleanup(*original_values):
01314     if not _thread:
01315         return
01316     _MAX_COUNT = 10
01317     for count in range(_MAX_COUNT):
01318         values = _thread._count(), threading._dangling
01319         if values == original_values:
01320             break
01321         time.sleep(0.1)
01322         gc_collect()
01323     # XXX print a warning in case of failure?

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 1306 of file support.py.

01306 
01307 def threading_setup():
01308     if _thread:
01309         return _thread._count(), threading._dangling.copy()
01310     else:
01311         return 1, ()

Here is the caller graph for this function:

def test.support.transient_internet (   resource_name,
  timeout = 30.0,
  errnos = () 
)
Return a context manager that raises ResourceDenied when various issues
with the Internet connection manifest themselves as exceptions.

Definition at line 868 of file support.py.

00868 
00869 def transient_internet(resource_name, *, timeout=30.0, errnos=()):
00870     """Return a context manager that raises ResourceDenied when various issues
00871     with the Internet connection manifest themselves as exceptions."""
00872     default_errnos = [
00873         ('ECONNREFUSED', 111),
00874         ('ECONNRESET', 104),
00875         ('EHOSTUNREACH', 113),
00876         ('ENETUNREACH', 101),
00877         ('ETIMEDOUT', 110),
00878     ]
00879     default_gai_errnos = [
00880         ('EAI_AGAIN', -3),
00881         ('EAI_NONAME', -2),
00882         ('EAI_NODATA', -5),
00883         # Encountered when trying to resolve IPv6-only hostnames
00884         ('WSANO_DATA', 11004),
00885     ]
00886 
00887     denied = ResourceDenied("Resource '%s' is not available" % resource_name)
00888     captured_errnos = errnos
00889     gai_errnos = []
00890     if not captured_errnos:
00891         captured_errnos = [getattr(errno, name, num)
00892                            for (name, num) in default_errnos]
00893         gai_errnos = [getattr(socket, name, num)
00894                       for (name, num) in default_gai_errnos]
00895 
00896     def filter_error(err):
00897         n = getattr(err, 'errno', None)
00898         if (isinstance(err, socket.timeout) or
00899             (isinstance(err, socket.gaierror) and n in gai_errnos) or
00900             n in captured_errnos):
00901             if not verbose:
00902                 sys.stderr.write(denied.args[0] + "\n")
00903             raise denied from err
00904 
00905     old_timeout = socket.getdefaulttimeout()
00906     try:
00907         if timeout is not None:
00908             socket.setdefaulttimeout(timeout)
00909         yield
00910     except IOError as err:
00911         # urllib can wrap original socket errors multiple times (!), we must
00912         # unwrap to get at the original error.
00913         while True:
00914             a = err.args
00915             if len(a) >= 1 and isinstance(a[0], IOError):
00916                 err = a[0]
00917             # The error can also be wrapped as args[1]:
00918             #    except socket.error as msg:
00919             #        raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
00920             elif len(a) >= 2 and isinstance(a[1], IOError):
00921                 err = a[1]
00922             else:
00923                 break
00924         filter_error(err)
00925         raise
00926     # XXX should we catch generic exceptions and look for their
00927     # __cause__ or __context__?
00928     finally:
00929         socket.setdefaulttimeout(old_timeout)
00930 
00931 
@contextlib.contextmanager

Here is the call graph for this function:

Here is the caller graph for this function:

def test.support.unlink (   filename)

Definition at line 200 of file support.py.

00200 
00201 def unlink(filename):
00202     try:
00203         os.unlink(filename)
00204     except OSError as error:
00205         # The filename need not exist.
00206         if error.errno not in (errno.ENOENT, errno.ENOTDIR):
00207             raise

Here is the caller graph for this function:

def test.support.unload (   name)

Definition at line 194 of file support.py.

00194 
00195 def unload(name):
00196     try:
00197         del sys.modules[name]
00198     except KeyError:
00199         pass

Here is the caller graph for this function:


Variable Documentation

Definition at line 1029 of file support.py.

Definition at line 1028 of file support.py.

Definition at line 1030 of file support.py.

Definition at line 1031 of file support.py.

Initial value:
00001 [
00002     "Error", "TestFailed", "ResourceDenied", "import_module",
00003     "verbose", "use_resources", "max_memuse", "record_original_stdout",
00004     "get_original_stdout", "unload", "unlink", "rmtree", "forget",
00005     "is_resource_enabled", "requires", "requires_mac_ver",
00006     "find_unused_port", "bind_port",
00007     "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
00008     "findfile", "sortdict", "check_syntax_error", "open_urlresource",
00009     "check_warnings", "CleanImport", "EnvironmentVarGuard",
00010     "TransientResource", "captured_output", "captured_stdout",
00011     "captured_stdin", "captured_stderr",
00012     "time_out", "socket_peer_reset", "ioerror_peer_reset",
00013     "run_with_locale", 'temp_umask', "transient_internet",
00014     "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
00015     "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
00016     "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
00017     "swap_item", "swap_attr", "requires_IEEE_754",
00018     "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink",
00019     "import_fresh_module", "failfast",
00020     ]

Definition at line 38 of file support.py.

Definition at line 1510 of file support.py.

Definition at line 186 of file support.py.

Definition at line 30 of file support.py.

Definition at line 180 of file support.py.

Definition at line 423 of file support.py.

string test.support.HOST = 'localhost'

Definition at line 328 of file support.py.

tuple test.support.ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)

Definition at line 864 of file support.py.

tuple test.support.is_jython = sys.platform.startswith('java')

Definition at line 446 of file support.py.

Definition at line 181 of file support.py.

Definition at line 177 of file support.py.

Definition at line 1033 of file support.py.

Definition at line 35 of file support.py.

Definition at line 179 of file support.py.

Initial value:
00001 unittest.skipUnless(
00002     float.__getformat__("double").startswith("IEEE"),
00003     "test requires IEEE 754 doubles")

Definition at line 442 of file support.py.

Definition at line 504 of file support.py.

Definition at line 863 of file support.py.

Definition at line 451 of file support.py.

tuple test.support.TESTFN_ENCODING = sys.getfilesystemencoding()

Definition at line 468 of file support.py.

Definition at line 473 of file support.py.

tuple test.support.TESTFN_UNICODE = "-\xe0\xf2\u0258\u0141\u011f"

Definition at line 461 of file support.py.

Definition at line 31 of file support.py.

tuple test.support.time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)

Definition at line 862 of file support.py.

Definition at line 176 of file support.py.

Definition at line 175 of file support.py.