Package test :: Module test_support |
[hide private]
[frames] | no frames]

# Module test_support

source code

Supporting definitions for the Python regression tests.

Classes | [hide private]
| Error Base class for regression test exceptions.
| TestFailed Test failed.
| ResourceDenied Test skipped because it requested a disallowed resource.
| WarningsRecorder Convenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager.
| CleanImport Context manager to force import to return a new module reference.
| EnvironmentVarGuard Class to help protect the environment variable properly.
| DirsOnSysPath Context manager to temporarily add directories to sys.path.
| TransientResource Raise ResourceDenied if an exception is raised while the context manager is in effect that matches the specified exception and attributes.
| BasicTestRunner

Functions | [hide private]
_ignore_deprecated_imports(*args, **kwds) Context manager to suppress package and module deprecation warnings when importing them. | source code
import_module(name, deprecated=False) Import and return the module to be tested, raising SkipTest if it is not available. | source code
_save_and_remove_module(name, orig_modules) Helper function to save and remove a module from sys.modules | source code
_save_and_block_module(name, orig_modules) Helper function to save and block a module in sys.modules | source code
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. | source code
get_attribute(obj, name) Get an attribute, raising SkipTest if AttributeError is raised. | source code
record_original_stdout(stdout) | source code
get_original_stdout() | source code
unload(name) | source code
unlink(filename) | source code
rmtree(path) | source code
forget(modname) "Forget" a module was ever imported by removing it from sys.modules and deleting any .pyc and .pyo files. | source code
is_resource_enabled(resource) Test whether a resource is enabled. | source code
requires(resource, msg=None) Raise ResourceDenied if the specified resource is not available. | source code
find_unused_port(family=2, socktype=1) Returns an unused port that should be suitable for binding. | source code
bind_port(sock, host=`'``localhost``'`) Bind the socket to a free port and return the port number. | source code
fcmp(x, y) | source code
temp_cwd(*args, **kwds) Context manager that creates a temporary directory and set it as CWD. | source code
findfile(file, here=`'``/usr/lib/python2.7/test/test_support.pyc``'`, subdir=None) Try to find a file on sys.path and the working directory. | source code
sortdict(dict) Like repr(dict), but in sorted order. | source code
make_bad_fd() Create an invalid file descriptor by opening and closing a file and return its fd. | source code
check_syntax_error(testcase, statement) | source code
open_urlresource(url, check=None) | source code
_filterwarnings(filters, quiet=False) Catch the warnings, then check if all the expected warnings have been raised and re-raise unexpected warnings. | source code
check_warnings(*args, **kwds) Context manager to silence warnings. | source code
check_py3k_warnings(*args, **kwds) Context manager to silence py3k warnings. | source code
transient_internet(*args, **kwds) Return a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions. | source code
captured_output(*args, **kwds) Run the 'with' statement body using a StringIO object in place of a specific attribute on the sys module. | source code
captured_stdout() | source code
captured_stdin() | source code
gc_collect() Force as many objects as possible to be collected. | source code
run_with_locale(catstr, *locales) | source code
set_memlimit(limit) | source code
bigmemtest(minsize, memuse, overhead=5242880) Decorator for bigmem tests. | source code
precisionbigmemtest(size, memuse, overhead=5242880) | source code
bigaddrspacetest(f) Decorator for tests that fill the address space. | source code
_id(obj) | source code
requires_resource(resource) | source code
cpython_only(test) Decorator for tests only applicable on CPython. | source code
impl_detail(msg=None, **guards) | source code
_parse_guards(guards) | source code
check_impl_detail(**guards) This function returns True or False depending on the host platform. | source code
_run_suite(suite) Run tests from a unittest.TestSuite-derived class. | source code
run_unittest(*classes) Run tests from unittest.TestCase-derived classes. | source code
run_doctest(module, verbosity=None) Run doctest on the given module. | source code
threading_setup() | source code
threading_cleanup(nb_threads) | source code
reap_threads(func) Use this function when threads are being used. | source code
reap_children() Use this function at the end of test_main() whenever sub-processes are started. | source code
py3k_bytes(b) Emulate the py3k bytes() constructor. | source code
args_from_interpreter_flags() Return a list of command-line arguments reproducing the current settings in sys.flags. | source code
strip_python_stderr(stderr) Strip the stderr of a Python process from potential debug output emitted by the interpreter. | source code

