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