Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 1 | """Supporting definitions for the Python regression tests.""" |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 2 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 3 | if __name__ != 'test.support': |
| 4 | raise ImportError('support must be imported from the test package') |
Barry Warsaw | 408b6d3 | 2002-07-30 23:27:12 +0000 | [diff] [blame] | 5 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 6 | import contextlib |
| 7 | import errno |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 8 | import functools |
Benjamin Peterson | 8cc7d88 | 2009-06-01 23:14:51 +0000 | [diff] [blame] | 9 | import gc |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 10 | import socket |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 11 | import sys |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 12 | import os |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 13 | import platform |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 14 | import shutil |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 15 | import warnings |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 16 | import unittest |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 17 | import importlib |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 18 | import collections |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 19 | import re |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 20 | import subprocess |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 21 | import imp |
Benjamin Peterson | a6590e8 | 2010-04-11 21:22:10 +0000 | [diff] [blame] | 22 | import time |
Benjamin Peterson | 65c66ab | 2010-10-29 21:31:35 +0000 | [diff] [blame] | 23 | import sysconfig |
Vinay Sajip | 129fd04 | 2010-12-10 08:19:38 +0000 | [diff] [blame] | 24 | import logging.handlers |
Benjamin Peterson | 65c66ab | 2010-10-29 21:31:35 +0000 | [diff] [blame] | 25 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 26 | try: |
| 27 | import _thread |
| 28 | except ImportError: |
| 29 | _thread = None |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 30 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 31 | __all__ = [ |
| 32 | "Error", "TestFailed", "ResourceDenied", "import_module", |
| 33 | "verbose", "use_resources", "max_memuse", "record_original_stdout", |
| 34 | "get_original_stdout", "unload", "unlink", "rmtree", "forget", |
Victor Stinner | 88701e2 | 2011-06-01 13:13:04 +0200 | [diff] [blame] | 35 | "is_resource_enabled", "requires", "requires_mac_ver", |
| 36 | "find_unused_port", "bind_port", |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 37 | "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd", |
| 38 | "findfile", "sortdict", "check_syntax_error", "open_urlresource", |
| 39 | "check_warnings", "CleanImport", "EnvironmentVarGuard", |
| 40 | "TransientResource", "captured_output", "captured_stdout", |
Ezio Melotti | 07352b0 | 2011-05-14 14:51:18 +0300 | [diff] [blame] | 41 | "captured_stdin", "captured_stderr", |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 42 | "time_out", "socket_peer_reset", "ioerror_peer_reset", |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 43 | "run_with_locale", 'temp_umask', "transient_internet", |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 44 | "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner", |
| 45 | "run_unittest", "run_doctest", "threading_setup", "threading_cleanup", |
| 46 | "reap_children", "cpython_only", "check_impl_detail", "get_attribute", |
Vinay Sajip | 129fd04 | 2010-12-10 08:19:38 +0000 | [diff] [blame] | 47 | "swap_item", "swap_attr", "requires_IEEE_754", |
Benjamin Peterson | 31dc373 | 2011-05-08 15:34:24 -0500 | [diff] [blame] | 48 | "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink", |
Benjamin Peterson | 262c582 | 2011-05-08 15:32:46 -0500 | [diff] [blame] | 49 | "import_fresh_module" |
Antoine Pitrou | 4d7979b | 2010-09-07 21:22:56 +0000 | [diff] [blame] | 50 | ] |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 51 | |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 52 | class Error(Exception): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 53 | """Base class for regression test exceptions.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 54 | |
| 55 | class TestFailed(Error): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 56 | """Test failed.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 57 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 58 | class ResourceDenied(unittest.SkipTest): |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 59 | """Test skipped because it requested a disallowed resource. |
| 60 | |
| 61 | This is raised when a test calls requires() for a resource that |
| 62 | has not be enabled. It is used to distinguish between expected |
| 63 | and unexpected skips. |
| 64 | """ |
| 65 | |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 66 | @contextlib.contextmanager |
| 67 | def _ignore_deprecated_imports(ignore=True): |
| 68 | """Context manager to suppress package and module deprecation |
| 69 | warnings when importing them. |
| 70 | |
| 71 | If ignore is False, this context manager has no effect.""" |
| 72 | if ignore: |
| 73 | with warnings.catch_warnings(): |
| 74 | warnings.filterwarnings("ignore", ".+ (module|package)", |
| 75 | DeprecationWarning) |
| 76 | yield |
| 77 | else: |
| 78 | yield |
| 79 | |
| 80 | |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 81 | def import_module(name, deprecated=False): |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 82 | """Import and return the module to be tested, raising SkipTest if |
| 83 | it is not available. |
| 84 | |
| 85 | If deprecated is True, any module or package deprecation messages |
| 86 | will be suppressed.""" |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 87 | with _ignore_deprecated_imports(deprecated): |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 88 | try: |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 89 | return importlib.import_module(name) |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 90 | except ImportError as msg: |
| 91 | raise unittest.SkipTest(str(msg)) |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 92 | |
| 93 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 94 | def _save_and_remove_module(name, orig_modules): |
| 95 | """Helper function to save and remove a module from sys.modules |
| 96 | |
Ezio Melotti | 199e085 | 2011-05-09 06:41:55 +0300 | [diff] [blame] | 97 | Raise ImportError if the module can't be imported.""" |
Ezio Melotti | fec3ad1 | 2011-05-14 06:02:25 +0300 | [diff] [blame] | 98 | # try to import the module and raise an error if it can't be imported |
| 99 | if name not in sys.modules: |
Ezio Melotti | 199e085 | 2011-05-09 06:41:55 +0300 | [diff] [blame] | 100 | __import__(name) |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 101 | del sys.modules[name] |
Ezio Melotti | fec3ad1 | 2011-05-14 06:02:25 +0300 | [diff] [blame] | 102 | for modname in list(sys.modules): |
| 103 | if modname == name or modname.startswith(name + '.'): |
| 104 | orig_modules[modname] = sys.modules[modname] |
| 105 | del sys.modules[modname] |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 106 | |
| 107 | def _save_and_block_module(name, orig_modules): |
| 108 | """Helper function to save and block a module in sys.modules |
| 109 | |
Ezio Melotti | 199e085 | 2011-05-09 06:41:55 +0300 | [diff] [blame] | 110 | Return True if the module was in sys.modules, False otherwise.""" |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 111 | saved = True |
| 112 | try: |
| 113 | orig_modules[name] = sys.modules[name] |
| 114 | except KeyError: |
| 115 | saved = False |
Alexander Belopolsky | 903396e | 2010-07-13 14:50:16 +0000 | [diff] [blame] | 116 | sys.modules[name] = None |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 117 | return saved |
| 118 | |
| 119 | |
| 120 | def import_fresh_module(name, fresh=(), blocked=(), deprecated=False): |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 121 | """Imports and returns a module, deliberately bypassing the sys.modules cache |
| 122 | and importing a fresh copy of the module. Once the import is complete, |
| 123 | the sys.modules cache is restored to its original state. |
| 124 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 125 | Modules named in fresh are also imported anew if needed by the import. |
Ezio Melotti | 199e085 | 2011-05-09 06:41:55 +0300 | [diff] [blame] | 126 | If one of these modules can't be imported, None is returned. |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 127 | |
| 128 | Importing of modules named in blocked is prevented while the fresh import |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 129 | takes place. |
| 130 | |
| 131 | If deprecated is True, any module or package deprecation messages |
| 132 | will be suppressed.""" |
Ezio Melotti | 6b60fb9 | 2011-05-14 06:47:51 +0300 | [diff] [blame] | 133 | # NOTE: test_heapq, test_json and test_warnings include extra sanity checks |
| 134 | # to make sure that this utility function is working as expected |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 135 | with _ignore_deprecated_imports(deprecated): |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 136 | # Keep track of modules saved for later restoration as well |
| 137 | # as those which just need a blocking entry removed |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 138 | orig_modules = {} |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 139 | names_to_remove = [] |
| 140 | _save_and_remove_module(name, orig_modules) |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 141 | try: |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 142 | for fresh_name in fresh: |
| 143 | _save_and_remove_module(fresh_name, orig_modules) |
| 144 | for blocked_name in blocked: |
| 145 | if not _save_and_block_module(blocked_name, orig_modules): |
| 146 | names_to_remove.append(blocked_name) |
| 147 | fresh_module = importlib.import_module(name) |
Ezio Melotti | 199e085 | 2011-05-09 06:41:55 +0300 | [diff] [blame] | 148 | except ImportError: |
| 149 | fresh_module = None |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 150 | finally: |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 151 | for orig_name, module in orig_modules.items(): |
| 152 | sys.modules[orig_name] = module |
| 153 | for name_to_remove in names_to_remove: |
| 154 | del sys.modules[name_to_remove] |
| 155 | return fresh_module |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 156 | |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 157 | |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 158 | def get_attribute(obj, name): |
| 159 | """Get an attribute, raising SkipTest if AttributeError is raised.""" |
| 160 | try: |
| 161 | attribute = getattr(obj, name) |
| 162 | except AttributeError: |
| 163 | raise unittest.SkipTest("module %s has no attribute %s" % ( |
| 164 | obj.__name__, name)) |
| 165 | else: |
| 166 | return attribute |
| 167 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 168 | verbose = 1 # Flag set to 0 by regrtest.py |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 169 | use_resources = None # Flag set to [] by regrtest.py |
| 170 | max_memuse = 0 # Disable bigmem tests (they will still be run with |
| 171 | # small sizes, to make sure they work.) |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 172 | real_max_memuse = 0 |
Guido van Rossum | 531661c | 1996-12-20 02:58:22 +0000 | [diff] [blame] | 173 | |
Tim Peters | 8dee809 | 2001-09-25 20:05:11 +0000 | [diff] [blame] | 174 | # _original_stdout is meant to hold stdout at the time regrtest began. |
| 175 | # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. |
| 176 | # The point is to have some flavor of stdout the user can actually see. |
| 177 | _original_stdout = None |
| 178 | def record_original_stdout(stdout): |
| 179 | global _original_stdout |
| 180 | _original_stdout = stdout |
| 181 | |
| 182 | def get_original_stdout(): |
| 183 | return _original_stdout or sys.stdout |
| 184 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 185 | def unload(name): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 186 | try: |
| 187 | del sys.modules[name] |
| 188 | except KeyError: |
| 189 | pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 190 | |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 191 | def unlink(filename): |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 192 | try: |
| 193 | os.unlink(filename) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 194 | except OSError as error: |
| 195 | # The filename need not exist. |
Michael Foord | 2d9c2d5 | 2010-05-04 22:29:10 +0000 | [diff] [blame] | 196 | if error.errno not in (errno.ENOENT, errno.ENOTDIR): |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 197 | raise |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 198 | |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 199 | def rmtree(path): |
| 200 | try: |
| 201 | shutil.rmtree(path) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 202 | except OSError as error: |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 203 | # Unix returns ENOENT, Windows returns ESRCH. |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 204 | if error.errno not in (errno.ENOENT, errno.ESRCH): |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 205 | raise |
| 206 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 207 | def make_legacy_pyc(source): |
| 208 | """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location. |
| 209 | |
| 210 | The choice of .pyc or .pyo extension is done based on the __debug__ flag |
| 211 | value. |
| 212 | |
| 213 | :param source: The file system path to the source file. The source file |
| 214 | does not need to exist, however the PEP 3147 pyc file must exist. |
| 215 | :return: The file system path to the legacy pyc file. |
| 216 | """ |
| 217 | pyc_file = imp.cache_from_source(source) |
| 218 | up_one = os.path.dirname(os.path.abspath(source)) |
| 219 | legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o')) |
| 220 | os.rename(pyc_file, legacy_pyc) |
| 221 | return legacy_pyc |
| 222 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 223 | def forget(modname): |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 224 | """'Forget' a module was ever imported. |
| 225 | |
| 226 | This removes the module from sys.modules and deletes any PEP 3147 or |
| 227 | legacy .pyc and .pyo files. |
| 228 | """ |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 229 | unload(modname) |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 230 | for dirname in sys.path: |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 231 | source = os.path.join(dirname, modname + '.py') |
| 232 | # It doesn't matter if they exist or not, unlink all possible |
| 233 | # combinations of PEP 3147 and legacy pyc and pyo files. |
| 234 | unlink(source + 'c') |
| 235 | unlink(source + 'o') |
| 236 | unlink(imp.cache_from_source(source, debug_override=True)) |
| 237 | unlink(imp.cache_from_source(source, debug_override=False)) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 238 | |
Antoine Pitrou | 4914f9e | 2011-02-26 16:49:08 +0000 | [diff] [blame] | 239 | # On some platforms, should not run gui test even if it is allowed |
| 240 | # in `use_resources'. |
| 241 | if sys.platform.startswith('win'): |
| 242 | import ctypes |
| 243 | import ctypes.wintypes |
| 244 | def _is_gui_available(): |
| 245 | UOI_FLAGS = 1 |
| 246 | WSF_VISIBLE = 0x0001 |
| 247 | class USEROBJECTFLAGS(ctypes.Structure): |
| 248 | _fields_ = [("fInherit", ctypes.wintypes.BOOL), |
| 249 | ("fReserved", ctypes.wintypes.BOOL), |
| 250 | ("dwFlags", ctypes.wintypes.DWORD)] |
| 251 | dll = ctypes.windll.user32 |
| 252 | h = dll.GetProcessWindowStation() |
| 253 | if not h: |
| 254 | raise ctypes.WinError() |
| 255 | uof = USEROBJECTFLAGS() |
| 256 | needed = ctypes.wintypes.DWORD() |
| 257 | res = dll.GetUserObjectInformationW(h, |
| 258 | UOI_FLAGS, |
| 259 | ctypes.byref(uof), |
| 260 | ctypes.sizeof(uof), |
| 261 | ctypes.byref(needed)) |
| 262 | if not res: |
| 263 | raise ctypes.WinError() |
| 264 | return bool(uof.dwFlags & WSF_VISIBLE) |
| 265 | else: |
| 266 | def _is_gui_available(): |
| 267 | return True |
| 268 | |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 269 | def is_resource_enabled(resource): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 270 | """Test whether a resource is enabled. Known resources are set by |
| 271 | regrtest.py.""" |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 272 | return use_resources is not None and resource in use_resources |
| 273 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 274 | def requires(resource, msg=None): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 275 | """Raise ResourceDenied if the specified resource is not available. |
| 276 | |
| 277 | If the caller's module is __main__ then automatically return True. The |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 278 | possibility of False being returned occurs when regrtest.py is |
| 279 | executing. |
| 280 | """ |
Antoine Pitrou | 4914f9e | 2011-02-26 16:49:08 +0000 | [diff] [blame] | 281 | if resource == 'gui' and not _is_gui_available(): |
| 282 | raise unittest.SkipTest("Cannot use the 'gui' resource") |
Skip Montanaro | d839ecd | 2003-04-24 19:06:57 +0000 | [diff] [blame] | 283 | # see if the caller's module is __main__ - if so, treat as if |
| 284 | # the resource was set |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 285 | if sys._getframe(1).f_globals.get("__name__") == "__main__": |
Skip Montanaro | d839ecd | 2003-04-24 19:06:57 +0000 | [diff] [blame] | 286 | return |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 287 | if not is_resource_enabled(resource): |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 288 | if msg is None: |
| 289 | msg = "Use of the `%s' resource not enabled" % resource |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 290 | raise ResourceDenied(msg) |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 291 | |
Victor Stinner | 88701e2 | 2011-06-01 13:13:04 +0200 | [diff] [blame] | 292 | def requires_mac_ver(*min_version): |
| 293 | """Decorator raising SkipTest if the OS is Mac OS X and the OS X |
| 294 | version if less than min_version. |
| 295 | |
| 296 | For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version |
| 297 | is lesser than 10.5. |
| 298 | """ |
| 299 | def decorator(func): |
| 300 | @functools.wraps(func) |
| 301 | def wrapper(*args, **kw): |
| 302 | if sys.platform == 'darwin': |
| 303 | version_txt = platform.mac_ver()[0] |
| 304 | try: |
| 305 | version = tuple(map(int, version_txt.split('.'))) |
| 306 | except ValueError: |
| 307 | pass |
| 308 | else: |
| 309 | if version < min_version: |
| 310 | min_version_txt = '.'.join(map(str, min_version)) |
| 311 | raise unittest.SkipTest( |
| 312 | "Mac OS X %s or higher required, not %s" |
| 313 | % (min_version_txt, version_txt)) |
| 314 | return func(*args, **kw) |
| 315 | wrapper.min_version = min_version |
| 316 | return wrapper |
| 317 | return decorator |
| 318 | |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 319 | HOST = 'localhost' |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 320 | |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 321 | def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): |
| 322 | """Returns an unused port that should be suitable for binding. This is |
| 323 | achieved by creating a temporary socket with the same family and type as |
| 324 | the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to |
| 325 | the specified host address (defaults to 0.0.0.0) with the port set to 0, |
| 326 | eliciting an unused ephemeral port from the OS. The temporary socket is |
| 327 | then closed and deleted, and the ephemeral port is returned. |
| 328 | |
| 329 | Either this method or bind_port() should be used for any tests where a |
| 330 | server socket needs to be bound to a particular port for the duration of |
| 331 | the test. Which one to use depends on whether the calling code is creating |
| 332 | a python socket, or if an unused port needs to be provided in a constructor |
| 333 | or passed to an external program (i.e. the -accept argument to openssl's |
| 334 | s_server mode). Always prefer bind_port() over find_unused_port() where |
| 335 | possible. Hard coded ports should *NEVER* be used. As soon as a server |
| 336 | socket is bound to a hard coded port, the ability to run multiple instances |
| 337 | of the test simultaneously on the same host is compromised, which makes the |
| 338 | test a ticking time bomb in a buildbot environment. On Unix buildbots, this |
| 339 | may simply manifest as a failed test, which can be recovered from without |
| 340 | intervention in most cases, but on Windows, the entire python process can |
| 341 | completely and utterly wedge, requiring someone to log in to the buildbot |
| 342 | and manually kill the affected process. |
| 343 | |
| 344 | (This is easy to reproduce on Windows, unfortunately, and can be traced to |
| 345 | the SO_REUSEADDR socket option having different semantics on Windows versus |
| 346 | Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, |
| 347 | listen and then accept connections on identical host/ports. An EADDRINUSE |
| 348 | socket.error will be raised at some point (depending on the platform and |
| 349 | the order bind and listen were called on each socket). |
| 350 | |
| 351 | However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE |
| 352 | will ever be raised when attempting to bind two identical host/ports. When |
| 353 | accept() is called on each socket, the second caller's process will steal |
| 354 | the port from the first caller, leaving them both in an awkwardly wedged |
| 355 | state where they'll no longer respond to any signals or graceful kills, and |
| 356 | must be forcibly killed via OpenProcess()/TerminateProcess(). |
| 357 | |
| 358 | The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option |
| 359 | instead of SO_REUSEADDR, which effectively affords the same semantics as |
| 360 | SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open |
| 361 | Source world compared to Windows ones, this is a common mistake. A quick |
| 362 | look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when |
| 363 | openssl.exe is called with the 's_server' option, for example. See |
| 364 | http://bugs.python.org/issue2550 for more info. The following site also |
| 365 | has a very thorough description about the implications of both REUSEADDR |
| 366 | and EXCLUSIVEADDRUSE on Windows: |
| 367 | http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) |
| 368 | |
| 369 | XXX: although this approach is a vast improvement on previous attempts to |
| 370 | elicit unused ports, it rests heavily on the assumption that the ephemeral |
| 371 | port returned to us by the OS won't immediately be dished back out to some |
| 372 | other process when we close and delete our temporary socket but before our |
| 373 | calling code has a chance to bind the returned port. We can deal with this |
| 374 | issue if/when we come across it. |
| 375 | """ |
| 376 | |
| 377 | tempsock = socket.socket(family, socktype) |
| 378 | port = bind_port(tempsock) |
| 379 | tempsock.close() |
| 380 | del tempsock |
| 381 | return port |
| 382 | |
| 383 | def bind_port(sock, host=HOST): |
| 384 | """Bind the socket to a free port and return the port number. Relies on |
| 385 | ephemeral ports in order to ensure we are using an unbound port. This is |
| 386 | important as many tests may be running simultaneously, especially in a |
| 387 | buildbot environment. This method raises an exception if the sock.family |
| 388 | is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR |
| 389 | or SO_REUSEPORT set on it. Tests should *never* set these socket options |
| 390 | for TCP/IP sockets. The only case for setting these options is testing |
| 391 | multicasting via multiple UDP sockets. |
| 392 | |
| 393 | Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. |
| 394 | on Windows), it will be set on the socket. This will prevent anyone else |
| 395 | from bind()'ing to our host/port for the duration of the test. |
| 396 | """ |
| 397 | |
| 398 | if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: |
| 399 | if hasattr(socket, 'SO_REUSEADDR'): |
| 400 | if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: |
| 401 | raise TestFailed("tests should never set the SO_REUSEADDR " \ |
| 402 | "socket option on TCP/IP sockets!") |
| 403 | if hasattr(socket, 'SO_REUSEPORT'): |
| 404 | if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: |
| 405 | raise TestFailed("tests should never set the SO_REUSEPORT " \ |
| 406 | "socket option on TCP/IP sockets!") |
| 407 | if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): |
| 408 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) |
| 409 | |
| 410 | sock.bind((host, 0)) |
| 411 | port = sock.getsockname()[1] |
| 412 | return port |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 413 | |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 414 | FUZZ = 1e-6 |
| 415 | |
| 416 | def fcmp(x, y): # fuzzy comparison function |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 417 | if isinstance(x, float) or isinstance(y, float): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 418 | try: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 419 | fuzz = (abs(x) + abs(y)) * FUZZ |
| 420 | if abs(x-y) <= fuzz: |
| 421 | return 0 |
| 422 | except: |
| 423 | pass |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 424 | elif type(x) == type(y) and isinstance(x, (tuple, list)): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 425 | for i in range(min(len(x), len(y))): |
| 426 | outcome = fcmp(x[i], y[i]) |
Fred Drake | 132dce2 | 2000-12-12 23:11:42 +0000 | [diff] [blame] | 427 | if outcome != 0: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 428 | return outcome |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 429 | return (len(x) > len(y)) - (len(x) < len(y)) |
| 430 | return (x > y) - (x < y) |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 431 | |
Eric Smith | f24a0d9 | 2010-12-04 13:32:18 +0000 | [diff] [blame] | 432 | # decorator for skipping tests on non-IEEE 754 platforms |
| 433 | requires_IEEE_754 = unittest.skipUnless( |
| 434 | float.__getformat__("double").startswith("IEEE"), |
| 435 | "test requires IEEE 754 doubles") |
| 436 | |
Finn Bock | 57bc5fa | 2002-11-01 18:02:03 +0000 | [diff] [blame] | 437 | is_jython = sys.platform.startswith('java') |
| 438 | |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 439 | # Filename used for testing |
| 440 | if os.name == 'java': |
| 441 | # Jython disallows @ in module names |
| 442 | TESTFN = '$test' |
Martin v. Löwis | a94568a | 2003-05-10 07:36:56 +0000 | [diff] [blame] | 443 | else: |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 444 | TESTFN = '@test' |
Walter Dörwald | 9b77553 | 2007-06-08 14:30:53 +0000 | [diff] [blame] | 445 | |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 446 | # Disambiguate TESTFN for parallel testing, while letting it remain a valid |
| 447 | # module name. |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 448 | TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid()) |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 449 | |
Michael Foord | 2d9c2d5 | 2010-05-04 22:29:10 +0000 | [diff] [blame] | 450 | |
Victor Stinner | d91df1a | 2010-08-18 10:56:19 +0000 | [diff] [blame] | 451 | # TESTFN_UNICODE is a non-ascii filename |
| 452 | TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f" |
Victor Stinner | 74a833f | 2010-08-18 21:06:23 +0000 | [diff] [blame] | 453 | if sys.platform == 'darwin': |
| 454 | # In Mac OS X's VFS API file names are, by definition, canonically |
| 455 | # decomposed Unicode, encoded using UTF-8. See QA1173: |
| 456 | # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html |
| 457 | import unicodedata |
| 458 | TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE) |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 459 | TESTFN_ENCODING = sys.getfilesystemencoding() |
Victor Stinner | 3d85a6f | 2010-08-13 13:02:04 +0000 | [diff] [blame] | 460 | |
Victor Stinner | 09c449c | 2010-08-13 22:23:24 +0000 | [diff] [blame] | 461 | # TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be |
Victor Stinner | 3d85a6f | 2010-08-13 13:02:04 +0000 | [diff] [blame] | 462 | # encoded by the filesystem encoding (in strict mode). It can be None if we |
| 463 | # cannot generate such filename. |
Victor Stinner | a0241c8 | 2010-08-15 19:28:21 +0000 | [diff] [blame] | 464 | TESTFN_UNENCODABLE = None |
Victor Stinner | 3d85a6f | 2010-08-13 13:02:04 +0000 | [diff] [blame] | 465 | if os.name in ('nt', 'ce'): |
Victor Stinner | a0241c8 | 2010-08-15 19:28:21 +0000 | [diff] [blame] | 466 | # skip win32s (0) or Windows 9x/ME (1) |
| 467 | if sys.getwindowsversion().platform >= 2: |
Victor Stinner | 8ce7df6 | 2010-09-10 11:19:59 +0000 | [diff] [blame] | 468 | # Different kinds of characters from various languages to minimize the |
| 469 | # probability that the whole name is encodable to MBCS (issue #9819) |
| 470 | TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80" |
Victor Stinner | 3d85a6f | 2010-08-13 13:02:04 +0000 | [diff] [blame] | 471 | try: |
Victor Stinner | 09c449c | 2010-08-13 22:23:24 +0000 | [diff] [blame] | 472 | TESTFN_UNENCODABLE.encode(TESTFN_ENCODING) |
Victor Stinner | 3d85a6f | 2010-08-13 13:02:04 +0000 | [diff] [blame] | 473 | except UnicodeEncodeError: |
| 474 | pass |
| 475 | else: |
| 476 | print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). ' |
| 477 | 'Unicode filename tests may not be effective' |
Victor Stinner | 09c449c | 2010-08-13 22:23:24 +0000 | [diff] [blame] | 478 | % (TESTFN_UNENCODABLE, TESTFN_ENCODING)) |
| 479 | TESTFN_UNENCODABLE = None |
Victor Stinner | a0241c8 | 2010-08-15 19:28:21 +0000 | [diff] [blame] | 480 | # Mac OS X denies unencodable filenames (invalid utf-8) |
Victor Stinner | 03c9e1d | 2010-08-14 17:35:20 +0000 | [diff] [blame] | 481 | elif sys.platform != 'darwin': |
Victor Stinner | 3d85a6f | 2010-08-13 13:02:04 +0000 | [diff] [blame] | 482 | try: |
| 483 | # ascii and utf-8 cannot encode the byte 0xff |
| 484 | b'\xff'.decode(TESTFN_ENCODING) |
| 485 | except UnicodeDecodeError: |
| 486 | # 0xff will be encoded using the surrogate character u+DCFF |
Victor Stinner | 09c449c | 2010-08-13 22:23:24 +0000 | [diff] [blame] | 487 | TESTFN_UNENCODABLE = TESTFN \ |
Victor Stinner | 3d85a6f | 2010-08-13 13:02:04 +0000 | [diff] [blame] | 488 | + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape') |
| 489 | else: |
| 490 | # File system encoding (eg. ISO-8859-* encodings) can encode |
| 491 | # the byte 0xff. Skip some unicode filename tests. |
Victor Stinner | a0241c8 | 2010-08-15 19:28:21 +0000 | [diff] [blame] | 492 | pass |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 493 | |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 494 | # Save the initial cwd |
| 495 | SAVEDCWD = os.getcwd() |
| 496 | |
| 497 | @contextlib.contextmanager |
Nick Coghlan | d26c18a | 2010-08-17 13:06:11 +0000 | [diff] [blame] | 498 | def temp_cwd(name='tempcwd', quiet=False, path=None): |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 499 | """ |
Nick Coghlan | d26c18a | 2010-08-17 13:06:11 +0000 | [diff] [blame] | 500 | Context manager that temporarily changes the CWD. |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 501 | |
Nick Coghlan | d26c18a | 2010-08-17 13:06:11 +0000 | [diff] [blame] | 502 | An existing path may be provided as *path*, in which case this |
| 503 | function makes no changes to the file system. |
| 504 | |
| 505 | Otherwise, the new CWD is created in the current directory and it's |
| 506 | named *name*. If *quiet* is False (default) and it's not possible to |
| 507 | create or change the CWD, an error is raised. If it's True, only a |
| 508 | warning is raised and the original CWD is used. |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 509 | """ |
| 510 | saved_dir = os.getcwd() |
| 511 | is_temporary = False |
Nick Coghlan | d26c18a | 2010-08-17 13:06:11 +0000 | [diff] [blame] | 512 | if path is None: |
| 513 | path = name |
| 514 | try: |
| 515 | os.mkdir(name) |
| 516 | is_temporary = True |
| 517 | except OSError: |
| 518 | if not quiet: |
| 519 | raise |
| 520 | warnings.warn('tests may fail, unable to create temp CWD ' + name, |
| 521 | RuntimeWarning, stacklevel=3) |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 522 | try: |
Nick Coghlan | d26c18a | 2010-08-17 13:06:11 +0000 | [diff] [blame] | 523 | os.chdir(path) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 524 | except OSError: |
| 525 | if not quiet: |
| 526 | raise |
| 527 | warnings.warn('tests may fail, unable to change the CWD to ' + name, |
| 528 | RuntimeWarning, stacklevel=3) |
| 529 | try: |
| 530 | yield os.getcwd() |
| 531 | finally: |
| 532 | os.chdir(saved_dir) |
| 533 | if is_temporary: |
| 534 | rmtree(name) |
| 535 | |
Guido van Rossum | a8f7e59 | 2001-03-13 09:31:07 +0000 | [diff] [blame] | 536 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 537 | @contextlib.contextmanager |
| 538 | def temp_umask(umask): |
| 539 | """Context manager that temporarily sets the process umask.""" |
| 540 | oldmask = os.umask(umask) |
| 541 | try: |
| 542 | yield |
| 543 | finally: |
| 544 | os.umask(oldmask) |
| 545 | |
| 546 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 547 | def findfile(file, here=__file__, subdir=None): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 548 | """Try to find a file on sys.path and the working directory. If it is not |
| 549 | found the argument passed to the function is returned (this does not |
| 550 | necessarily signal failure; could still be the legitimate path).""" |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 551 | if os.path.isabs(file): |
| 552 | return file |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 553 | if subdir is not None: |
| 554 | file = os.path.join(subdir, file) |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 555 | path = sys.path |
| 556 | path = [os.path.dirname(here)] + path |
| 557 | for dn in path: |
| 558 | fn = os.path.join(dn, file) |
| 559 | if os.path.exists(fn): return fn |
| 560 | return file |
Marc-André Lemburg | 3661908 | 2001-01-17 19:11:13 +0000 | [diff] [blame] | 561 | |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 562 | def sortdict(dict): |
| 563 | "Like repr(dict), but in sorted order." |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 564 | items = sorted(dict.items()) |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 565 | reprpairs = ["%r: %r" % pair for pair in items] |
| 566 | withcommas = ", ".join(reprpairs) |
| 567 | return "{%s}" % withcommas |
| 568 | |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 569 | def make_bad_fd(): |
| 570 | """ |
| 571 | Create an invalid file descriptor by opening and closing a file and return |
| 572 | its fd. |
| 573 | """ |
| 574 | file = open(TESTFN, "wb") |
| 575 | try: |
| 576 | return file.fileno() |
| 577 | finally: |
| 578 | file.close() |
| 579 | unlink(TESTFN) |
| 580 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 581 | def check_syntax_error(testcase, statement): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 582 | testcase.assertRaises(SyntaxError, compile, statement, |
| 583 | '<test string>', 'exec') |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 584 | |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 585 | def open_urlresource(url, *args, **kw): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 586 | import urllib.request, urllib.parse |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 587 | |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 588 | check = kw.pop('check', None) |
| 589 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 590 | filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL! |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 591 | |
Alexandre Vassalotti | 711ed4a | 2009-07-17 10:42:05 +0000 | [diff] [blame] | 592 | fn = os.path.join(os.path.dirname(__file__), "data", filename) |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 593 | |
| 594 | def check_valid_file(fn): |
| 595 | f = open(fn, *args, **kw) |
| 596 | if check is None: |
| 597 | return f |
| 598 | elif check(f): |
| 599 | f.seek(0) |
| 600 | return f |
| 601 | f.close() |
| 602 | |
Alexandre Vassalotti | 711ed4a | 2009-07-17 10:42:05 +0000 | [diff] [blame] | 603 | if os.path.exists(fn): |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 604 | f = check_valid_file(fn) |
| 605 | if f is not None: |
| 606 | return f |
| 607 | unlink(fn) |
| 608 | |
| 609 | # Verify the requirement before downloading the file |
| 610 | requires('urlfetch') |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 611 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 612 | print('\tfetching %s ...' % url, file=get_original_stdout()) |
Antoine Pitrou | fd0680b | 2009-11-01 22:13:48 +0000 | [diff] [blame] | 613 | f = urllib.request.urlopen(url, timeout=15) |
| 614 | try: |
| 615 | with open(fn, "wb") as out: |
| 616 | s = f.read() |
| 617 | while s: |
| 618 | out.write(s) |
| 619 | s = f.read() |
| 620 | finally: |
| 621 | f.close() |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 622 | |
| 623 | f = check_valid_file(fn) |
| 624 | if f is not None: |
| 625 | return f |
| 626 | raise TestFailed('invalid resource "%s"' % fn) |
| 627 | |
Thomas Wouters | 9fe394c | 2007-02-05 01:24:16 +0000 | [diff] [blame] | 628 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 629 | class WarningsRecorder(object): |
| 630 | """Convenience wrapper for the warnings list returned on |
| 631 | entry to the warnings.catch_warnings() context manager. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 632 | """ |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 633 | def __init__(self, warnings_list): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 634 | self._warnings = warnings_list |
| 635 | self._last = 0 |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 636 | |
| 637 | def __getattr__(self, attr): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 638 | if len(self._warnings) > self._last: |
| 639 | return getattr(self._warnings[-1], attr) |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 640 | elif attr in warnings.WarningMessage._WARNING_DETAILS: |
| 641 | return None |
| 642 | raise AttributeError("%r has no attribute %r" % (self, attr)) |
| 643 | |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 644 | @property |
| 645 | def warnings(self): |
| 646 | return self._warnings[self._last:] |
| 647 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 648 | def reset(self): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 649 | self._last = len(self._warnings) |
| 650 | |
| 651 | |
| 652 | def _filterwarnings(filters, quiet=False): |
| 653 | """Catch the warnings, then check if all the expected |
| 654 | warnings have been raised and re-raise unexpected warnings. |
| 655 | If 'quiet' is True, only re-raise the unexpected warnings. |
| 656 | """ |
| 657 | # Clear the warning registry of the calling module |
| 658 | # in order to re-raise the warnings. |
| 659 | frame = sys._getframe(2) |
| 660 | registry = frame.f_globals.get('__warningregistry__') |
| 661 | if registry: |
| 662 | registry.clear() |
| 663 | with warnings.catch_warnings(record=True) as w: |
| 664 | # Set filter "always" to record all warnings. Because |
| 665 | # test_warnings swap the module, we need to look up in |
| 666 | # the sys.modules dictionary. |
| 667 | sys.modules['warnings'].simplefilter("always") |
| 668 | yield WarningsRecorder(w) |
| 669 | # Filter the recorded warnings |
Antoine Pitrou | 31e08a4 | 2010-10-29 11:54:03 +0000 | [diff] [blame] | 670 | reraise = list(w) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 671 | missing = [] |
| 672 | for msg, cat in filters: |
| 673 | seen = False |
Antoine Pitrou | 31e08a4 | 2010-10-29 11:54:03 +0000 | [diff] [blame] | 674 | for w in reraise[:]: |
| 675 | warning = w.message |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 676 | # Filter out the matching messages |
Antoine Pitrou | 31e08a4 | 2010-10-29 11:54:03 +0000 | [diff] [blame] | 677 | if (re.match(msg, str(warning), re.I) and |
| 678 | issubclass(warning.__class__, cat)): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 679 | seen = True |
Antoine Pitrou | 31e08a4 | 2010-10-29 11:54:03 +0000 | [diff] [blame] | 680 | reraise.remove(w) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 681 | if not seen and not quiet: |
| 682 | # This filter caught nothing |
| 683 | missing.append((msg, cat.__name__)) |
| 684 | if reraise: |
Antoine Pitrou | 31e08a4 | 2010-10-29 11:54:03 +0000 | [diff] [blame] | 685 | raise AssertionError("unhandled warning %s" % reraise[0]) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 686 | if missing: |
| 687 | raise AssertionError("filter (%r, %s) did not catch any warning" % |
| 688 | missing[0]) |
| 689 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 690 | |
| 691 | @contextlib.contextmanager |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 692 | def check_warnings(*filters, **kwargs): |
| 693 | """Context manager to silence warnings. |
| 694 | |
| 695 | Accept 2-tuples as positional arguments: |
| 696 | ("message regexp", WarningCategory) |
| 697 | |
| 698 | Optional argument: |
| 699 | - if 'quiet' is True, it does not fail if a filter catches nothing |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 700 | (default True without argument, |
| 701 | default False if some filters are defined) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 702 | |
| 703 | Without argument, it defaults to: |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 704 | check_warnings(("", Warning), quiet=True) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 705 | """ |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 706 | quiet = kwargs.get('quiet') |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 707 | if not filters: |
| 708 | filters = (("", Warning),) |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 709 | # Preserve backward compatibility |
| 710 | if quiet is None: |
| 711 | quiet = True |
| 712 | return _filterwarnings(filters, quiet) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 713 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 714 | |
| 715 | class CleanImport(object): |
| 716 | """Context manager to force import to return a new module reference. |
| 717 | |
| 718 | This is useful for testing module-level behaviours, such as |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 719 | the emission of a DeprecationWarning on import. |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 720 | |
| 721 | Use like this: |
| 722 | |
| 723 | with CleanImport("foo"): |
Brett Cannon | ddb5e70 | 2010-02-03 22:16:11 +0000 | [diff] [blame] | 724 | importlib.import_module("foo") # new reference |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 725 | """ |
| 726 | |
| 727 | def __init__(self, *module_names): |
| 728 | self.original_modules = sys.modules.copy() |
| 729 | for module_name in module_names: |
| 730 | if module_name in sys.modules: |
| 731 | module = sys.modules[module_name] |
| 732 | # It is possible that module_name is just an alias for |
| 733 | # another module (e.g. stub for modules renamed in 3.x). |
| 734 | # In that case, we also need delete the real module to clear |
| 735 | # the import cache. |
| 736 | if module.__name__ != module_name: |
| 737 | del sys.modules[module.__name__] |
| 738 | del sys.modules[module_name] |
| 739 | |
| 740 | def __enter__(self): |
| 741 | return self |
| 742 | |
| 743 | def __exit__(self, *ignore_exc): |
| 744 | sys.modules.update(self.original_modules) |
| 745 | |
| 746 | |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 747 | class EnvironmentVarGuard(collections.MutableMapping): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 748 | |
| 749 | """Class to help protect the environment variable properly. Can be used as |
| 750 | a context manager.""" |
| 751 | |
| 752 | def __init__(self): |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 753 | self._environ = os.environ |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 754 | self._changed = {} |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 755 | |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 756 | def __getitem__(self, envvar): |
| 757 | return self._environ[envvar] |
| 758 | |
| 759 | def __setitem__(self, envvar, value): |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 760 | # Remember the initial value on the first access |
| 761 | if envvar not in self._changed: |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 762 | self._changed[envvar] = self._environ.get(envvar) |
| 763 | self._environ[envvar] = value |
| 764 | |
| 765 | def __delitem__(self, envvar): |
| 766 | # Remember the initial value on the first access |
| 767 | if envvar not in self._changed: |
| 768 | self._changed[envvar] = self._environ.get(envvar) |
| 769 | if envvar in self._environ: |
| 770 | del self._environ[envvar] |
| 771 | |
| 772 | def keys(self): |
| 773 | return self._environ.keys() |
| 774 | |
| 775 | def __iter__(self): |
| 776 | return iter(self._environ) |
| 777 | |
| 778 | def __len__(self): |
| 779 | return len(self._environ) |
| 780 | |
| 781 | def set(self, envvar, value): |
| 782 | self[envvar] = value |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 783 | |
| 784 | def unset(self, envvar): |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 785 | del self[envvar] |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 786 | |
| 787 | def __enter__(self): |
| 788 | return self |
| 789 | |
| 790 | def __exit__(self, *ignore_exc): |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 791 | for (k, v) in self._changed.items(): |
| 792 | if v is None: |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 793 | if k in self._environ: |
| 794 | del self._environ[k] |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 795 | else: |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 796 | self._environ[k] = v |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 797 | os.environ = self._environ |
| 798 | |
| 799 | |
| 800 | class DirsOnSysPath(object): |
| 801 | """Context manager to temporarily add directories to sys.path. |
| 802 | |
| 803 | This makes a copy of sys.path, appends any directories given |
| 804 | as positional arguments, then reverts sys.path to the copied |
| 805 | settings when the context ends. |
| 806 | |
| 807 | Note that *all* sys.path modifications in the body of the |
| 808 | context manager, including replacement of the object, |
| 809 | will be reverted at the end of the block. |
| 810 | """ |
| 811 | |
| 812 | def __init__(self, *paths): |
| 813 | self.original_value = sys.path[:] |
| 814 | self.original_object = sys.path |
| 815 | sys.path.extend(paths) |
| 816 | |
| 817 | def __enter__(self): |
| 818 | return self |
| 819 | |
| 820 | def __exit__(self, *ignore_exc): |
| 821 | sys.path = self.original_object |
| 822 | sys.path[:] = self.original_value |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 823 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 824 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 825 | class TransientResource(object): |
| 826 | |
| 827 | """Raise ResourceDenied if an exception is raised while the context manager |
| 828 | is in effect that matches the specified exception and attributes.""" |
| 829 | |
| 830 | def __init__(self, exc, **kwargs): |
| 831 | self.exc = exc |
| 832 | self.attrs = kwargs |
| 833 | |
| 834 | def __enter__(self): |
| 835 | return self |
| 836 | |
| 837 | def __exit__(self, type_=None, value=None, traceback=None): |
| 838 | """If type_ is a subclass of self.exc and value has attributes matching |
| 839 | self.attrs, raise ResourceDenied. Otherwise let the exception |
| 840 | propagate (if any).""" |
| 841 | if type_ is not None and issubclass(self.exc, type_): |
| 842 | for attr, attr_value in self.attrs.items(): |
| 843 | if not hasattr(value, attr): |
| 844 | break |
| 845 | if getattr(value, attr) != attr_value: |
| 846 | break |
| 847 | else: |
| 848 | raise ResourceDenied("an optional resource is not available") |
| 849 | |
Raymond Hettinger | 686057b | 2009-06-04 00:11:54 +0000 | [diff] [blame] | 850 | # Context managers that raise ResourceDenied when various issues |
| 851 | # with the Internet connection manifest themselves as exceptions. |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 852 | # XXX deprecate these and use transient_internet() instead |
Raymond Hettinger | 686057b | 2009-06-04 00:11:54 +0000 | [diff] [blame] | 853 | time_out = TransientResource(IOError, errno=errno.ETIMEDOUT) |
| 854 | socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET) |
| 855 | ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 856 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 857 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 858 | @contextlib.contextmanager |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 859 | def transient_internet(resource_name, *, timeout=30.0, errnos=()): |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 860 | """Return a context manager that raises ResourceDenied when various issues |
| 861 | with the Internet connection manifest themselves as exceptions.""" |
Antoine Pitrou | 8bc0903 | 2010-09-07 21:09:09 +0000 | [diff] [blame] | 862 | default_errnos = [ |
| 863 | ('ECONNREFUSED', 111), |
| 864 | ('ECONNRESET', 104), |
Antoine Pitrou | 5d938cb | 2011-01-08 10:28:11 +0000 | [diff] [blame] | 865 | ('EHOSTUNREACH', 113), |
Antoine Pitrou | 8bc0903 | 2010-09-07 21:09:09 +0000 | [diff] [blame] | 866 | ('ENETUNREACH', 101), |
| 867 | ('ETIMEDOUT', 110), |
| 868 | ] |
Antoine Pitrou | 2673c5b | 2010-09-07 21:43:31 +0000 | [diff] [blame] | 869 | default_gai_errnos = [ |
Antoine Pitrou | 4875c46 | 2011-07-09 02:31:24 +0200 | [diff] [blame] | 870 | ('EAI_AGAIN', -3), |
Antoine Pitrou | 2673c5b | 2010-09-07 21:43:31 +0000 | [diff] [blame] | 871 | ('EAI_NONAME', -2), |
| 872 | ('EAI_NODATA', -5), |
Antoine Pitrou | 390ea0f | 2011-04-29 00:44:33 +0200 | [diff] [blame] | 873 | # Encountered when trying to resolve IPv6-only hostnames |
| 874 | ('WSANO_DATA', 11004), |
Antoine Pitrou | 2673c5b | 2010-09-07 21:43:31 +0000 | [diff] [blame] | 875 | ] |
Antoine Pitrou | 8bc0903 | 2010-09-07 21:09:09 +0000 | [diff] [blame] | 876 | |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 877 | denied = ResourceDenied("Resource '%s' is not available" % resource_name) |
Antoine Pitrou | 8bc0903 | 2010-09-07 21:09:09 +0000 | [diff] [blame] | 878 | captured_errnos = errnos |
Antoine Pitrou | 2673c5b | 2010-09-07 21:43:31 +0000 | [diff] [blame] | 879 | gai_errnos = [] |
Antoine Pitrou | 8bc0903 | 2010-09-07 21:09:09 +0000 | [diff] [blame] | 880 | if not captured_errnos: |
| 881 | captured_errnos = [getattr(errno, name, num) |
| 882 | for (name, num) in default_errnos] |
Antoine Pitrou | 2673c5b | 2010-09-07 21:43:31 +0000 | [diff] [blame] | 883 | gai_errnos = [getattr(socket, name, num) |
| 884 | for (name, num) in default_gai_errnos] |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 885 | |
| 886 | def filter_error(err): |
Antoine Pitrou | 2673c5b | 2010-09-07 21:43:31 +0000 | [diff] [blame] | 887 | n = getattr(err, 'errno', None) |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 888 | if (isinstance(err, socket.timeout) or |
Antoine Pitrou | 2673c5b | 2010-09-07 21:43:31 +0000 | [diff] [blame] | 889 | (isinstance(err, socket.gaierror) and n in gai_errnos) or |
| 890 | n in captured_errnos): |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 891 | if not verbose: |
| 892 | sys.stderr.write(denied.args[0] + "\n") |
| 893 | raise denied from err |
| 894 | |
| 895 | old_timeout = socket.getdefaulttimeout() |
| 896 | try: |
| 897 | if timeout is not None: |
| 898 | socket.setdefaulttimeout(timeout) |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 899 | yield |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 900 | except IOError as err: |
Antoine Pitrou | 8bc0903 | 2010-09-07 21:09:09 +0000 | [diff] [blame] | 901 | # urllib can wrap original socket errors multiple times (!), we must |
| 902 | # unwrap to get at the original error. |
| 903 | while True: |
| 904 | a = err.args |
| 905 | if len(a) >= 1 and isinstance(a[0], IOError): |
| 906 | err = a[0] |
| 907 | # The error can also be wrapped as args[1]: |
| 908 | # except socket.error as msg: |
| 909 | # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2]) |
| 910 | elif len(a) >= 2 and isinstance(a[1], IOError): |
| 911 | err = a[1] |
| 912 | else: |
| 913 | break |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 914 | filter_error(err) |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 915 | raise |
| 916 | # XXX should we catch generic exceptions and look for their |
| 917 | # __cause__ or __context__? |
| 918 | finally: |
| 919 | socket.setdefaulttimeout(old_timeout) |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 920 | |
| 921 | |
| 922 | @contextlib.contextmanager |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 923 | def captured_output(stream_name): |
Ezio Melotti | 07352b0 | 2011-05-14 14:51:18 +0300 | [diff] [blame] | 924 | """Return a context manager used by captured_stdout/stdin/stderr |
Ezio Melotti | fc778fd | 2011-05-14 08:22:47 +0300 | [diff] [blame] | 925 | that temporarily replaces the sys stream *stream_name* with a StringIO.""" |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 926 | import io |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 927 | orig_stdout = getattr(sys, stream_name) |
| 928 | setattr(sys, stream_name, io.StringIO()) |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 929 | try: |
| 930 | yield getattr(sys, stream_name) |
| 931 | finally: |
| 932 | setattr(sys, stream_name, orig_stdout) |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 933 | |
| 934 | def captured_stdout(): |
Ezio Melotti | fc778fd | 2011-05-14 08:22:47 +0300 | [diff] [blame] | 935 | """Capture the output of sys.stdout: |
| 936 | |
| 937 | with captured_stdout() as s: |
| 938 | print("hello") |
| 939 | self.assertEqual(s.getvalue(), "hello") |
| 940 | """ |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 941 | return captured_output("stdout") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 942 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 943 | def captured_stderr(): |
| 944 | return captured_output("stderr") |
| 945 | |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 946 | def captured_stdin(): |
| 947 | return captured_output("stdin") |
| 948 | |
Ezio Melotti | 07352b0 | 2011-05-14 14:51:18 +0300 | [diff] [blame] | 949 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 950 | def gc_collect(): |
| 951 | """Force as many objects as possible to be collected. |
| 952 | |
| 953 | In non-CPython implementations of Python, this is needed because timely |
| 954 | deallocation is not guaranteed by the garbage collector. (Even in CPython |
| 955 | this can be the case in case of reference cycles.) This means that __del__ |
| 956 | methods may be called later than expected and weakrefs may remain alive for |
| 957 | longer than expected. This function tries its best to force all garbage |
| 958 | objects to disappear. |
| 959 | """ |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 960 | gc.collect() |
Benjamin Peterson | a6590e8 | 2010-04-11 21:22:10 +0000 | [diff] [blame] | 961 | if is_jython: |
| 962 | time.sleep(0.1) |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 963 | gc.collect() |
| 964 | gc.collect() |
| 965 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 966 | |
Benjamin Peterson | 65c66ab | 2010-10-29 21:31:35 +0000 | [diff] [blame] | 967 | def python_is_optimized(): |
| 968 | """Find if Python was built with optimizations.""" |
Antoine Pitrou | 6447454 | 2010-10-31 11:34:47 +0000 | [diff] [blame] | 969 | cflags = sysconfig.get_config_var('PY_CFLAGS') or '' |
Benjamin Peterson | 65c66ab | 2010-10-29 21:31:35 +0000 | [diff] [blame] | 970 | final_opt = "" |
| 971 | for opt in cflags.split(): |
| 972 | if opt.startswith('-O'): |
| 973 | final_opt = opt |
| 974 | return final_opt and final_opt != '-O0' |
| 975 | |
| 976 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 977 | #======================================================================= |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 978 | # Decorator for running a function in a different locale, correctly resetting |
| 979 | # it afterwards. |
| 980 | |
| 981 | def run_with_locale(catstr, *locales): |
| 982 | def decorator(func): |
| 983 | def inner(*args, **kwds): |
| 984 | try: |
| 985 | import locale |
| 986 | category = getattr(locale, catstr) |
| 987 | orig_locale = locale.setlocale(category) |
| 988 | except AttributeError: |
| 989 | # if the test author gives us an invalid category string |
| 990 | raise |
| 991 | except: |
| 992 | # cannot retrieve original locale, so do nothing |
| 993 | locale = orig_locale = None |
| 994 | else: |
| 995 | for loc in locales: |
| 996 | try: |
| 997 | locale.setlocale(category, loc) |
| 998 | break |
| 999 | except: |
| 1000 | pass |
| 1001 | |
| 1002 | # now run the function, resetting the locale on exceptions |
| 1003 | try: |
| 1004 | return func(*args, **kwds) |
| 1005 | finally: |
| 1006 | if locale and orig_locale: |
| 1007 | locale.setlocale(category, orig_locale) |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 1008 | inner.__name__ = func.__name__ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1009 | inner.__doc__ = func.__doc__ |
| 1010 | return inner |
| 1011 | return decorator |
| 1012 | |
| 1013 | #======================================================================= |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 1014 | # Big-memory-test support. Separate from 'resources' because memory use |
| 1015 | # should be configurable. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1016 | |
| 1017 | # Some handy shorthands. Note that these are used for byte-limits as well |
| 1018 | # as size-limits, in the various bigmem tests |
| 1019 | _1M = 1024*1024 |
| 1020 | _1G = 1024 * _1M |
| 1021 | _2G = 2 * _1G |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 1022 | _4G = 4 * _1G |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1023 | |
Thomas Wouters | d2cf20e | 2007-08-30 22:57:53 +0000 | [diff] [blame] | 1024 | MAX_Py_ssize_t = sys.maxsize |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1025 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1026 | def set_memlimit(limit): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1027 | global max_memuse |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 1028 | global real_max_memuse |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1029 | sizes = { |
| 1030 | 'k': 1024, |
| 1031 | 'm': _1M, |
| 1032 | 'g': _1G, |
| 1033 | 't': 1024*_1G, |
| 1034 | } |
| 1035 | m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit, |
| 1036 | re.IGNORECASE | re.VERBOSE) |
| 1037 | if m is None: |
| 1038 | raise ValueError('Invalid memory limit %r' % (limit,)) |
| 1039 | memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()]) |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 1040 | real_max_memuse = memlimit |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1041 | if memlimit > MAX_Py_ssize_t: |
| 1042 | memlimit = MAX_Py_ssize_t |
| 1043 | if memlimit < _2G - 1: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1044 | raise ValueError('Memory limit %r too low to be useful' % (limit,)) |
| 1045 | max_memuse = memlimit |
| 1046 | |
Antoine Pitrou | aca5fa7 | 2011-01-12 21:19:59 +0000 | [diff] [blame] | 1047 | def bigmemtest(minsize, memuse): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1048 | """Decorator for bigmem tests. |
| 1049 | |
| 1050 | 'minsize' is the minimum useful size for the test (in arbitrary, |
| 1051 | test-interpreted units.) 'memuse' is the number of 'bytes per size' for |
Antoine Pitrou | aca5fa7 | 2011-01-12 21:19:59 +0000 | [diff] [blame] | 1052 | the test, or a good estimate of it. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1053 | |
| 1054 | The decorator tries to guess a good value for 'size' and passes it to |
| 1055 | the decorated test function. If minsize * memuse is more than the |
| 1056 | allowed memory use (as defined by max_memuse), the test is skipped. |
| 1057 | Otherwise, minsize is adjusted upward to use up to max_memuse. |
| 1058 | """ |
| 1059 | def decorator(f): |
| 1060 | def wrapper(self): |
Antoine Pitrou | 7cdb495 | 2009-03-07 23:40:49 +0000 | [diff] [blame] | 1061 | # Retrieve values in case someone decided to adjust them |
| 1062 | minsize = wrapper.minsize |
| 1063 | memuse = wrapper.memuse |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1064 | if not max_memuse: |
| 1065 | # If max_memuse is 0 (the default), |
| 1066 | # we still want to run the tests with size set to a few kb, |
| 1067 | # to make sure they work. We still want to avoid using |
| 1068 | # too much memory, though, but we do that noisily. |
| 1069 | maxsize = 5147 |
Antoine Pitrou | 9dd1171 | 2011-01-12 21:40:20 +0000 | [diff] [blame] | 1070 | self.assertFalse(maxsize * memuse > 20 * _1M) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1071 | else: |
Antoine Pitrou | aca5fa7 | 2011-01-12 21:19:59 +0000 | [diff] [blame] | 1072 | maxsize = int(max_memuse / memuse) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1073 | if maxsize < minsize: |
Antoine Pitrou | aca5fa7 | 2011-01-12 21:19:59 +0000 | [diff] [blame] | 1074 | raise unittest.SkipTest( |
| 1075 | "not enough memory: %.1fG minimum needed" |
| 1076 | % (minsize * memuse / (1024 ** 3))) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1077 | return f(self, maxsize) |
| 1078 | wrapper.minsize = minsize |
| 1079 | wrapper.memuse = memuse |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1080 | return wrapper |
| 1081 | return decorator |
| 1082 | |
Antoine Pitrou | aca5fa7 | 2011-01-12 21:19:59 +0000 | [diff] [blame] | 1083 | def precisionbigmemtest(size, memuse): |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 1084 | def decorator(f): |
| 1085 | def wrapper(self): |
Antoine Pitrou | 7cdb495 | 2009-03-07 23:40:49 +0000 | [diff] [blame] | 1086 | size = wrapper.size |
| 1087 | memuse = wrapper.memuse |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 1088 | if not real_max_memuse: |
| 1089 | maxsize = 5147 |
| 1090 | else: |
| 1091 | maxsize = size |
| 1092 | |
| 1093 | if real_max_memuse and real_max_memuse < maxsize * memuse: |
Antoine Pitrou | aca5fa7 | 2011-01-12 21:19:59 +0000 | [diff] [blame] | 1094 | raise unittest.SkipTest( |
| 1095 | "not enough memory: %.1fG minimum needed" |
| 1096 | % (size * memuse / (1024 ** 3))) |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 1097 | |
| 1098 | return f(self, maxsize) |
| 1099 | wrapper.size = size |
| 1100 | wrapper.memuse = memuse |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 1101 | return wrapper |
| 1102 | return decorator |
| 1103 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1104 | def bigaddrspacetest(f): |
| 1105 | """Decorator for tests that fill the address space.""" |
| 1106 | def wrapper(self): |
| 1107 | if max_memuse < MAX_Py_ssize_t: |
Antoine Pitrou | 98c62bd | 2011-01-12 21:58:39 +0000 | [diff] [blame] | 1108 | if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31: |
Antoine Pitrou | e0d3f8a | 2011-01-12 21:50:44 +0000 | [diff] [blame] | 1109 | raise unittest.SkipTest( |
| 1110 | "not enough memory: try a 32-bit build instead") |
| 1111 | else: |
| 1112 | raise unittest.SkipTest( |
| 1113 | "not enough memory: %.1fG minimum needed" |
| 1114 | % (MAX_Py_ssize_t / (1024 ** 3))) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1115 | else: |
| 1116 | return f(self) |
| 1117 | return wrapper |
| 1118 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1119 | #======================================================================= |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1120 | # unittest integration. |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1121 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1122 | class BasicTestRunner: |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1123 | def run(self, test): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1124 | result = unittest.TestResult() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1125 | test(result) |
| 1126 | return result |
| 1127 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1128 | def _id(obj): |
| 1129 | return obj |
| 1130 | |
| 1131 | def requires_resource(resource): |
Antoine Pitrou | 4914f9e | 2011-02-26 16:49:08 +0000 | [diff] [blame] | 1132 | if resource == 'gui' and not _is_gui_available(): |
| 1133 | return unittest.skip("resource 'gui' is not available") |
Antoine Pitrou | 5bc4fa7 | 2010-10-14 15:34:31 +0000 | [diff] [blame] | 1134 | if is_resource_enabled(resource): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1135 | return _id |
| 1136 | else: |
| 1137 | return unittest.skip("resource {0!r} is not enabled".format(resource)) |
| 1138 | |
| 1139 | def cpython_only(test): |
| 1140 | """ |
| 1141 | Decorator for tests only applicable on CPython. |
| 1142 | """ |
| 1143 | return impl_detail(cpython=True)(test) |
| 1144 | |
| 1145 | def impl_detail(msg=None, **guards): |
| 1146 | if check_impl_detail(**guards): |
| 1147 | return _id |
| 1148 | if msg is None: |
| 1149 | guardnames, default = _parse_guards(guards) |
| 1150 | if default: |
| 1151 | msg = "implementation detail not available on {0}" |
| 1152 | else: |
| 1153 | msg = "implementation detail specific to {0}" |
| 1154 | guardnames = sorted(guardnames.keys()) |
| 1155 | msg = msg.format(' or '.join(guardnames)) |
| 1156 | return unittest.skip(msg) |
| 1157 | |
| 1158 | def _parse_guards(guards): |
| 1159 | # Returns a tuple ({platform_name: run_me}, default_value) |
| 1160 | if not guards: |
| 1161 | return ({'cpython': True}, False) |
Eric Smith | 886b40a | 2009-04-26 21:26:45 +0000 | [diff] [blame] | 1162 | is_true = list(guards.values())[0] |
| 1163 | assert list(guards.values()) == [is_true] * len(guards) # all True or all False |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 1164 | return (guards, not is_true) |
| 1165 | |
| 1166 | # Use the following check to guard CPython's implementation-specific tests -- |
| 1167 | # or to run them only on the implementation(s) guarded by the arguments. |
| 1168 | def check_impl_detail(**guards): |
| 1169 | """This function returns True or False depending on the host platform. |
| 1170 | Examples: |
| 1171 | if check_impl_detail(): # only on CPython (default) |
| 1172 | if check_impl_detail(jython=True): # only on Jython |
| 1173 | if check_impl_detail(cpython=False): # everywhere except on CPython |
| 1174 | """ |
| 1175 | guards, default = _parse_guards(guards) |
| 1176 | return guards.get(platform.python_implementation().lower(), default) |
| 1177 | |
| 1178 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1179 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1180 | def _run_suite(suite): |
Barry Warsaw | c88425e | 2001-09-20 06:31:22 +0000 | [diff] [blame] | 1181 | """Run tests from a unittest.TestSuite-derived class.""" |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1182 | if verbose: |
Victor Stinner | f58087b | 2010-05-02 17:24:51 +0000 | [diff] [blame] | 1183 | runner = unittest.TextTestRunner(sys.stdout, verbosity=2) |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1184 | else: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1185 | runner = BasicTestRunner() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1186 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1187 | result = runner.run(suite) |
| 1188 | if not result.wasSuccessful(): |
Fred Drake | 14f6c18 | 2001-07-16 18:51:32 +0000 | [diff] [blame] | 1189 | if len(result.errors) == 1 and not result.failures: |
| 1190 | err = result.errors[0][1] |
| 1191 | elif len(result.failures) == 1 and not result.errors: |
| 1192 | err = result.failures[0][1] |
| 1193 | else: |
R. David Murray | 723357e | 2009-10-19 18:06:17 +0000 | [diff] [blame] | 1194 | err = "multiple errors occurred" |
| 1195 | if not verbose: err += "; run in verbose mode for details" |
Tim Peters | 2d84f2c | 2001-09-08 03:37:56 +0000 | [diff] [blame] | 1196 | raise TestFailed(err) |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1197 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 1198 | |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1199 | def run_unittest(*classes): |
| 1200 | """Run tests from unittest.TestCase-derived classes.""" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1201 | valid_types = (unittest.TestSuite, unittest.TestCase) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 1202 | suite = unittest.TestSuite() |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1203 | for cls in classes: |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1204 | if isinstance(cls, str): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1205 | if cls in sys.modules: |
| 1206 | suite.addTest(unittest.findTestCases(sys.modules[cls])) |
| 1207 | else: |
| 1208 | raise ValueError("str arguments must be keys in sys.modules") |
| 1209 | elif isinstance(cls, valid_types): |
Raymond Hettinger | 21d9987 | 2003-07-16 02:59:32 +0000 | [diff] [blame] | 1210 | suite.addTest(cls) |
| 1211 | else: |
| 1212 | suite.addTest(unittest.makeSuite(cls)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1213 | _run_suite(suite) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 1214 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 1215 | |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1216 | #======================================================================= |
| 1217 | # doctest driver. |
| 1218 | |
| 1219 | def run_doctest(module, verbosity=None): |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 1220 | """Run doctest on the given module. Return (#failures, #tests). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1221 | |
| 1222 | If optional argument verbosity is not specified (or is None), pass |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1223 | support's belief about verbosity on to doctest. Else doctest's |
Tim Peters | bea3fb8 | 2001-09-10 01:39:21 +0000 | [diff] [blame] | 1224 | usual behavior is used (it searches sys.argv for -v). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1225 | """ |
| 1226 | |
| 1227 | import doctest |
| 1228 | |
| 1229 | if verbosity is None: |
| 1230 | verbosity = verbose |
| 1231 | else: |
| 1232 | verbosity = None |
| 1233 | |
Victor Stinner | bddc4d4 | 2011-06-29 15:52:46 +0200 | [diff] [blame] | 1234 | f, t = doctest.testmod(module, verbose=verbosity) |
| 1235 | if f: |
| 1236 | raise TestFailed("%d of %d doctests failed" % (f, t)) |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 1237 | if verbose: |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 1238 | print('doctest (%s) ... %d tests with zero failures' % |
| 1239 | (module.__name__, t)) |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 1240 | return f, t |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1241 | |
Antoine Pitrou | 060cee2 | 2009-11-13 16:29:04 +0000 | [diff] [blame] | 1242 | |
| 1243 | #======================================================================= |
| 1244 | # Support for saving and restoring the imported modules. |
| 1245 | |
| 1246 | def modules_setup(): |
| 1247 | return sys.modules.copy(), |
| 1248 | |
| 1249 | def modules_cleanup(oldmodules): |
| 1250 | # Encoders/decoders are registered permanently within the internal |
| 1251 | # codec cache. If we destroy the corresponding modules their |
| 1252 | # globals will be set to None which will trip up the cached functions. |
| 1253 | encodings = [(k, v) for k, v in sys.modules.items() |
| 1254 | if k.startswith('encodings.')] |
| 1255 | sys.modules.clear() |
| 1256 | sys.modules.update(encodings) |
Nick Coghlan | 90be5fb | 2011-01-11 10:05:20 +0000 | [diff] [blame] | 1257 | # XXX: This kind of problem can affect more than just encodings. In particular |
Eric Smith | a3e8f3d | 2011-01-11 10:24:34 +0000 | [diff] [blame] | 1258 | # extension modules (such as _ssl) don't cope with reloading properly. |
Nick Coghlan | 90be5fb | 2011-01-11 10:05:20 +0000 | [diff] [blame] | 1259 | # Really, test modules should be cleaning out the test specific modules they |
| 1260 | # know they added (ala test_runpy) rather than relying on this function (as |
| 1261 | # test_importhooks and test_pkg do currently). |
| 1262 | # Implicitly imported *real* modules should be left alone (see issue 10556). |
Antoine Pitrou | 060cee2 | 2009-11-13 16:29:04 +0000 | [diff] [blame] | 1263 | sys.modules.update(oldmodules) |
| 1264 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1265 | #======================================================================= |
| 1266 | # Threading support to prevent reporting refleaks when running regrtest.py -R |
| 1267 | |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1268 | # NOTE: we use thread._count() rather than threading.enumerate() (or the |
| 1269 | # moral equivalent thereof) because a threading.Thread object is still alive |
| 1270 | # until its __bootstrap() method has returned, even after it has been |
| 1271 | # unregistered from the threading module. |
| 1272 | # thread._count(), on the other hand, only gets decremented *after* the |
| 1273 | # __bootstrap() method has returned, which gives us reliable reference counts |
| 1274 | # at the end of a test run. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1275 | |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1276 | def threading_setup(): |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 1277 | if _thread: |
| 1278 | return _thread._count(), |
| 1279 | else: |
| 1280 | return 1, |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1281 | |
| 1282 | def threading_cleanup(nb_threads): |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 1283 | if not _thread: |
| 1284 | return |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1285 | _MAX_COUNT = 10 |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1286 | for count in range(_MAX_COUNT): |
| 1287 | n = _thread._count() |
| 1288 | if n == nb_threads: |
| 1289 | break |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1290 | time.sleep(0.1) |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1291 | # XXX print a warning in case of failure? |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1292 | |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 1293 | def reap_threads(func): |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 1294 | """Use this function when threads are being used. This will |
| 1295 | ensure that the threads are cleaned up even when the test fails. |
| 1296 | If threading is unavailable this function does nothing. |
| 1297 | """ |
| 1298 | if not _thread: |
| 1299 | return func |
| 1300 | |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 1301 | @functools.wraps(func) |
| 1302 | def decorator(*args): |
| 1303 | key = threading_setup() |
| 1304 | try: |
| 1305 | return func(*args) |
| 1306 | finally: |
| 1307 | threading_cleanup(*key) |
| 1308 | return decorator |
| 1309 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1310 | def reap_children(): |
| 1311 | """Use this function at the end of test_main() whenever sub-processes |
| 1312 | are started. This will help ensure that no extra children (zombies) |
| 1313 | stick around to hog resources and create problems when looking |
| 1314 | for refleaks. |
| 1315 | """ |
| 1316 | |
| 1317 | # Reap all our dead child processes so we don't leave zombies around. |
| 1318 | # These hog resources and might be causing some of the buildbots to die. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1319 | if hasattr(os, 'waitpid'): |
| 1320 | any_process = -1 |
| 1321 | while True: |
| 1322 | try: |
| 1323 | # This will raise an exception on Windows. That's ok. |
| 1324 | pid, status = os.waitpid(any_process, os.WNOHANG) |
| 1325 | if pid == 0: |
| 1326 | break |
| 1327 | except: |
| 1328 | break |
Collin Winter | f2bf2b3 | 2010-03-17 00:41:56 +0000 | [diff] [blame] | 1329 | |
| 1330 | @contextlib.contextmanager |
| 1331 | def swap_attr(obj, attr, new_val): |
| 1332 | """Temporary swap out an attribute with a new object. |
| 1333 | |
| 1334 | Usage: |
| 1335 | with swap_attr(obj, "attr", 5): |
| 1336 | ... |
| 1337 | |
| 1338 | This will set obj.attr to 5 for the duration of the with: block, |
| 1339 | restoring the old value at the end of the block. If `attr` doesn't |
| 1340 | exist on `obj`, it will be created and then deleted at the end of the |
| 1341 | block. |
| 1342 | """ |
| 1343 | if hasattr(obj, attr): |
| 1344 | real_val = getattr(obj, attr) |
| 1345 | setattr(obj, attr, new_val) |
| 1346 | try: |
| 1347 | yield |
| 1348 | finally: |
| 1349 | setattr(obj, attr, real_val) |
| 1350 | else: |
| 1351 | setattr(obj, attr, new_val) |
| 1352 | try: |
| 1353 | yield |
| 1354 | finally: |
| 1355 | delattr(obj, attr) |
| 1356 | |
| 1357 | @contextlib.contextmanager |
| 1358 | def swap_item(obj, item, new_val): |
| 1359 | """Temporary swap out an item with a new object. |
| 1360 | |
| 1361 | Usage: |
| 1362 | with swap_item(obj, "item", 5): |
| 1363 | ... |
| 1364 | |
| 1365 | This will set obj["item"] to 5 for the duration of the with: block, |
| 1366 | restoring the old value at the end of the block. If `item` doesn't |
| 1367 | exist on `obj`, it will be created and then deleted at the end of the |
| 1368 | block. |
| 1369 | """ |
| 1370 | if item in obj: |
| 1371 | real_val = obj[item] |
| 1372 | obj[item] = new_val |
| 1373 | try: |
| 1374 | yield |
| 1375 | finally: |
| 1376 | obj[item] = real_val |
| 1377 | else: |
| 1378 | obj[item] = new_val |
| 1379 | try: |
| 1380 | yield |
| 1381 | finally: |
| 1382 | del obj[item] |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 1383 | |
| 1384 | def strip_python_stderr(stderr): |
| 1385 | """Strip the stderr of a Python process from potential debug output |
| 1386 | emitted by the interpreter. |
| 1387 | |
| 1388 | This will typically be run on the result of the communicate() method |
| 1389 | of a subprocess.Popen object. |
| 1390 | """ |
| 1391 | stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip() |
| 1392 | return stderr |
Antoine Pitrou | 1b03f2c | 2010-10-14 11:12:00 +0000 | [diff] [blame] | 1393 | |
| 1394 | def args_from_interpreter_flags(): |
| 1395 | """Return a list of command-line arguments reproducing the current |
| 1396 | settings in sys.flags.""" |
| 1397 | flag_opt_map = { |
| 1398 | 'bytes_warning': 'b', |
| 1399 | 'dont_write_bytecode': 'B', |
| 1400 | 'ignore_environment': 'E', |
| 1401 | 'no_user_site': 's', |
| 1402 | 'no_site': 'S', |
| 1403 | 'optimize': 'O', |
| 1404 | 'verbose': 'v', |
| 1405 | } |
| 1406 | args = [] |
| 1407 | for flag, opt in flag_opt_map.items(): |
| 1408 | v = getattr(sys.flags, flag) |
| 1409 | if v > 0: |
| 1410 | args.append('-' + opt * v) |
| 1411 | return args |
Vinay Sajip | 129fd04 | 2010-12-10 08:19:38 +0000 | [diff] [blame] | 1412 | |
| 1413 | #============================================================ |
| 1414 | # Support for assertions about logging. |
| 1415 | #============================================================ |
| 1416 | |
| 1417 | class TestHandler(logging.handlers.BufferingHandler): |
| 1418 | def __init__(self, matcher): |
| 1419 | # BufferingHandler takes a "capacity" argument |
| 1420 | # so as to know when to flush. As we're overriding |
| 1421 | # shouldFlush anyway, we can set a capacity of zero. |
| 1422 | # You can call flush() manually to clear out the |
| 1423 | # buffer. |
| 1424 | logging.handlers.BufferingHandler.__init__(self, 0) |
| 1425 | self.matcher = matcher |
| 1426 | |
| 1427 | def shouldFlush(self): |
| 1428 | return False |
| 1429 | |
| 1430 | def emit(self, record): |
| 1431 | self.format(record) |
| 1432 | self.buffer.append(record.__dict__) |
| 1433 | |
| 1434 | def matches(self, **kwargs): |
| 1435 | """ |
| 1436 | Look for a saved dict whose keys/values match the supplied arguments. |
| 1437 | """ |
| 1438 | result = False |
| 1439 | for d in self.buffer: |
| 1440 | if self.matcher.matches(d, **kwargs): |
| 1441 | result = True |
| 1442 | break |
| 1443 | return result |
| 1444 | |
| 1445 | class Matcher(object): |
| 1446 | |
| 1447 | _partial_matches = ('msg', 'message') |
| 1448 | |
| 1449 | def matches(self, d, **kwargs): |
| 1450 | """ |
| 1451 | Try to match a single dict with the supplied arguments. |
| 1452 | |
| 1453 | Keys whose values are strings and which are in self._partial_matches |
| 1454 | will be checked for partial (i.e. substring) matches. You can extend |
| 1455 | this scheme to (for example) do regular expression matching, etc. |
| 1456 | """ |
| 1457 | result = True |
| 1458 | for k in kwargs: |
| 1459 | v = kwargs[k] |
| 1460 | dv = d.get(k) |
| 1461 | if not self.match_value(k, dv, v): |
| 1462 | result = False |
| 1463 | break |
| 1464 | return result |
| 1465 | |
| 1466 | def match_value(self, k, dv, v): |
| 1467 | """ |
| 1468 | Try to match a single stored value (dv) with a supplied value (v). |
| 1469 | """ |
| 1470 | if type(v) != type(dv): |
| 1471 | result = False |
| 1472 | elif type(dv) is not str or k not in self._partial_matches: |
| 1473 | result = (v == dv) |
| 1474 | else: |
| 1475 | result = dv.find(v) >= 0 |
| 1476 | return result |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 1477 | |
| 1478 | |
| 1479 | _can_symlink = None |
| 1480 | def can_symlink(): |
| 1481 | global _can_symlink |
| 1482 | if _can_symlink is not None: |
| 1483 | return _can_symlink |
Victor Stinner | 62ec61f | 2011-06-07 12:17:15 +0200 | [diff] [blame] | 1484 | symlink_path = TESTFN + "can_symlink" |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 1485 | try: |
Victor Stinner | 62ec61f | 2011-06-07 12:17:15 +0200 | [diff] [blame] | 1486 | os.symlink(TESTFN, symlink_path) |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 1487 | can = True |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 1488 | except (OSError, NotImplementedError, AttributeError): |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 1489 | can = False |
Victor Stinner | 62ec61f | 2011-06-07 12:17:15 +0200 | [diff] [blame] | 1490 | else: |
| 1491 | os.remove(symlink_path) |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 1492 | _can_symlink = can |
| 1493 | return can |
| 1494 | |
| 1495 | def skip_unless_symlink(test): |
| 1496 | """Skip decorator for tests that require functional symlink""" |
| 1497 | ok = can_symlink() |
| 1498 | msg = "Requires functional symlink implementation" |
| 1499 | return test if ok else unittest.skip(msg)(test) |
Antoine Pitrou | e870623 | 2011-03-15 21:05:36 +0100 | [diff] [blame] | 1500 | |
Antoine Pitrou | 2c50a09 | 2011-03-15 21:02:59 +0100 | [diff] [blame] | 1501 | def patch(test_instance, object_to_patch, attr_name, new_value): |
| 1502 | """Override 'object_to_patch'.'attr_name' with 'new_value'. |
| 1503 | |
| 1504 | Also, add a cleanup procedure to 'test_instance' to restore |
| 1505 | 'object_to_patch' value for 'attr_name'. |
| 1506 | The 'attr_name' should be a valid attribute for 'object_to_patch'. |
| 1507 | |
| 1508 | """ |
| 1509 | # check that 'attr_name' is a real attribute for 'object_to_patch' |
| 1510 | # will raise AttributeError if it does not exist |
| 1511 | getattr(object_to_patch, attr_name) |
| 1512 | |
| 1513 | # keep a copy of the old value |
| 1514 | attr_is_local = False |
| 1515 | try: |
| 1516 | old_value = object_to_patch.__dict__[attr_name] |
| 1517 | except (AttributeError, KeyError): |
| 1518 | old_value = getattr(object_to_patch, attr_name, None) |
| 1519 | else: |
| 1520 | attr_is_local = True |
| 1521 | |
| 1522 | # restore the value when the test is done |
| 1523 | def cleanup(): |
| 1524 | if attr_is_local: |
| 1525 | setattr(object_to_patch, attr_name, old_value) |
| 1526 | else: |
| 1527 | delattr(object_to_patch, attr_name) |
| 1528 | |
| 1529 | test_instance.addCleanup(cleanup) |
| 1530 | |
| 1531 | # actually override the attribute |
| 1532 | setattr(object_to_patch, attr_name, new_value) |