Variables | [hide private]
| verbose = `1`
| use_resources = `None`
| max_memuse = `0`
| real_max_memuse = `0`
| _original_stdout = `None`
| HOST = ``'``localhost``'``
| FUZZ = `1e-06`
| have_unicode = `True`
| is_jython = `False`
| TESTFN_UNICODE = ``u'``@test-àò``'``
| TESTFN_ENCODING = ``'``UTF-8``'``
| TESTFN_UNENCODABLE = `None`
| TESTFN = ``'``@test_7043_tmp``'``
| SAVEDCWD = ``'``/home/sch/Documents/Bouquin_Python/exemples/15``'``
| _1M = `1048576`
| _1G = `1073741824`
| _2G = `2147483648`
| _4G = `4294967296`
| MAX_Py_ssize_t = `9223372036854775807`
| __package__ = ``'``test``'``

Function Details | [hide private]

### _ignore_deprecated_imports(*args, **kwds) | source code
Context manager to suppress package and module deprecation warnings when importing them. If ignore is False, this context manager has no effect. Decorators: `@contextlib.contextmanager`

### import_module(name, deprecated=False) | source code
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.

### _save_and_remove_module(name, orig_modules) | source code
Helper function to save and remove a module from sys.modules Return value is True if the module was in sys.modules and False otherwise.

### _save_and_block_module(name, orig_modules) | source code
Helper function to save and block a module in sys.modules Return value is True if the module was in sys.modules and False otherwise.

### import_fresh_module(name, fresh=`(``)`, blocked=`(``)`, deprecated=False) | source code
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. 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.

### is_resource_enabled(resource) | source code
Test whether a resource is enabled. Known resources are set by regrtest.py.

### requires(resource, msg=None) | source code
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.

### find_unused_port(family=2, socktype=1) | source code
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.

### bind_port(sock, host=`'``localhost``'`) | source code
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.

### temp_cwd(*args, **kwds) | source code
Context manager that creates a temporary directory and set it as CWD. 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. Decorators: `@contextlib.contextmanager`

### findfile(file, here=`'``/usr/lib/python2.7/test/test_support.pyc``'`, subdir=None) | source code
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).

### _filterwarnings(filters, quiet=False) | source code
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.

### check_warnings(*args, **kwds) | source code
    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)
Decorators: `@contextlib.contextmanager`

### check_py3k_warnings(*args, **kwds) | source code
    Context manager to silence py3k 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 False)

    Without argument, it defaults to:
        check_py3k_warnings(("", DeprecationWarning), quiet=False)
Decorators: `@contextlib.contextmanager`

### transient_internet(*args, **kwds) | source code
Return a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions. Decorators: `@contextlib.contextmanager`

### captured_output(*args, **kwds) | source code
Run the 'with' statement body using a StringIO object in place of a specific attribute on the sys module. Example use (with 'stream_name=stdout'):
      with captured_stdout() as s:
          print "hello"
      assert s.getvalue() == "hello"
Decorators: `@contextlib.contextmanager`

### gc_collect() | source code
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.

### bigmemtest(minsize, memuse, overhead=5242880) | source code
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. 'overhead' specifies fixed overhead, independent of the testsize, and defaults to 5Mb. 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.

### check_impl_detail(**guards) | source code
    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

### run_doctest(module, verbosity=None) | source code
Run doctest on the given module. Return (#failures, #tests). If optional argument verbosity is not specified (or is None), pass test_support's belief about verbosity on to doctest. Else doctest's usual behavior is used (it searches sys.argv for -v).

### reap_threads(func) | source code
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.

### reap_children() | source code
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.

### py3k_bytes(b) | source code
Emulate the py3k bytes() constructor. NOTE: This is only a best effort function.

### strip_python_stderr(stderr) | source code
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.