14adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao"""Supporting definitions for the Python regression tests."""
24adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
34adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoif __name__ != 'test.test_support':
44adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    raise ImportError('test_support must be imported from the test package')
54adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
64adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport contextlib
74adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport errno
84adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport functools
94adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport gc
104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport socket
114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport sys
124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport os
134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport platform
144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport shutil
154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport warnings
164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport unittest
174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport importlib
184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport UserDict
194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport re
204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport time
214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport struct
224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport _testcapi
234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoimport sysconfig
244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaotry:
254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    import thread
264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoexcept ImportError:
274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    thread = None
284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao__all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "verbose", "use_resources", "max_memuse", "record_original_stdout",
314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "get_original_stdout", "unload", "unlink", "rmtree", "forget",
324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "is_resource_enabled", "requires", "find_unused_port", "bind_port",
334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ",
344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "SAVEDCWD", "temp_cwd", "findfile", "sortdict", "check_syntax_error",
354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "open_urlresource", "check_warnings", "check_py3k_warnings",
364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "CleanImport", "EnvironmentVarGuard", "captured_output",
374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "captured_stdout", "TransientResource", "transient_internet",
384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "threading_cleanup", "reap_children", "cpython_only",
414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "check_impl_detail", "get_attribute", "py3k_bytes",
424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "import_fresh_module", "threading_cleanup", "reap_children",
434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           "strip_python_stderr"]
444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass Error(Exception):
464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Base class for regression test exceptions."""
474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass TestFailed(Error):
494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Test failed."""
504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass ResourceDenied(unittest.SkipTest):
524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Test skipped because it requested a disallowed resource.
534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    This is raised when a test calls requires() for a resource that
554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    has not been enabled.  It is used to distinguish between expected
564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    and unexpected skips.
574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao@contextlib.contextmanager
604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef _ignore_deprecated_imports(ignore=True):
614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Context manager to suppress package and module deprecation
624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    warnings when importing them.
634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If ignore is False, this context manager has no effect."""
654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if ignore:
664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        with warnings.catch_warnings():
674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            warnings.filterwarnings("ignore", ".+ (module|package)",
684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                    DeprecationWarning)
694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            yield
704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        yield
724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef import_module(name, deprecated=False):
754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Import and return the module to be tested, raising SkipTest if
764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    it is not available.
774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If deprecated is True, any module or package deprecation messages
794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    will be suppressed."""
804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    with _ignore_deprecated_imports(deprecated):
814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return importlib.import_module(name)
834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        except ImportError, msg:
844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            raise unittest.SkipTest(str(msg))
854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef _save_and_remove_module(name, orig_modules):
884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Helper function to save and remove a module from sys.modules
894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao       Raise ImportError if the module can't be imported."""
914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # try to import the module and raise an error if it can't be imported
924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if name not in sys.modules:
934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        __import__(name)
944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        del sys.modules[name]
954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for modname in list(sys.modules):
964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if modname == name or modname.startswith(name + '.'):
974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            orig_modules[modname] = sys.modules[modname]
984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            del sys.modules[modname]
994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef _save_and_block_module(name, orig_modules):
1014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Helper function to save and block a module in sys.modules
1024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao       Return True if the module was in sys.modules, False otherwise."""
1044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    saved = True
1054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
1064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        orig_modules[name] = sys.modules[name]
1074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except KeyError:
1084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        saved = False
1094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    sys.modules[name] = None
1104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return saved
1114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
1144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Imports and returns a module, deliberately bypassing the sys.modules cache
1154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    and importing a fresh copy of the module. Once the import is complete,
1164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the sys.modules cache is restored to its original state.
1174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Modules named in fresh are also imported anew if needed by the import.
1194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If one of these modules can't be imported, None is returned.
1204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Importing of modules named in blocked is prevented while the fresh import
1224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    takes place.
1234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If deprecated is True, any module or package deprecation messages
1254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    will be suppressed."""
1264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # NOTE: test_heapq, test_json, and test_warnings include extra sanity
1274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # checks to make sure that this utility function is working as expected
1284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    with _ignore_deprecated_imports(deprecated):
1294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Keep track of modules saved for later restoration as well
1304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # as those which just need a blocking entry removed
1314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        orig_modules = {}
1324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        names_to_remove = []
1334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _save_and_remove_module(name, orig_modules)
1344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
1354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            for fresh_name in fresh:
1364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                _save_and_remove_module(fresh_name, orig_modules)
1374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            for blocked_name in blocked:
1384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if not _save_and_block_module(blocked_name, orig_modules):
1394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    names_to_remove.append(blocked_name)
1404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            fresh_module = importlib.import_module(name)
1414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        except ImportError:
1424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            fresh_module = None
1434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        finally:
1444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            for orig_name, module in orig_modules.items():
1454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                sys.modules[orig_name] = module
1464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            for name_to_remove in names_to_remove:
1474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                del sys.modules[name_to_remove]
1484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return fresh_module
1494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef get_attribute(obj, name):
1524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Get an attribute, raising SkipTest if AttributeError is raised."""
1534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
1544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        attribute = getattr(obj, name)
1554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except AttributeError:
1564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise unittest.SkipTest("module %s has no attribute %s" % (
1574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            obj.__name__, name))
1584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
1594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return attribute
1604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoverbose = 1              # Flag set to 0 by regrtest.py
1634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaouse_resources = None     # Flag set to [] by regrtest.py
1644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaomax_memuse = 0           # Disable bigmem tests (they will still be run with
1654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                         # small sizes, to make sure they work.)
1664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoreal_max_memuse = 0
1674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# _original_stdout is meant to hold stdout at the time regrtest began.
1694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
1704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# The point is to have some flavor of stdout the user can actually see.
1714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_original_stdout = None
1724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef record_original_stdout(stdout):
1734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    global _original_stdout
1744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    _original_stdout = stdout
1754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef get_original_stdout():
1774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return _original_stdout or sys.stdout
1784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef unload(name):
1804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
1814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        del sys.modules[name]
1824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except KeyError:
1834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        pass
1844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
1854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoif sys.platform.startswith("win"):
1864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def _waitfor(func, pathname, waitall=False):
1874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Peform the operation
1884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        func(pathname)
1894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Now setup the wait loop
1904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if waitall:
1914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            dirname = pathname
1924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        else:
1934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            dirname, name = os.path.split(pathname)
1944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            dirname = dirname or '.'
1954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Check for `pathname` to be removed from the filesystem.
1964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # The exponential backoff of the timeout amounts to a total
1974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # of ~1 second after which the deletion is probably an error
1984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # anyway.
1994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Testing on a i7@4.3GHz shows that usually only 1 iteration is
2004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # required when contention occurs.
2014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        timeout = 0.001
2024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        while timeout < 1.0:
2034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # Note we are only testing for the existance of the file(s) in
2044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # the contents of the directory regardless of any security or
2054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # access rights.  If we have made it this far, we have sufficient
2064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # permissions to do that much using Python's equivalent of the
2074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # Windows API FindFirstFile.
2084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # Other Windows APIs can fail or give incorrect results when
2094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # dealing with files that are pending deletion.
2104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            L = os.listdir(dirname)
2114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if not (L if waitall else name in L):
2124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                return
2134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # Increase the timeout and try again
2144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            time.sleep(timeout)
2154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            timeout *= 2
2164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        warnings.warn('tests may fail, delete still pending for ' + pathname,
2174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                      RuntimeWarning, stacklevel=4)
2184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def _unlink(filename):
2204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _waitfor(os.unlink, filename)
2214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def _rmdir(dirname):
2234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _waitfor(os.rmdir, dirname)
2244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def _rmtree(path):
2264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        def _rmtree_inner(path):
2274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            for name in os.listdir(path):
2284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                fullname = os.path.join(path, name)
2294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if os.path.isdir(fullname):
2304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    _waitfor(_rmtree_inner, fullname, waitall=True)
2314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    os.rmdir(fullname)
2324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                else:
2334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    os.unlink(fullname)
2344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _waitfor(_rmtree_inner, path, waitall=True)
2354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _waitfor(os.rmdir, path)
2364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoelse:
2374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    _unlink = os.unlink
2384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    _rmdir = os.rmdir
2394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    _rmtree = shutil.rmtree
2404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef unlink(filename):
2424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
2434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _unlink(filename)
2444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except OSError:
2454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        pass
2464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef rmdir(dirname):
2484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
2494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _rmdir(dirname)
2504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except OSError as error:
2514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # The directory need not exist.
2524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if error.errno != errno.ENOENT:
2534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            raise
2544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef rmtree(path):
2564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
2574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        _rmtree(path)
2584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except OSError, e:
2594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Unix returns ENOENT, Windows returns ESRCH.
2604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if e.errno not in (errno.ENOENT, errno.ESRCH):
2614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            raise
2624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef forget(modname):
2644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    '''"Forget" a module was ever imported by removing it from sys.modules and
2654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    deleting any .pyc and .pyo files.'''
2664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    unload(modname)
2674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for dirname in sys.path:
2684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
2694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Deleting the .pyo file cannot be within the 'try' for the .pyc since
2704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # the chance exists that there is no .pyc (and thus the 'try' statement
2714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # is exited) but there is a .pyo file.
2724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        unlink(os.path.join(dirname, modname + os.extsep + 'pyo'))
2734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef is_resource_enabled(resource):
2754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Test whether a resource is enabled.  Known resources are set by
2764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    regrtest.py."""
2774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return use_resources is not None and resource in use_resources
2784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef requires(resource, msg=None):
2804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Raise ResourceDenied if the specified resource is not available.
2814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If the caller's module is __main__ then automatically return True.  The
2834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    possibility of False being returned occurs when regrtest.py is executing."""
2844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # see if the caller's module is __main__ - if so, treat as if
2854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # the resource was set
2864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if sys._getframe(1).f_globals.get("__name__") == "__main__":
2874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return
2884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if not is_resource_enabled(resource):
2894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if msg is None:
2904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            msg = "Use of the `%s' resource not enabled" % resource
2914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise ResourceDenied(msg)
2924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2934adfde8bc82dd39f59e0445588c3e599ada477dJosh GaoHOST = 'localhost'
2944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
2954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
2964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Returns an unused port that should be suitable for binding.  This is
2974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    achieved by creating a temporary socket with the same family and type as
2984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
2994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the specified host address (defaults to 0.0.0.0) with the port set to 0,
3004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    eliciting an unused ephemeral port from the OS.  The temporary socket is
3014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    then closed and deleted, and the ephemeral port is returned.
3024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Either this method or bind_port() should be used for any tests where a
3044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    server socket needs to be bound to a particular port for the duration of
3054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the test.  Which one to use depends on whether the calling code is creating
3064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    a python socket, or if an unused port needs to be provided in a constructor
3074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    or passed to an external program (i.e. the -accept argument to openssl's
3084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    s_server mode).  Always prefer bind_port() over find_unused_port() where
3094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
3104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    socket is bound to a hard coded port, the ability to run multiple instances
3114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    of the test simultaneously on the same host is compromised, which makes the
3124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
3134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    may simply manifest as a failed test, which can be recovered from without
3144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    intervention in most cases, but on Windows, the entire python process can
3154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    completely and utterly wedge, requiring someone to log in to the buildbot
3164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    and manually kill the affected process.
3174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    (This is easy to reproduce on Windows, unfortunately, and can be traced to
3194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the SO_REUSEADDR socket option having different semantics on Windows versus
3204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
3214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    listen and then accept connections on identical host/ports.  An EADDRINUSE
3224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    socket.error will be raised at some point (depending on the platform and
3234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the order bind and listen were called on each socket).
3244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
3264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    will ever be raised when attempting to bind two identical host/ports. When
3274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    accept() is called on each socket, the second caller's process will steal
3284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the port from the first caller, leaving them both in an awkwardly wedged
3294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    state where they'll no longer respond to any signals or graceful kills, and
3304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    must be forcibly killed via OpenProcess()/TerminateProcess().
3314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
3334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    instead of SO_REUSEADDR, which effectively affords the same semantics as
3344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
3354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Source world compared to Windows ones, this is a common mistake.  A quick
3364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
3374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    openssl.exe is called with the 's_server' option, for example. See
3384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    http://bugs.python.org/issue2550 for more info.  The following site also
3394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    has a very thorough description about the implications of both REUSEADDR
3404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    and EXCLUSIVEADDRUSE on Windows:
3414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
3424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    XXX: although this approach is a vast improvement on previous attempts to
3444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    elicit unused ports, it rests heavily on the assumption that the ephemeral
3454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    port returned to us by the OS won't immediately be dished back out to some
3464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    other process when we close and delete our temporary socket but before our
3474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    calling code has a chance to bind the returned port.  We can deal with this
3484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    issue if/when we come across it."""
3494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    tempsock = socket.socket(family, socktype)
3504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    port = bind_port(tempsock)
3514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    tempsock.close()
3524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    del tempsock
3534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return port
3544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef bind_port(sock, host=HOST):
3564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Bind the socket to a free port and return the port number.  Relies on
3574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    ephemeral ports in order to ensure we are using an unbound port.  This is
3584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    important as many tests may be running simultaneously, especially in a
3594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    buildbot environment.  This method raises an exception if the sock.family
3604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
3614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
3624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for TCP/IP sockets.  The only case for setting these options is testing
3634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    multicasting via multiple UDP sockets.
3644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
3664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    on Windows), it will be set on the socket.  This will prevent anyone else
3674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    from bind()'ing to our host/port for the duration of the test.
3684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
3694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
3704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if hasattr(socket, 'SO_REUSEADDR'):
3714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
3724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                raise TestFailed("tests should never set the SO_REUSEADDR "   \
3734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                 "socket option on TCP/IP sockets!")
3744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if hasattr(socket, 'SO_REUSEPORT'):
3754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
3764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                raise TestFailed("tests should never set the SO_REUSEPORT "   \
3774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                 "socket option on TCP/IP sockets!")
3784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
3794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
3804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    sock.bind((host, 0))
3824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    port = sock.getsockname()[1]
3834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return port
3844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3854adfde8bc82dd39f59e0445588c3e599ada477dJosh GaoFUZZ = 1e-6
3864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
3874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef fcmp(x, y): # fuzzy comparison function
3884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if isinstance(x, float) or isinstance(y, float):
3894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
3904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            fuzz = (abs(x) + abs(y)) * FUZZ
3914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if abs(x-y) <= fuzz:
3924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                return 0
3934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        except:
3944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            pass
3954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    elif type(x) == type(y) and isinstance(x, (tuple, list)):
3964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        for i in range(min(len(x), len(y))):
3974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            outcome = fcmp(x[i], y[i])
3984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if outcome != 0:
3994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                return outcome
4004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return (len(x) > len(y)) - (len(x) < len(y))
4014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return (x > y) - (x < y)
4024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# A constant likely larger than the underlying OS pipe buffer size, to
4054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# make writes blocking.
4064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Windows limit seems to be around 512 B, and many Unix kernels have a
4074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
4084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# (see issue #17835 for a discussion of this number).
4094adfde8bc82dd39f59e0445588c3e599ada477dJosh GaoPIPE_MAX_SIZE = 4 *1024 * 1024 + 1
4104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaotry:
4134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    unicode
4144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    have_unicode = True
4154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoexcept NameError:
4164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    have_unicode = False
4174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaois_jython = sys.platform.startswith('java')
4194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Filename used for testing
4214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoif os.name == 'java':
4224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Jython disallows @ in module names
4234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    TESTFN = '$test'
4244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoelif os.name == 'riscos':
4254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    TESTFN = 'testfile'
4264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoelse:
4274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    TESTFN = '@test'
4284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Unicode name only used if TEST_FN_ENCODING exists for the platform.
4294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if have_unicode:
4304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
4314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # TESTFN_UNICODE is a filename that can be encoded using the
4324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # file system encoding, but *not* with the default (ascii) encoding
4334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if isinstance('', unicode):
4344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # python -U
4354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # XXX perhaps unicode() should accept Unicode strings?
4364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            TESTFN_UNICODE = "@test-\xe0\xf2"
4374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        else:
4384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # 2 latin characters.
4394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1")
4404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        TESTFN_ENCODING = sys.getfilesystemencoding()
4414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # TESTFN_UNENCODABLE is a filename that should *not* be
4424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # able to be encoded by *either* the default or filesystem encoding.
4434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # This test really only makes sense on Windows NT platforms
4444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # which have special Unicode support in posixmodule.
4454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if (not hasattr(sys, "getwindowsversion") or
4464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                sys.getwindowsversion()[3] < 2): #  0=win32s or 1=9x/ME
4474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            TESTFN_UNENCODABLE = None
4484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        else:
4494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # Japanese characters (I think - from bug 846133)
4504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            TESTFN_UNENCODABLE = eval('u"@test-\u5171\u6709\u3055\u308c\u308b"')
4514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            try:
4524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # XXX - Note - should be using TESTFN_ENCODING here - but for
4534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # Windows, "mbcs" currently always operates as if in
4544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # errors=ignore' mode - hence we get '?' characters rather than
4554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # the exception.  'Latin1' operates as we expect - ie, fails.
4564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # See [ 850997 ] mbcs encoding ignores errors
4574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                TESTFN_UNENCODABLE.encode("Latin1")
4584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            except UnicodeEncodeError:
4594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                pass
4604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
4614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                print \
4624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                'WARNING: The filename %r CAN be encoded by the filesystem.  ' \
4634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                'Unicode filename tests may not be effective' \
4644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                % TESTFN_UNENCODABLE
4654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Disambiguate TESTFN for parallel testing, while letting it remain a valid
4684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# module name.
4694adfde8bc82dd39f59e0445588c3e599ada477dJosh GaoTESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
4704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Save the initial cwd
4724adfde8bc82dd39f59e0445588c3e599ada477dJosh GaoSAVEDCWD = os.getcwd()
4734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao@contextlib.contextmanager
4754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef temp_cwd(name='tempcwd', quiet=False):
4764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
4774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Context manager that creates a temporary directory and set it as CWD.
4784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
4794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    The new CWD is created in the current directory and it's named *name*.
4804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If *quiet* is False (default) and it's not possible to create or change
4814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the CWD, an error is raised.  If it's True, only a warning is raised
4824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    and the original CWD is used.
4834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
4844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if have_unicode and isinstance(name, unicode):
4854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
4864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            name = name.encode(sys.getfilesystemencoding() or 'ascii')
4874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        except UnicodeEncodeError:
4884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if not quiet:
4894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                raise unittest.SkipTest('unable to encode the cwd name with '
4904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                        'the filesystem encoding.')
4914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    saved_dir = os.getcwd()
4924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    is_temporary = False
4934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
4944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        os.mkdir(name)
4954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        os.chdir(name)
4964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        is_temporary = True
4974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except OSError:
4984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if not quiet:
4994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            raise
5004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        warnings.warn('tests may fail, unable to change the CWD to ' + name,
5014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                      RuntimeWarning, stacklevel=3)
5024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
5034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        yield os.getcwd()
5044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    finally:
5054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        os.chdir(saved_dir)
5064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if is_temporary:
5074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            rmtree(name)
5084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef findfile(file, here=__file__, subdir=None):
5114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Try to find a file on sys.path and the working directory.  If it is not
5124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    found the argument passed to the function is returned (this does not
5134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    necessarily signal failure; could still be the legitimate path)."""
5144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if os.path.isabs(file):
5154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return file
5164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if subdir is not None:
5174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        file = os.path.join(subdir, file)
5184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    path = sys.path
5194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    path = [os.path.dirname(here)] + path
5204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for dn in path:
5214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        fn = os.path.join(dn, file)
5224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if os.path.exists(fn): return fn
5234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return file
5244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef sortdict(dict):
5264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    "Like repr(dict), but in sorted order."
5274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    items = dict.items()
5284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    items.sort()
5294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    reprpairs = ["%r: %r" % pair for pair in items]
5304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    withcommas = ", ".join(reprpairs)
5314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return "{%s}" % withcommas
5324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef make_bad_fd():
5344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
5354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Create an invalid file descriptor by opening and closing a file and return
5364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    its fd.
5374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
5384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    file = open(TESTFN, "wb")
5394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
5404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return file.fileno()
5414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    finally:
5424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        file.close()
5434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        unlink(TESTFN)
5444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef check_syntax_error(testcase, statement):
5464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    testcase.assertRaises(SyntaxError, compile, statement,
5474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                          '<test string>', 'exec')
5484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef open_urlresource(url, check=None):
5504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    import urlparse, urllib2
5514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
5534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    fn = os.path.join(os.path.dirname(__file__), "data", filename)
5554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def check_valid_file(fn):
5574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        f = open(fn)
5584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if check is None:
5594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return f
5604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        elif check(f):
5614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            f.seek(0)
5624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return f
5634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        f.close()
5644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if os.path.exists(fn):
5664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        f = check_valid_file(fn)
5674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if f is not None:
5684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return f
5694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        unlink(fn)
5704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Verify the requirement before downloading the file
5724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    requires('urlfetch')
5734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    print >> get_original_stdout(), '\tfetching %s ...' % url
5754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    f = urllib2.urlopen(url, timeout=15)
5764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
5774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        with open(fn, "wb") as out:
5784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            s = f.read()
5794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            while s:
5804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                out.write(s)
5814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                s = f.read()
5824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    finally:
5834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        f.close()
5844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    f = check_valid_file(fn)
5864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if f is not None:
5874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return f
5884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    raise TestFailed('invalid resource "%s"' % fn)
5894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass WarningsRecorder(object):
5924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Convenience wrapper for the warnings list returned on
5934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao       entry to the warnings.catch_warnings() context manager.
5944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
5954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __init__(self, warnings_list):
5964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self._warnings = warnings_list
5974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self._last = 0
5984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
5994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __getattr__(self, attr):
6004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if len(self._warnings) > self._last:
6014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return getattr(self._warnings[-1], attr)
6024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        elif attr in warnings.WarningMessage._WARNING_DETAILS:
6034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return None
6044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise AttributeError("%r has no attribute %r" % (self, attr))
6054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    @property
6074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def warnings(self):
6084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return self._warnings[self._last:]
6094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def reset(self):
6114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self._last = len(self._warnings)
6124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef _filterwarnings(filters, quiet=False):
6154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Catch the warnings, then check if all the expected
6164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    warnings have been raised and re-raise unexpected warnings.
6174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If 'quiet' is True, only re-raise the unexpected warnings.
6184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
6194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Clear the warning registry of the calling module
6204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # in order to re-raise the warnings.
6214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    frame = sys._getframe(2)
6224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    registry = frame.f_globals.get('__warningregistry__')
6234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if registry:
6244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        registry.clear()
6254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    with warnings.catch_warnings(record=True) as w:
6264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Set filter "always" to record all warnings.  Because
6274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # test_warnings swap the module, we need to look up in
6284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # the sys.modules dictionary.
6294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        sys.modules['warnings'].simplefilter("always")
6304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        yield WarningsRecorder(w)
6314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Filter the recorded warnings
6324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    reraise = [warning.message for warning in w]
6334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    missing = []
6344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for msg, cat in filters:
6354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        seen = False
6364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        for exc in reraise[:]:
6374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            message = str(exc)
6384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # Filter out the matching messages
6394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if (re.match(msg, message, re.I) and
6404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                issubclass(exc.__class__, cat)):
6414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                seen = True
6424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                reraise.remove(exc)
6434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if not seen and not quiet:
6444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # This filter caught nothing
6454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            missing.append((msg, cat.__name__))
6464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if reraise:
6474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise AssertionError("unhandled warning %r" % reraise[0])
6484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if missing:
6494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise AssertionError("filter (%r, %s) did not catch any warning" %
6504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                             missing[0])
6514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao@contextlib.contextmanager
6544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef check_warnings(*filters, **kwargs):
6554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Context manager to silence warnings.
6564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Accept 2-tuples as positional arguments:
6584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ("message regexp", WarningCategory)
6594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Optional argument:
6614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao     - if 'quiet' is True, it does not fail if a filter catches nothing
6624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        (default True without argument,
6634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao         default False if some filters are defined)
6644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Without argument, it defaults to:
6664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        check_warnings(("", Warning), quiet=True)
6674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
6684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    quiet = kwargs.get('quiet')
6694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if not filters:
6704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        filters = (("", Warning),)
6714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Preserve backward compatibility
6724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if quiet is None:
6734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            quiet = True
6744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return _filterwarnings(filters, quiet)
6754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao@contextlib.contextmanager
6784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef check_py3k_warnings(*filters, **kwargs):
6794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Context manager to silence py3k warnings.
6804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Accept 2-tuples as positional arguments:
6824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ("message regexp", WarningCategory)
6834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Optional argument:
6854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao     - if 'quiet' is True, it does not fail if a filter catches nothing
6864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        (default False)
6874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Without argument, it defaults to:
6894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        check_py3k_warnings(("", DeprecationWarning), quiet=False)
6904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
6914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if sys.py3kwarning:
6924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if not filters:
6934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            filters = (("", DeprecationWarning),)
6944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
6954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # It should not raise any py3k warning
6964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        filters = ()
6974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return _filterwarnings(filters, kwargs.get('quiet'))
6984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
6994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass CleanImport(object):
7014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Context manager to force import to return a new module reference.
7024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    This is useful for testing module-level behaviours, such as
7044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the emission of a DeprecationWarning on import.
7054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Use like this:
7074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        with CleanImport("foo"):
7094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            importlib.import_module("foo") # new reference
7104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
7114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __init__(self, *module_names):
7134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self.original_modules = sys.modules.copy()
7144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        for module_name in module_names:
7154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if module_name in sys.modules:
7164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                module = sys.modules[module_name]
7174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # It is possible that module_name is just an alias for
7184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # another module (e.g. stub for modules renamed in 3.x).
7194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # In that case, we also need delete the real module to clear
7204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # the import cache.
7214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if module.__name__ != module_name:
7224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    del sys.modules[module.__name__]
7234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                del sys.modules[module_name]
7244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __enter__(self):
7264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return self
7274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __exit__(self, *ignore_exc):
7294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        sys.modules.update(self.original_modules)
7304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass EnvironmentVarGuard(UserDict.DictMixin):
7334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Class to help protect the environment variable properly.  Can be used as
7354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    a context manager."""
7364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __init__(self):
7384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self._environ = os.environ
7394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self._changed = {}
7404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __getitem__(self, envvar):
7424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return self._environ[envvar]
7434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __setitem__(self, envvar, value):
7454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Remember the initial value on the first access
7464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if envvar not in self._changed:
7474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            self._changed[envvar] = self._environ.get(envvar)
7484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self._environ[envvar] = value
7494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __delitem__(self, envvar):
7514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Remember the initial value on the first access
7524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if envvar not in self._changed:
7534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            self._changed[envvar] = self._environ.get(envvar)
7544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if envvar in self._environ:
7554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            del self._environ[envvar]
7564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def keys(self):
7584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return self._environ.keys()
7594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def set(self, envvar, value):
7614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self[envvar] = value
7624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def unset(self, envvar):
7644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        del self[envvar]
7654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __enter__(self):
7674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return self
7684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __exit__(self, *ignore_exc):
7704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        for (k, v) in self._changed.items():
7714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if v is None:
7724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if k in self._environ:
7734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    del self._environ[k]
7744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
7754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                self._environ[k] = v
7764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        os.environ = self._environ
7774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass DirsOnSysPath(object):
7804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Context manager to temporarily add directories to sys.path.
7814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    This makes a copy of sys.path, appends any directories given
7834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    as positional arguments, then reverts sys.path to the copied
7844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    settings when the context ends.
7854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Note that *all* sys.path modifications in the body of the
7874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    context manager, including replacement of the object,
7884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    will be reverted at the end of the block.
7894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
7904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __init__(self, *paths):
7924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self.original_value = sys.path[:]
7934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self.original_object = sys.path
7944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        sys.path.extend(paths)
7954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __enter__(self):
7974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return self
7984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
7994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __exit__(self, *ignore_exc):
8004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        sys.path = self.original_object
8014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        sys.path[:] = self.original_value
8024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass TransientResource(object):
8054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Raise ResourceDenied if an exception is raised while the context manager
8074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    is in effect that matches the specified exception and attributes."""
8084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __init__(self, exc, **kwargs):
8104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self.exc = exc
8114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self.attrs = kwargs
8124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __enter__(self):
8144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return self
8154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def __exit__(self, type_=None, value=None, traceback=None):
8174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        """If type_ is a subclass of self.exc and value has attributes matching
8184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        self.attrs, raise ResourceDenied.  Otherwise let the exception
8194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        propagate (if any)."""
8204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if type_ is not None and issubclass(self.exc, type_):
8214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            for attr, attr_value in self.attrs.iteritems():
8224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if not hasattr(value, attr):
8234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    break
8244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if getattr(value, attr) != attr_value:
8254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    break
8264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
8274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                raise ResourceDenied("an optional resource is not available")
8284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao@contextlib.contextmanager
8314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef transient_internet(resource_name, timeout=30.0, errnos=()):
8324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Return a context manager that raises ResourceDenied when various issues
8334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    with the Internet connection manifest themselves as exceptions."""
8344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    default_errnos = [
8354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('ECONNREFUSED', 111),
8364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('ECONNRESET', 104),
8374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('EHOSTUNREACH', 113),
8384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('ENETUNREACH', 101),
8394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('ETIMEDOUT', 110),
8404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    ]
8414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    default_gai_errnos = [
8424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('EAI_AGAIN', -3),
8434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('EAI_FAIL', -4),
8444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('EAI_NONAME', -2),
8454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('EAI_NODATA', -5),
8464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # Windows defines EAI_NODATA as 11001 but idiotic getaddrinfo()
8474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # implementation actually returns WSANO_DATA i.e. 11004.
8484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ('WSANO_DATA', 11004),
8494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    ]
8504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    denied = ResourceDenied("Resource '%s' is not available" % resource_name)
8524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    captured_errnos = errnos
8534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    gai_errnos = []
8544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if not captured_errnos:
8554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        captured_errnos = [getattr(errno, name, num)
8564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                           for (name, num) in default_errnos]
8574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        gai_errnos = [getattr(socket, name, num)
8584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                      for (name, num) in default_gai_errnos]
8594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def filter_error(err):
8614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        n = getattr(err, 'errno', None)
8624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if (isinstance(err, socket.timeout) or
8634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            (isinstance(err, socket.gaierror) and n in gai_errnos) or
8644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            n in captured_errnos):
8654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if not verbose:
8664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                sys.stderr.write(denied.args[0] + "\n")
8674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            raise denied
8684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    old_timeout = socket.getdefaulttimeout()
8704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
8714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if timeout is not None:
8724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            socket.setdefaulttimeout(timeout)
8734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        yield
8744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except IOError as err:
8754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # urllib can wrap original socket errors multiple times (!), we must
8764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # unwrap to get at the original error.
8774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        while True:
8784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            a = err.args
8794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if len(a) >= 1 and isinstance(a[0], IOError):
8804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                err = a[0]
8814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # The error can also be wrapped as args[1]:
8824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            #    except socket.error as msg:
8834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            #        raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
8844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            elif len(a) >= 2 and isinstance(a[1], IOError):
8854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                err = a[1]
8864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
8874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                break
8884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        filter_error(err)
8894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise
8904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # XXX should we catch generic exceptions and look for their
8914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # __cause__ or __context__?
8924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    finally:
8934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        socket.setdefaulttimeout(old_timeout)
8944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
8964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao@contextlib.contextmanager
8974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef captured_output(stream_name):
8984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Return a context manager used by captured_stdout and captured_stdin
8994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    that temporarily replaces the sys stream *stream_name* with a StringIO."""
9004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    import StringIO
9014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    orig_stdout = getattr(sys, stream_name)
9024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    setattr(sys, stream_name, StringIO.StringIO())
9034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
9044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        yield getattr(sys, stream_name)
9054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    finally:
9064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        setattr(sys, stream_name, orig_stdout)
9074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef captured_stdout():
9094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Capture the output of sys.stdout:
9104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao       with captured_stdout() as s:
9124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao           print "hello"
9134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao       self.assertEqual(s.getvalue(), "hello")
9144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
9154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return captured_output("stdout")
9164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef captured_stderr():
9184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return captured_output("stderr")
9194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef captured_stdin():
9214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return captured_output("stdin")
9224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef gc_collect():
9244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Force as many objects as possible to be collected.
9254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    In non-CPython implementations of Python, this is needed because timely
9274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    deallocation is not guaranteed by the garbage collector.  (Even in CPython
9284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    this can be the case in case of reference cycles.)  This means that __del__
9294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    methods may be called later than expected and weakrefs may remain alive for
9304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    longer than expected.  This function tries its best to force all garbage
9314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    objects to disappear.
9324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
9334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    gc.collect()
9344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if is_jython:
9354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        time.sleep(0.1)
9364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    gc.collect()
9374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    gc.collect()
9384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_header = '2P'
9414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoif hasattr(sys, "gettotalrefcount"):
9424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    _header = '2P' + _header
9434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_vheader = _header + 'P'
9444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef calcobjsize(fmt):
9464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return struct.calcsize(_header + fmt + '0P')
9474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef calcvobjsize(fmt):
9494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return struct.calcsize(_vheader + fmt + '0P')
9504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_TPFLAGS_HAVE_GC = 1<<14
9534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_TPFLAGS_HEAPTYPE = 1<<9
9544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef check_sizeof(test, o, size):
9564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    result = sys.getsizeof(o)
9574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # add GC header size
9584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
9594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
9604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        size += _testcapi.SIZEOF_PYGC_HEAD
9614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    msg = 'wrong size for %s: got %d, expected %d' \
9624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            % (type(o), result, size)
9634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    test.assertEqual(result, size, msg)
9644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao#=======================================================================
9674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Decorator for running a function in a different locale, correctly resetting
9684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# it afterwards.
9694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef run_with_locale(catstr, *locales):
9714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def decorator(func):
9724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        def inner(*args, **kwds):
9734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            try:
9744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                import locale
9754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                category = getattr(locale, catstr)
9764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                orig_locale = locale.setlocale(category)
9774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            except AttributeError:
9784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # if the test author gives us an invalid category string
9794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                raise
9804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            except:
9814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # cannot retrieve original locale, so do nothing
9824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                locale = orig_locale = None
9834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
9844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                for loc in locales:
9854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    try:
9864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                        locale.setlocale(category, loc)
9874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                        break
9884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    except:
9894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                        pass
9904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
9914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # now run the function, resetting the locale on exceptions
9924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            try:
9934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                return func(*args, **kwds)
9944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            finally:
9954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if locale and orig_locale:
9964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    locale.setlocale(category, orig_locale)
9974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        inner.func_name = func.func_name
9984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        inner.__doc__ = func.__doc__
9994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return inner
10004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return decorator
10014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao#=======================================================================
10034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Big-memory-test support. Separate from 'resources' because memory use should be configurable.
10044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Some handy shorthands. Note that these are used for byte-limits as well
10064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# as size-limits, in the various bigmem tests
10074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_1M = 1024*1024
10084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_1G = 1024 * _1M
10094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_2G = 2 * _1G
10104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao_4G = 4 * _1G
10114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10124adfde8bc82dd39f59e0445588c3e599ada477dJosh GaoMAX_Py_ssize_t = sys.maxsize
10134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef set_memlimit(limit):
10154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    global max_memuse
10164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    global real_max_memuse
10174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    sizes = {
10184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        'k': 1024,
10194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        'm': _1M,
10204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        'g': _1G,
10214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        't': 1024*_1G,
10224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    }
10234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
10244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                 re.IGNORECASE | re.VERBOSE)
10254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if m is None:
10264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise ValueError('Invalid memory limit %r' % (limit,))
10274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
10284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    real_max_memuse = memlimit
10294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if memlimit > MAX_Py_ssize_t:
10304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        memlimit = MAX_Py_ssize_t
10314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if memlimit < _2G - 1:
10324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise ValueError('Memory limit %r too low to be useful' % (limit,))
10334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    max_memuse = memlimit
10344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef bigmemtest(minsize, memuse, overhead=5*_1M):
10364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Decorator for bigmem tests.
10374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    'minsize' is the minimum useful size for the test (in arbitrary,
10394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    test-interpreted units.) 'memuse' is the number of 'bytes per size' for
10404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the test, or a good estimate of it. 'overhead' specifies fixed overhead,
10414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    independent of the testsize, and defaults to 5Mb.
10424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    The decorator tries to guess a good value for 'size' and passes it to
10444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    the decorated test function. If minsize * memuse is more than the
10454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    allowed memory use (as defined by max_memuse), the test is skipped.
10464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Otherwise, minsize is adjusted upward to use up to max_memuse.
10474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
10484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def decorator(f):
10494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        def wrapper(self):
10504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if not max_memuse:
10514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # If max_memuse is 0 (the default),
10524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # we still want to run the tests with size set to a few kb,
10534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # to make sure they work. We still want to avoid using
10544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # too much memory, though, but we do that noisily.
10554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                maxsize = 5147
10564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
10574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
10584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                maxsize = int((max_memuse - overhead) / memuse)
10594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if maxsize < minsize:
10604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    # Really ought to print 'test skipped' or something
10614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    if verbose:
10624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                        sys.stderr.write("Skipping %s because of memory "
10634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                         "constraint\n" % (f.__name__,))
10644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    return
10654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # Try to keep some breathing room in memory use
10664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                maxsize = max(maxsize - 50 * _1M, minsize)
10674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return f(self, maxsize)
10684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        wrapper.minsize = minsize
10694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        wrapper.memuse = memuse
10704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        wrapper.overhead = overhead
10714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return wrapper
10724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return decorator
10734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef precisionbigmemtest(size, memuse, overhead=5*_1M, dry_run=True):
10754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def decorator(f):
10764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        def wrapper(self):
10774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if not real_max_memuse:
10784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                maxsize = 5147
10794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
10804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                maxsize = size
10814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if ((real_max_memuse or not dry_run)
10834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                and real_max_memuse < maxsize * memuse):
10844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if verbose:
10854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    sys.stderr.write("Skipping %s because of memory "
10864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                     "constraint\n" % (f.__name__,))
10874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                return
10884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return f(self, maxsize)
10904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        wrapper.size = size
10914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        wrapper.memuse = memuse
10924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        wrapper.overhead = overhead
10934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return wrapper
10944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return decorator
10954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
10964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef bigaddrspacetest(f):
10974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Decorator for tests that fill the address space."""
10984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def wrapper(self):
10994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if max_memuse < MAX_Py_ssize_t:
11004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if verbose:
11014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                sys.stderr.write("Skipping %s because of memory "
11024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                 "constraint\n" % (f.__name__,))
11034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        else:
11044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return f(self)
11054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return wrapper
11064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao#=======================================================================
11084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# unittest integration.
11094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaoclass BasicTestRunner:
11114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def run(self, test):
11124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        result = unittest.TestResult()
11134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        test(result)
11144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return result
11154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef _id(obj):
11174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return obj
11184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef requires_resource(resource):
11204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if is_resource_enabled(resource):
11214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return _id
11224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
11234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return unittest.skip("resource {0!r} is not enabled".format(resource))
11244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef cpython_only(test):
11264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
11274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Decorator for tests only applicable on CPython.
11284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
11294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return impl_detail(cpython=True)(test)
11304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef impl_detail(msg=None, **guards):
11324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if check_impl_detail(**guards):
11334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return _id
11344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if msg is None:
11354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        guardnames, default = _parse_guards(guards)
11364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if default:
11374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            msg = "implementation detail not available on {0}"
11384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        else:
11394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            msg = "implementation detail specific to {0}"
11404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        guardnames = sorted(guardnames.keys())
11414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        msg = msg.format(' or '.join(guardnames))
11424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return unittest.skip(msg)
11434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef _parse_guards(guards):
11454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Returns a tuple ({platform_name: run_me}, default_value)
11464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if not guards:
11474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return ({'cpython': True}, False)
11484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    is_true = guards.values()[0]
11494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    assert guards.values() == [is_true] * len(guards)   # all True or all False
11504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return (guards, not is_true)
11514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Use the following check to guard CPython's implementation-specific tests --
11534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# or to run them only on the implementation(s) guarded by the arguments.
11544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef check_impl_detail(**guards):
11554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """This function returns True or False depending on the host platform.
11564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao       Examples:
11574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao          if check_impl_detail():               # only on CPython (default)
11584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao          if check_impl_detail(jython=True):    # only on Jython
11594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao          if check_impl_detail(cpython=False):  # everywhere except on CPython
11604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
11614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    guards, default = _parse_guards(guards)
11624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return guards.get(platform.python_implementation().lower(), default)
11634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef _run_suite(suite):
11674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Run tests from a unittest.TestSuite-derived class."""
11684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if verbose:
11694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
11704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
11714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        runner = BasicTestRunner()
11724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    result = runner.run(suite)
11744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if not result.wasSuccessful():
11754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if len(result.errors) == 1 and not result.failures:
11764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            err = result.errors[0][1]
11774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        elif len(result.failures) == 1 and not result.errors:
11784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            err = result.failures[0][1]
11794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        else:
11804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            err = "multiple errors occurred"
11814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if not verbose:
11824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                err += "; run in verbose mode for details"
11834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        raise TestFailed(err)
11844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
11864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef run_unittest(*classes):
11874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Run tests from unittest.TestCase-derived classes."""
11884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    valid_types = (unittest.TestSuite, unittest.TestCase)
11894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    suite = unittest.TestSuite()
11904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for cls in classes:
11914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if isinstance(cls, str):
11924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            if cls in sys.modules:
11934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                suite.addTest(unittest.findTestCases(sys.modules[cls]))
11944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            else:
11954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                raise ValueError("str arguments must be keys in sys.modules")
11964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        elif isinstance(cls, valid_types):
11974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            suite.addTest(cls)
11984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        else:
11994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            suite.addTest(unittest.makeSuite(cls))
12004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    _run_suite(suite)
12014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao#=======================================================================
12034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Check for the presence of docstrings.
12044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12054adfde8bc82dd39f59e0445588c3e599ada477dJosh GaoHAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or
12064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                   sys.platform == 'win32' or
12074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                   sysconfig.get_config_var('WITH_DOC_STRINGS'))
12084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaorequires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
12104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                                          "test requires docstrings")
12114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao#=======================================================================
12144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# doctest driver.
12154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef run_doctest(module, verbosity=None):
12174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Run doctest on the given module.  Return (#failures, #tests).
12184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If optional argument verbosity is not specified (or is None), pass
12204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    test_support's belief about verbosity on to doctest.  Else doctest's
12214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    usual behavior is used (it searches sys.argv for -v).
12224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
12234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    import doctest
12254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if verbosity is None:
12274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        verbosity = verbose
12284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
12294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        verbosity = None
12304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Direct doctest output (normally just errors) to real stdout; doctest
12324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # output shouldn't be compared by regrtest.
12334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    save_stdout = sys.stdout
12344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    sys.stdout = get_original_stdout()
12354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
12364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        f, t = doctest.testmod(module, verbose=verbosity)
12374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if f:
12384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            raise TestFailed("%d of %d doctests failed" % (f, t))
12394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    finally:
12404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        sys.stdout = save_stdout
12414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if verbose:
12424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
12434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return f, t
12444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao#=======================================================================
12464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# Threading support to prevent reporting refleaks when running regrtest.py -R
12474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# NOTE: we use thread._count() rather than threading.enumerate() (or the
12494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# moral equivalent thereof) because a threading.Thread object is still alive
12504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# until its __bootstrap() method has returned, even after it has been
12514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# unregistered from the threading module.
12524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# thread._count(), on the other hand, only gets decremented *after* the
12534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# __bootstrap() method has returned, which gives us reliable reference counts
12544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao# at the end of a test run.
12554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef threading_setup():
12574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if thread:
12584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return thread._count(),
12594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
12604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return 1,
12614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef threading_cleanup(nb_threads):
12634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if not thread:
12644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return
12654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    _MAX_COUNT = 10
12674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for count in range(_MAX_COUNT):
12684adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        n = thread._count()
12694adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        if n == nb_threads:
12704adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            break
12714adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        time.sleep(0.1)
12724adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # XXX print a warning in case of failure?
12734adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12744adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef reap_threads(func):
12754adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Use this function when threads are being used.  This will
12764adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    ensure that the threads are cleaned up even when the test fails.
12774adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    If threading is unavailable this function does nothing.
12784adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
12794adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if not thread:
12804adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return func
12814adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12824adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    @functools.wraps(func)
12834adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    def decorator(*args):
12844adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        key = threading_setup()
12854adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
12864adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return func(*args)
12874adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        finally:
12884adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            threading_cleanup(*key)
12894adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return decorator
12904adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12914adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef reap_children():
12924adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Use this function at the end of test_main() whenever sub-processes
12934adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    are started.  This will help ensure that no extra children (zombies)
12944adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    stick around to hog resources and create problems when looking
12954adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    for refleaks.
12964adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
12974adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
12984adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # Reap all our dead child processes so we don't leave zombies around.
12994adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    # These hog resources and might be causing some of the buildbots to die.
13004adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if hasattr(os, 'waitpid'):
13014adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        any_process = -1
13024adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        while True:
13034adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            try:
13044adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                # This will raise an exception on Windows.  That's ok.
13054adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                pid, status = os.waitpid(any_process, os.WNOHANG)
13064adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                if pid == 0:
13074adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                    break
13084adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            except:
13094adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao                break
13104adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13114adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao@contextlib.contextmanager
13124adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef swap_attr(obj, attr, new_val):
13134adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Temporary swap out an attribute with a new object.
13144adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13154adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    Usage:
13164adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        with swap_attr(obj, "attr", 5):
13174adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            ...
13184adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13194adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        This will set obj.attr to 5 for the duration of the with: block,
13204adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        restoring the old value at the end of the block. If `attr` doesn't
13214adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        exist on `obj`, it will be created and then deleted at the end of the
13224adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        block.
13234adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
13244adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    if hasattr(obj, attr):
13254adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        real_val = getattr(obj, attr)
13264adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        setattr(obj, attr, new_val)
13274adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
13284adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            yield
13294adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        finally:
13304adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            setattr(obj, attr, real_val)
13314adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    else:
13324adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        setattr(obj, attr, new_val)
13334adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
13344adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            yield
13354adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        finally:
13364adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            delattr(obj, attr)
13374adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13384adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef py3k_bytes(b):
13394adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Emulate the py3k bytes() constructor.
13404adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13414adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    NOTE: This is only a best effort function.
13424adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
13434adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    try:
13444adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        # memoryview?
13454adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        return b.tobytes()
13464adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    except AttributeError:
13474adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        try:
13484adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            # iterable of ints?
13494adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return b"".join(chr(x) for x in b)
13504adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao        except TypeError:
13514adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao            return bytes(b)
13524adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13534adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef args_from_interpreter_flags():
13544adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Return a list of command-line arguments reproducing the current
13554adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    settings in sys.flags."""
13564adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    import subprocess
13574adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return subprocess._args_from_interpreter_flags()
13584adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13594adfde8bc82dd39f59e0445588c3e599ada477dJosh Gaodef strip_python_stderr(stderr):
13604adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """Strip the stderr of a Python process from potential debug output
13614adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    emitted by the interpreter.
13624adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao
13634adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    This will typically be run on the result of the communicate() method
13644adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    of a subprocess.Popen object.
13654adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    """
13664adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
13674adfde8bc82dd39f59e0445588c3e599ada477dJosh Gao    return stderr
1368