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 | 23daade | 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 |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 20 | import imp |
Benjamin Peterson | a6590e8 | 2010-04-11 21:22:10 +0000 | [diff] [blame] | 21 | import time |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 22 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 23 | __all__ = [ |
| 24 | "Error", "TestFailed", "ResourceDenied", "import_module", |
| 25 | "verbose", "use_resources", "max_memuse", "record_original_stdout", |
| 26 | "get_original_stdout", "unload", "unlink", "rmtree", "forget", |
| 27 | "is_resource_enabled", "requires", "find_unused_port", "bind_port", |
| 28 | "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd", |
| 29 | "findfile", "sortdict", "check_syntax_error", "open_urlresource", |
| 30 | "check_warnings", "CleanImport", "EnvironmentVarGuard", |
| 31 | "TransientResource", "captured_output", "captured_stdout", |
| 32 | "time_out", "socket_peer_reset", "ioerror_peer_reset", |
| 33 | "run_with_locale", 'temp_umask', |
| 34 | "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner", |
| 35 | "run_unittest", "run_doctest", "threading_setup", "threading_cleanup", |
| 36 | "reap_children", "cpython_only", "check_impl_detail", "get_attribute", |
| 37 | "swap_item", "swap_attr", |
| 38 | ] |
Benjamin Peterson | 744c2cd | 2008-05-26 16:26:37 +0000 | [diff] [blame] | 39 | |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 40 | |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 41 | class Error(Exception): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 42 | """Base class for regression test exceptions.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 43 | |
| 44 | class TestFailed(Error): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 45 | """Test failed.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 46 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 47 | class ResourceDenied(unittest.SkipTest): |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 48 | """Test skipped because it requested a disallowed resource. |
| 49 | |
| 50 | This is raised when a test calls requires() for a resource that |
| 51 | has not be enabled. It is used to distinguish between expected |
| 52 | and unexpected skips. |
| 53 | """ |
| 54 | |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 55 | @contextlib.contextmanager |
| 56 | def _ignore_deprecated_imports(ignore=True): |
| 57 | """Context manager to suppress package and module deprecation |
| 58 | warnings when importing them. |
| 59 | |
| 60 | If ignore is False, this context manager has no effect.""" |
| 61 | if ignore: |
| 62 | with warnings.catch_warnings(): |
| 63 | warnings.filterwarnings("ignore", ".+ (module|package)", |
| 64 | DeprecationWarning) |
| 65 | yield |
| 66 | else: |
| 67 | yield |
| 68 | |
| 69 | |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 70 | def import_module(name, deprecated=False): |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 71 | """Import and return the module to be tested, raising SkipTest if |
| 72 | it is not available. |
| 73 | |
| 74 | If deprecated is True, any module or package deprecation messages |
| 75 | will be suppressed.""" |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 76 | with _ignore_deprecated_imports(deprecated): |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 77 | try: |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 78 | return importlib.import_module(name) |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 79 | except ImportError as msg: |
| 80 | raise unittest.SkipTest(str(msg)) |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 81 | |
| 82 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 83 | def _save_and_remove_module(name, orig_modules): |
| 84 | """Helper function to save and remove a module from sys.modules |
| 85 | |
| 86 | Return value is True if the module was in sys.modules and |
| 87 | False otherwise.""" |
| 88 | saved = True |
| 89 | try: |
| 90 | orig_modules[name] = sys.modules[name] |
| 91 | except KeyError: |
| 92 | saved = False |
| 93 | else: |
| 94 | del sys.modules[name] |
| 95 | return saved |
| 96 | |
| 97 | |
| 98 | def _save_and_block_module(name, orig_modules): |
| 99 | """Helper function to save and block a module in sys.modules |
| 100 | |
| 101 | Return value is True if the module was in sys.modules and |
| 102 | False otherwise.""" |
| 103 | saved = True |
| 104 | try: |
| 105 | orig_modules[name] = sys.modules[name] |
| 106 | except KeyError: |
| 107 | saved = False |
| 108 | sys.modules[name] = 0 |
| 109 | return saved |
| 110 | |
| 111 | |
| 112 | def import_fresh_module(name, fresh=(), blocked=(), deprecated=False): |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 113 | """Imports and returns a module, deliberately bypassing the sys.modules cache |
| 114 | and importing a fresh copy of the module. Once the import is complete, |
| 115 | the sys.modules cache is restored to its original state. |
| 116 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 117 | Modules named in fresh are also imported anew if needed by the import. |
| 118 | |
| 119 | Importing of modules named in blocked is prevented while the fresh import |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 120 | takes place. |
| 121 | |
| 122 | If deprecated is True, any module or package deprecation messages |
| 123 | will be suppressed.""" |
| 124 | # NOTE: test_heapq and test_warnings include extra sanity checks to make |
| 125 | # sure that this utility function is working as expected |
| 126 | with _ignore_deprecated_imports(deprecated): |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 127 | # Keep track of modules saved for later restoration as well |
| 128 | # as those which just need a blocking entry removed |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 129 | orig_modules = {} |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 130 | names_to_remove = [] |
| 131 | _save_and_remove_module(name, orig_modules) |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 132 | try: |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 133 | for fresh_name in fresh: |
| 134 | _save_and_remove_module(fresh_name, orig_modules) |
| 135 | for blocked_name in blocked: |
| 136 | if not _save_and_block_module(blocked_name, orig_modules): |
| 137 | names_to_remove.append(blocked_name) |
| 138 | fresh_module = importlib.import_module(name) |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 139 | finally: |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 140 | for orig_name, module in orig_modules.items(): |
| 141 | sys.modules[orig_name] = module |
| 142 | for name_to_remove in names_to_remove: |
| 143 | del sys.modules[name_to_remove] |
| 144 | return fresh_module |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 145 | |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 146 | |
R. David Murray | a21e4ca | 2009-03-31 23:16:50 +0000 | [diff] [blame] | 147 | def get_attribute(obj, name): |
| 148 | """Get an attribute, raising SkipTest if AttributeError is raised.""" |
| 149 | try: |
| 150 | attribute = getattr(obj, name) |
| 151 | except AttributeError: |
| 152 | raise unittest.SkipTest("module %s has no attribute %s" % ( |
| 153 | obj.__name__, name)) |
| 154 | else: |
| 155 | return attribute |
| 156 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 157 | verbose = 1 # Flag set to 0 by regrtest.py |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 158 | use_resources = None # Flag set to [] by regrtest.py |
| 159 | max_memuse = 0 # Disable bigmem tests (they will still be run with |
| 160 | # small sizes, to make sure they work.) |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 161 | real_max_memuse = 0 |
Guido van Rossum | 531661c | 1996-12-20 02:58:22 +0000 | [diff] [blame] | 162 | |
Tim Peters | 8dee809 | 2001-09-25 20:05:11 +0000 | [diff] [blame] | 163 | # _original_stdout is meant to hold stdout at the time regrtest began. |
| 164 | # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. |
| 165 | # The point is to have some flavor of stdout the user can actually see. |
| 166 | _original_stdout = None |
| 167 | def record_original_stdout(stdout): |
| 168 | global _original_stdout |
| 169 | _original_stdout = stdout |
| 170 | |
| 171 | def get_original_stdout(): |
| 172 | return _original_stdout or sys.stdout |
| 173 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 174 | def unload(name): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 175 | try: |
| 176 | del sys.modules[name] |
| 177 | except KeyError: |
| 178 | pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 179 | |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 180 | def unlink(filename): |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 181 | try: |
| 182 | os.unlink(filename) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 183 | except OSError as error: |
| 184 | # The filename need not exist. |
| 185 | if error.errno != errno.ENOENT: |
| 186 | raise |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 187 | |
Christian Heimes | 23daade | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 188 | def rmtree(path): |
| 189 | try: |
| 190 | shutil.rmtree(path) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 191 | except OSError as error: |
Christian Heimes | 23daade | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 192 | # Unix returns ENOENT, Windows returns ESRCH. |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 193 | if error.errno not in (errno.ENOENT, errno.ESRCH): |
Christian Heimes | 23daade | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 194 | raise |
| 195 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 196 | def make_legacy_pyc(source): |
| 197 | """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location. |
| 198 | |
| 199 | The choice of .pyc or .pyo extension is done based on the __debug__ flag |
| 200 | value. |
| 201 | |
| 202 | :param source: The file system path to the source file. The source file |
| 203 | does not need to exist, however the PEP 3147 pyc file must exist. |
| 204 | :return: The file system path to the legacy pyc file. |
| 205 | """ |
| 206 | pyc_file = imp.cache_from_source(source) |
| 207 | up_one = os.path.dirname(os.path.abspath(source)) |
| 208 | legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o')) |
| 209 | os.rename(pyc_file, legacy_pyc) |
| 210 | return legacy_pyc |
| 211 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 212 | def forget(modname): |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 213 | """'Forget' a module was ever imported. |
| 214 | |
| 215 | This removes the module from sys.modules and deletes any PEP 3147 or |
| 216 | legacy .pyc and .pyo files. |
| 217 | """ |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 218 | unload(modname) |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 219 | for dirname in sys.path: |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 220 | source = os.path.join(dirname, modname + '.py') |
| 221 | # It doesn't matter if they exist or not, unlink all possible |
| 222 | # combinations of PEP 3147 and legacy pyc and pyo files. |
| 223 | unlink(source + 'c') |
| 224 | unlink(source + 'o') |
| 225 | unlink(imp.cache_from_source(source, debug_override=True)) |
| 226 | unlink(imp.cache_from_source(source, debug_override=False)) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 227 | |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 228 | def is_resource_enabled(resource): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 229 | """Test whether a resource is enabled. Known resources are set by |
| 230 | regrtest.py.""" |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 231 | return use_resources is not None and resource in use_resources |
| 232 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 233 | def requires(resource, msg=None): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 234 | """Raise ResourceDenied if the specified resource is not available. |
| 235 | |
| 236 | If the caller's module is __main__ then automatically return True. The |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 237 | possibility of False being returned occurs when regrtest.py is |
| 238 | executing. |
| 239 | """ |
Skip Montanaro | d839ecd | 2003-04-24 19:06:57 +0000 | [diff] [blame] | 240 | # see if the caller's module is __main__ - if so, treat as if |
| 241 | # the resource was set |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 242 | if sys._getframe(1).f_globals.get("__name__") == "__main__": |
Skip Montanaro | d839ecd | 2003-04-24 19:06:57 +0000 | [diff] [blame] | 243 | return |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 244 | if not is_resource_enabled(resource): |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 245 | if msg is None: |
| 246 | msg = "Use of the `%s' resource not enabled" % resource |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 247 | raise ResourceDenied(msg) |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 248 | |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 249 | HOST = 'localhost' |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 250 | |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 251 | def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): |
| 252 | """Returns an unused port that should be suitable for binding. This is |
| 253 | achieved by creating a temporary socket with the same family and type as |
| 254 | the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to |
| 255 | the specified host address (defaults to 0.0.0.0) with the port set to 0, |
| 256 | eliciting an unused ephemeral port from the OS. The temporary socket is |
| 257 | then closed and deleted, and the ephemeral port is returned. |
| 258 | |
| 259 | Either this method or bind_port() should be used for any tests where a |
| 260 | server socket needs to be bound to a particular port for the duration of |
| 261 | the test. Which one to use depends on whether the calling code is creating |
| 262 | a python socket, or if an unused port needs to be provided in a constructor |
| 263 | or passed to an external program (i.e. the -accept argument to openssl's |
| 264 | s_server mode). Always prefer bind_port() over find_unused_port() where |
| 265 | possible. Hard coded ports should *NEVER* be used. As soon as a server |
| 266 | socket is bound to a hard coded port, the ability to run multiple instances |
| 267 | of the test simultaneously on the same host is compromised, which makes the |
| 268 | test a ticking time bomb in a buildbot environment. On Unix buildbots, this |
| 269 | may simply manifest as a failed test, which can be recovered from without |
| 270 | intervention in most cases, but on Windows, the entire python process can |
| 271 | completely and utterly wedge, requiring someone to log in to the buildbot |
| 272 | and manually kill the affected process. |
| 273 | |
| 274 | (This is easy to reproduce on Windows, unfortunately, and can be traced to |
| 275 | the SO_REUSEADDR socket option having different semantics on Windows versus |
| 276 | Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, |
| 277 | listen and then accept connections on identical host/ports. An EADDRINUSE |
| 278 | socket.error will be raised at some point (depending on the platform and |
| 279 | the order bind and listen were called on each socket). |
| 280 | |
| 281 | However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE |
| 282 | will ever be raised when attempting to bind two identical host/ports. When |
| 283 | accept() is called on each socket, the second caller's process will steal |
| 284 | the port from the first caller, leaving them both in an awkwardly wedged |
| 285 | state where they'll no longer respond to any signals or graceful kills, and |
| 286 | must be forcibly killed via OpenProcess()/TerminateProcess(). |
| 287 | |
| 288 | The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option |
| 289 | instead of SO_REUSEADDR, which effectively affords the same semantics as |
| 290 | SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open |
| 291 | Source world compared to Windows ones, this is a common mistake. A quick |
| 292 | look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when |
| 293 | openssl.exe is called with the 's_server' option, for example. See |
| 294 | http://bugs.python.org/issue2550 for more info. The following site also |
| 295 | has a very thorough description about the implications of both REUSEADDR |
| 296 | and EXCLUSIVEADDRUSE on Windows: |
| 297 | http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) |
| 298 | |
| 299 | XXX: although this approach is a vast improvement on previous attempts to |
| 300 | elicit unused ports, it rests heavily on the assumption that the ephemeral |
| 301 | port returned to us by the OS won't immediately be dished back out to some |
| 302 | other process when we close and delete our temporary socket but before our |
| 303 | calling code has a chance to bind the returned port. We can deal with this |
| 304 | issue if/when we come across it. |
| 305 | """ |
| 306 | |
| 307 | tempsock = socket.socket(family, socktype) |
| 308 | port = bind_port(tempsock) |
| 309 | tempsock.close() |
| 310 | del tempsock |
| 311 | return port |
| 312 | |
| 313 | def bind_port(sock, host=HOST): |
| 314 | """Bind the socket to a free port and return the port number. Relies on |
| 315 | ephemeral ports in order to ensure we are using an unbound port. This is |
| 316 | important as many tests may be running simultaneously, especially in a |
| 317 | buildbot environment. This method raises an exception if the sock.family |
| 318 | is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR |
| 319 | or SO_REUSEPORT set on it. Tests should *never* set these socket options |
| 320 | for TCP/IP sockets. The only case for setting these options is testing |
| 321 | multicasting via multiple UDP sockets. |
| 322 | |
| 323 | Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. |
| 324 | on Windows), it will be set on the socket. This will prevent anyone else |
| 325 | from bind()'ing to our host/port for the duration of the test. |
| 326 | """ |
| 327 | |
| 328 | if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: |
| 329 | if hasattr(socket, 'SO_REUSEADDR'): |
| 330 | if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: |
| 331 | raise TestFailed("tests should never set the SO_REUSEADDR " \ |
| 332 | "socket option on TCP/IP sockets!") |
| 333 | if hasattr(socket, 'SO_REUSEPORT'): |
| 334 | if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: |
| 335 | raise TestFailed("tests should never set the SO_REUSEPORT " \ |
| 336 | "socket option on TCP/IP sockets!") |
| 337 | if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): |
| 338 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) |
| 339 | |
| 340 | sock.bind((host, 0)) |
| 341 | port = sock.getsockname()[1] |
| 342 | return port |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 343 | |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 344 | FUZZ = 1e-6 |
| 345 | |
| 346 | def fcmp(x, y): # fuzzy comparison function |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 347 | if isinstance(x, float) or isinstance(y, float): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 348 | try: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 349 | fuzz = (abs(x) + abs(y)) * FUZZ |
| 350 | if abs(x-y) <= fuzz: |
| 351 | return 0 |
| 352 | except: |
| 353 | pass |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 354 | elif type(x) == type(y) and isinstance(x, (tuple, list)): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 355 | for i in range(min(len(x), len(y))): |
| 356 | outcome = fcmp(x[i], y[i]) |
Fred Drake | 132dce2 | 2000-12-12 23:11:42 +0000 | [diff] [blame] | 357 | if outcome != 0: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 358 | return outcome |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 359 | return (len(x) > len(y)) - (len(x) < len(y)) |
| 360 | return (x > y) - (x < y) |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 361 | |
Finn Bock | 57bc5fa | 2002-11-01 18:02:03 +0000 | [diff] [blame] | 362 | is_jython = sys.platform.startswith('java') |
| 363 | |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 364 | # Filename used for testing |
| 365 | if os.name == 'java': |
| 366 | # Jython disallows @ in module names |
| 367 | TESTFN = '$test' |
Martin v. Löwis | a94568a | 2003-05-10 07:36:56 +0000 | [diff] [blame] | 368 | else: |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 369 | TESTFN = '@test' |
Walter Dörwald | 9b77553 | 2007-06-08 14:30:53 +0000 | [diff] [blame] | 370 | |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 371 | # Disambiguate TESTFN for parallel testing, while letting it remain a valid |
| 372 | # module name. |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 373 | TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid()) |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 374 | |
| 375 | # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() |
| 376 | # TESTFN_UNICODE is a filename that can be encoded using the |
| 377 | # file system encoding, but *not* with the default (ascii) encoding |
| 378 | TESTFN_UNICODE = TESTFN + "-\xe0\xf2" |
| 379 | TESTFN_ENCODING = sys.getfilesystemencoding() |
| 380 | # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be |
| 381 | # able to be encoded by *either* the default or filesystem encoding. |
| 382 | # This test really only makes sense on Windows NT platforms |
| 383 | # which have special Unicode support in posixmodule. |
| 384 | if (not hasattr(sys, "getwindowsversion") or |
| 385 | sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME |
| 386 | TESTFN_UNICODE_UNENCODEABLE = None |
| 387 | else: |
| 388 | # Japanese characters (I think - from bug 846133) |
| 389 | TESTFN_UNICODE_UNENCODEABLE = TESTFN + "-\u5171\u6709\u3055\u308c\u308b" |
| 390 | try: |
| 391 | # XXX - Note - should be using TESTFN_ENCODING here - but for |
| 392 | # Windows, "mbcs" currently always operates as if in |
| 393 | # errors=ignore' mode - hence we get '?' characters rather than |
| 394 | # the exception. 'Latin1' operates as we expect - ie, fails. |
| 395 | # See [ 850997 ] mbcs encoding ignores errors |
| 396 | TESTFN_UNICODE_UNENCODEABLE.encode("Latin1") |
| 397 | except UnicodeEncodeError: |
| 398 | pass |
Walter Dörwald | 9b77553 | 2007-06-08 14:30:53 +0000 | [diff] [blame] | 399 | else: |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 400 | print('WARNING: The filename %r CAN be encoded by the filesystem. ' |
| 401 | 'Unicode filename tests may not be effective' |
| 402 | % TESTFN_UNICODE_UNENCODEABLE) |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 403 | |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 404 | # Save the initial cwd |
| 405 | SAVEDCWD = os.getcwd() |
| 406 | |
| 407 | @contextlib.contextmanager |
| 408 | def temp_cwd(name='tempcwd', quiet=False): |
| 409 | """ |
| 410 | Context manager that creates a temporary directory and set it as CWD. |
| 411 | |
| 412 | The new CWD is created in the current directory and it's named *name*. |
| 413 | If *quiet* is False (default) and it's not possible to create or change |
| 414 | the CWD, an error is raised. If it's True, only a warning is raised |
| 415 | and the original CWD is used. |
| 416 | """ |
| 417 | saved_dir = os.getcwd() |
| 418 | is_temporary = False |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 419 | try: |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 420 | os.mkdir(name) |
| 421 | os.chdir(name) |
| 422 | is_temporary = True |
| 423 | except OSError: |
| 424 | if not quiet: |
| 425 | raise |
| 426 | warnings.warn('tests may fail, unable to change the CWD to ' + name, |
| 427 | RuntimeWarning, stacklevel=3) |
| 428 | try: |
| 429 | yield os.getcwd() |
| 430 | finally: |
| 431 | os.chdir(saved_dir) |
| 432 | if is_temporary: |
| 433 | rmtree(name) |
| 434 | |
Guido van Rossum | a8f7e59 | 2001-03-13 09:31:07 +0000 | [diff] [blame] | 435 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame^] | 436 | @contextlib.contextmanager |
| 437 | def temp_umask(umask): |
| 438 | """Context manager that temporarily sets the process umask.""" |
| 439 | oldmask = os.umask(umask) |
| 440 | try: |
| 441 | yield |
| 442 | finally: |
| 443 | os.umask(oldmask) |
| 444 | |
| 445 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 446 | def findfile(file, here=__file__, subdir=None): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 447 | """Try to find a file on sys.path and the working directory. If it is not |
| 448 | found the argument passed to the function is returned (this does not |
| 449 | necessarily signal failure; could still be the legitimate path).""" |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 450 | if os.path.isabs(file): |
| 451 | return file |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 452 | if subdir is not None: |
| 453 | file = os.path.join(subdir, file) |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 454 | path = sys.path |
| 455 | path = [os.path.dirname(here)] + path |
| 456 | for dn in path: |
| 457 | fn = os.path.join(dn, file) |
| 458 | if os.path.exists(fn): return fn |
| 459 | return file |
Marc-André Lemburg | 3661908 | 2001-01-17 19:11:13 +0000 | [diff] [blame] | 460 | |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 461 | def sortdict(dict): |
| 462 | "Like repr(dict), but in sorted order." |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 463 | items = sorted(dict.items()) |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 464 | reprpairs = ["%r: %r" % pair for pair in items] |
| 465 | withcommas = ", ".join(reprpairs) |
| 466 | return "{%s}" % withcommas |
| 467 | |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 468 | def make_bad_fd(): |
| 469 | """ |
| 470 | Create an invalid file descriptor by opening and closing a file and return |
| 471 | its fd. |
| 472 | """ |
| 473 | file = open(TESTFN, "wb") |
| 474 | try: |
| 475 | return file.fileno() |
| 476 | finally: |
| 477 | file.close() |
| 478 | unlink(TESTFN) |
| 479 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 480 | def check_syntax_error(testcase, statement): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 481 | testcase.assertRaises(SyntaxError, compile, statement, |
| 482 | '<test string>', 'exec') |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 483 | |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 484 | def open_urlresource(url, *args, **kw): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 485 | import urllib.request, urllib.parse |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 486 | |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 487 | check = kw.pop('check', None) |
| 488 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 489 | filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL! |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 490 | |
Alexandre Vassalotti | 711ed4a | 2009-07-17 10:42:05 +0000 | [diff] [blame] | 491 | fn = os.path.join(os.path.dirname(__file__), "data", filename) |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 492 | |
| 493 | def check_valid_file(fn): |
| 494 | f = open(fn, *args, **kw) |
| 495 | if check is None: |
| 496 | return f |
| 497 | elif check(f): |
| 498 | f.seek(0) |
| 499 | return f |
| 500 | f.close() |
| 501 | |
Alexandre Vassalotti | 711ed4a | 2009-07-17 10:42:05 +0000 | [diff] [blame] | 502 | if os.path.exists(fn): |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 503 | f = check_valid_file(fn) |
| 504 | if f is not None: |
| 505 | return f |
| 506 | unlink(fn) |
| 507 | |
| 508 | # Verify the requirement before downloading the file |
| 509 | requires('urlfetch') |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 510 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 511 | print('\tfetching %s ...' % url, file=get_original_stdout()) |
Antoine Pitrou | fd0680b | 2009-11-01 22:13:48 +0000 | [diff] [blame] | 512 | f = urllib.request.urlopen(url, timeout=15) |
| 513 | try: |
| 514 | with open(fn, "wb") as out: |
| 515 | s = f.read() |
| 516 | while s: |
| 517 | out.write(s) |
| 518 | s = f.read() |
| 519 | finally: |
| 520 | f.close() |
Florent Xicluna | f089fd6 | 2010-03-19 14:25:03 +0000 | [diff] [blame] | 521 | |
| 522 | f = check_valid_file(fn) |
| 523 | if f is not None: |
| 524 | return f |
| 525 | raise TestFailed('invalid resource "%s"' % fn) |
| 526 | |
Thomas Wouters | 9fe394c | 2007-02-05 01:24:16 +0000 | [diff] [blame] | 527 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 528 | class WarningsRecorder(object): |
| 529 | """Convenience wrapper for the warnings list returned on |
| 530 | entry to the warnings.catch_warnings() context manager. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 531 | """ |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 532 | def __init__(self, warnings_list): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 533 | self._warnings = warnings_list |
| 534 | self._last = 0 |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 535 | |
| 536 | def __getattr__(self, attr): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 537 | if len(self._warnings) > self._last: |
| 538 | return getattr(self._warnings[-1], attr) |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 539 | elif attr in warnings.WarningMessage._WARNING_DETAILS: |
| 540 | return None |
| 541 | raise AttributeError("%r has no attribute %r" % (self, attr)) |
| 542 | |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 543 | @property |
| 544 | def warnings(self): |
| 545 | return self._warnings[self._last:] |
| 546 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 547 | def reset(self): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 548 | self._last = len(self._warnings) |
| 549 | |
| 550 | |
| 551 | def _filterwarnings(filters, quiet=False): |
| 552 | """Catch the warnings, then check if all the expected |
| 553 | warnings have been raised and re-raise unexpected warnings. |
| 554 | If 'quiet' is True, only re-raise the unexpected warnings. |
| 555 | """ |
| 556 | # Clear the warning registry of the calling module |
| 557 | # in order to re-raise the warnings. |
| 558 | frame = sys._getframe(2) |
| 559 | registry = frame.f_globals.get('__warningregistry__') |
| 560 | if registry: |
| 561 | registry.clear() |
| 562 | with warnings.catch_warnings(record=True) as w: |
| 563 | # Set filter "always" to record all warnings. Because |
| 564 | # test_warnings swap the module, we need to look up in |
| 565 | # the sys.modules dictionary. |
| 566 | sys.modules['warnings'].simplefilter("always") |
| 567 | yield WarningsRecorder(w) |
| 568 | # Filter the recorded warnings |
| 569 | reraise = [warning.message for warning in w] |
| 570 | missing = [] |
| 571 | for msg, cat in filters: |
| 572 | seen = False |
| 573 | for exc in reraise[:]: |
| 574 | message = str(exc) |
| 575 | # Filter out the matching messages |
| 576 | if (re.match(msg, message, re.I) and |
| 577 | issubclass(exc.__class__, cat)): |
| 578 | seen = True |
| 579 | reraise.remove(exc) |
| 580 | if not seen and not quiet: |
| 581 | # This filter caught nothing |
| 582 | missing.append((msg, cat.__name__)) |
| 583 | if reraise: |
| 584 | raise AssertionError("unhandled warning %r" % reraise[0]) |
| 585 | if missing: |
| 586 | raise AssertionError("filter (%r, %s) did not catch any warning" % |
| 587 | missing[0]) |
| 588 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 589 | |
| 590 | @contextlib.contextmanager |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 591 | def check_warnings(*filters, **kwargs): |
| 592 | """Context manager to silence warnings. |
| 593 | |
| 594 | Accept 2-tuples as positional arguments: |
| 595 | ("message regexp", WarningCategory) |
| 596 | |
| 597 | Optional argument: |
| 598 | - if 'quiet' is True, it does not fail if a filter catches nothing |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 599 | (default True without argument, |
| 600 | default False if some filters are defined) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 601 | |
| 602 | Without argument, it defaults to: |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 603 | check_warnings(("", Warning), quiet=True) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 604 | """ |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 605 | quiet = kwargs.get('quiet') |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 606 | if not filters: |
| 607 | filters = (("", Warning),) |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 608 | # Preserve backward compatibility |
| 609 | if quiet is None: |
| 610 | quiet = True |
| 611 | return _filterwarnings(filters, quiet) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 612 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 613 | |
| 614 | class CleanImport(object): |
| 615 | """Context manager to force import to return a new module reference. |
| 616 | |
| 617 | This is useful for testing module-level behaviours, such as |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 618 | the emission of a DeprecationWarning on import. |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 619 | |
| 620 | Use like this: |
| 621 | |
| 622 | with CleanImport("foo"): |
Brett Cannon | ddb5e70 | 2010-02-03 22:16:11 +0000 | [diff] [blame] | 623 | importlib.import_module("foo") # new reference |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 624 | """ |
| 625 | |
| 626 | def __init__(self, *module_names): |
| 627 | self.original_modules = sys.modules.copy() |
| 628 | for module_name in module_names: |
| 629 | if module_name in sys.modules: |
| 630 | module = sys.modules[module_name] |
| 631 | # It is possible that module_name is just an alias for |
| 632 | # another module (e.g. stub for modules renamed in 3.x). |
| 633 | # In that case, we also need delete the real module to clear |
| 634 | # the import cache. |
| 635 | if module.__name__ != module_name: |
| 636 | del sys.modules[module.__name__] |
| 637 | del sys.modules[module_name] |
| 638 | |
| 639 | def __enter__(self): |
| 640 | return self |
| 641 | |
| 642 | def __exit__(self, *ignore_exc): |
| 643 | sys.modules.update(self.original_modules) |
| 644 | |
| 645 | |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 646 | class EnvironmentVarGuard(collections.MutableMapping): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 647 | |
| 648 | """Class to help protect the environment variable properly. Can be used as |
| 649 | a context manager.""" |
| 650 | |
| 651 | def __init__(self): |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 652 | self._environ = os.environ |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 653 | self._changed = {} |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 654 | |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 655 | def __getitem__(self, envvar): |
| 656 | return self._environ[envvar] |
| 657 | |
| 658 | def __setitem__(self, envvar, value): |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 659 | # Remember the initial value on the first access |
| 660 | if envvar not in self._changed: |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 661 | self._changed[envvar] = self._environ.get(envvar) |
| 662 | self._environ[envvar] = value |
| 663 | |
| 664 | def __delitem__(self, envvar): |
| 665 | # Remember the initial value on the first access |
| 666 | if envvar not in self._changed: |
| 667 | self._changed[envvar] = self._environ.get(envvar) |
| 668 | if envvar in self._environ: |
| 669 | del self._environ[envvar] |
| 670 | |
| 671 | def keys(self): |
| 672 | return self._environ.keys() |
| 673 | |
| 674 | def __iter__(self): |
| 675 | return iter(self._environ) |
| 676 | |
| 677 | def __len__(self): |
| 678 | return len(self._environ) |
| 679 | |
| 680 | def set(self, envvar, value): |
| 681 | self[envvar] = value |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 682 | |
| 683 | def unset(self, envvar): |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 684 | del self[envvar] |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 685 | |
| 686 | def __enter__(self): |
| 687 | return self |
| 688 | |
| 689 | def __exit__(self, *ignore_exc): |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 690 | for (k, v) in self._changed.items(): |
| 691 | if v is None: |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 692 | if k in self._environ: |
| 693 | del self._environ[k] |
Walter Dörwald | 4ba8013 | 2009-04-25 12:48:43 +0000 | [diff] [blame] | 694 | else: |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 695 | self._environ[k] = v |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 696 | os.environ = self._environ |
| 697 | |
| 698 | |
| 699 | class DirsOnSysPath(object): |
| 700 | """Context manager to temporarily add directories to sys.path. |
| 701 | |
| 702 | This makes a copy of sys.path, appends any directories given |
| 703 | as positional arguments, then reverts sys.path to the copied |
| 704 | settings when the context ends. |
| 705 | |
| 706 | Note that *all* sys.path modifications in the body of the |
| 707 | context manager, including replacement of the object, |
| 708 | will be reverted at the end of the block. |
| 709 | """ |
| 710 | |
| 711 | def __init__(self, *paths): |
| 712 | self.original_value = sys.path[:] |
| 713 | self.original_object = sys.path |
| 714 | sys.path.extend(paths) |
| 715 | |
| 716 | def __enter__(self): |
| 717 | return self |
| 718 | |
| 719 | def __exit__(self, *ignore_exc): |
| 720 | sys.path = self.original_object |
| 721 | sys.path[:] = self.original_value |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 722 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 723 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 724 | class TransientResource(object): |
| 725 | |
| 726 | """Raise ResourceDenied if an exception is raised while the context manager |
| 727 | is in effect that matches the specified exception and attributes.""" |
| 728 | |
| 729 | def __init__(self, exc, **kwargs): |
| 730 | self.exc = exc |
| 731 | self.attrs = kwargs |
| 732 | |
| 733 | def __enter__(self): |
| 734 | return self |
| 735 | |
| 736 | def __exit__(self, type_=None, value=None, traceback=None): |
| 737 | """If type_ is a subclass of self.exc and value has attributes matching |
| 738 | self.attrs, raise ResourceDenied. Otherwise let the exception |
| 739 | propagate (if any).""" |
| 740 | if type_ is not None and issubclass(self.exc, type_): |
| 741 | for attr, attr_value in self.attrs.items(): |
| 742 | if not hasattr(value, attr): |
| 743 | break |
| 744 | if getattr(value, attr) != attr_value: |
| 745 | break |
| 746 | else: |
| 747 | raise ResourceDenied("an optional resource is not available") |
| 748 | |
| 749 | |
Raymond Hettinger | 686057b | 2009-06-04 00:11:54 +0000 | [diff] [blame] | 750 | # Context managers that raise ResourceDenied when various issues |
| 751 | # with the Internet connection manifest themselves as exceptions. |
| 752 | time_out = TransientResource(IOError, errno=errno.ETIMEDOUT) |
| 753 | socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET) |
| 754 | ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 755 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 756 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 757 | @contextlib.contextmanager |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 758 | def captured_output(stream_name): |
| 759 | """Run the 'with' statement body using a StringIO object in place of a |
| 760 | specific attribute on the sys module. |
| 761 | Example use (with 'stream_name=stdout'):: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 762 | |
| 763 | with captured_stdout() as s: |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 764 | print("hello") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 765 | assert s.getvalue() == "hello" |
| 766 | """ |
| 767 | import io |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 768 | orig_stdout = getattr(sys, stream_name) |
| 769 | setattr(sys, stream_name, io.StringIO()) |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 770 | try: |
| 771 | yield getattr(sys, stream_name) |
| 772 | finally: |
| 773 | setattr(sys, stream_name, orig_stdout) |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 774 | |
| 775 | def captured_stdout(): |
| 776 | return captured_output("stdout") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 777 | |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 778 | def captured_stdin(): |
| 779 | return captured_output("stdin") |
| 780 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 781 | def gc_collect(): |
| 782 | """Force as many objects as possible to be collected. |
| 783 | |
| 784 | In non-CPython implementations of Python, this is needed because timely |
| 785 | deallocation is not guaranteed by the garbage collector. (Even in CPython |
| 786 | this can be the case in case of reference cycles.) This means that __del__ |
| 787 | methods may be called later than expected and weakrefs may remain alive for |
| 788 | longer than expected. This function tries its best to force all garbage |
| 789 | objects to disappear. |
| 790 | """ |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 791 | gc.collect() |
Benjamin Peterson | a6590e8 | 2010-04-11 21:22:10 +0000 | [diff] [blame] | 792 | if is_jython: |
| 793 | time.sleep(0.1) |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 794 | gc.collect() |
| 795 | gc.collect() |
| 796 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 797 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 798 | #======================================================================= |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 799 | # Decorator for running a function in a different locale, correctly resetting |
| 800 | # it afterwards. |
| 801 | |
| 802 | def run_with_locale(catstr, *locales): |
| 803 | def decorator(func): |
| 804 | def inner(*args, **kwds): |
| 805 | try: |
| 806 | import locale |
| 807 | category = getattr(locale, catstr) |
| 808 | orig_locale = locale.setlocale(category) |
| 809 | except AttributeError: |
| 810 | # if the test author gives us an invalid category string |
| 811 | raise |
| 812 | except: |
| 813 | # cannot retrieve original locale, so do nothing |
| 814 | locale = orig_locale = None |
| 815 | else: |
| 816 | for loc in locales: |
| 817 | try: |
| 818 | locale.setlocale(category, loc) |
| 819 | break |
| 820 | except: |
| 821 | pass |
| 822 | |
| 823 | # now run the function, resetting the locale on exceptions |
| 824 | try: |
| 825 | return func(*args, **kwds) |
| 826 | finally: |
| 827 | if locale and orig_locale: |
| 828 | locale.setlocale(category, orig_locale) |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 829 | inner.__name__ = func.__name__ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 830 | inner.__doc__ = func.__doc__ |
| 831 | return inner |
| 832 | return decorator |
| 833 | |
| 834 | #======================================================================= |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 835 | # Big-memory-test support. Separate from 'resources' because memory use |
| 836 | # should be configurable. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 837 | |
| 838 | # Some handy shorthands. Note that these are used for byte-limits as well |
| 839 | # as size-limits, in the various bigmem tests |
| 840 | _1M = 1024*1024 |
| 841 | _1G = 1024 * _1M |
| 842 | _2G = 2 * _1G |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 843 | _4G = 4 * _1G |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 844 | |
Thomas Wouters | d2cf20e | 2007-08-30 22:57:53 +0000 | [diff] [blame] | 845 | MAX_Py_ssize_t = sys.maxsize |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 846 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 847 | def set_memlimit(limit): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 848 | global max_memuse |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 849 | global real_max_memuse |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 850 | sizes = { |
| 851 | 'k': 1024, |
| 852 | 'm': _1M, |
| 853 | 'g': _1G, |
| 854 | 't': 1024*_1G, |
| 855 | } |
| 856 | m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit, |
| 857 | re.IGNORECASE | re.VERBOSE) |
| 858 | if m is None: |
| 859 | raise ValueError('Invalid memory limit %r' % (limit,)) |
| 860 | memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()]) |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 861 | real_max_memuse = memlimit |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 862 | if memlimit > MAX_Py_ssize_t: |
| 863 | memlimit = MAX_Py_ssize_t |
| 864 | if memlimit < _2G - 1: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 865 | raise ValueError('Memory limit %r too low to be useful' % (limit,)) |
| 866 | max_memuse = memlimit |
| 867 | |
| 868 | def bigmemtest(minsize, memuse, overhead=5*_1M): |
| 869 | """Decorator for bigmem tests. |
| 870 | |
| 871 | 'minsize' is the minimum useful size for the test (in arbitrary, |
| 872 | test-interpreted units.) 'memuse' is the number of 'bytes per size' for |
| 873 | the test, or a good estimate of it. 'overhead' specifies fixed overhead, |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 874 | independent of the testsize, and defaults to 5Mb. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 875 | |
| 876 | The decorator tries to guess a good value for 'size' and passes it to |
| 877 | the decorated test function. If minsize * memuse is more than the |
| 878 | allowed memory use (as defined by max_memuse), the test is skipped. |
| 879 | Otherwise, minsize is adjusted upward to use up to max_memuse. |
| 880 | """ |
| 881 | def decorator(f): |
| 882 | def wrapper(self): |
Antoine Pitrou | 7cdb495 | 2009-03-07 23:40:49 +0000 | [diff] [blame] | 883 | # Retrieve values in case someone decided to adjust them |
| 884 | minsize = wrapper.minsize |
| 885 | memuse = wrapper.memuse |
| 886 | overhead = wrapper.overhead |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 887 | if not max_memuse: |
| 888 | # If max_memuse is 0 (the default), |
| 889 | # we still want to run the tests with size set to a few kb, |
| 890 | # to make sure they work. We still want to avoid using |
| 891 | # too much memory, though, but we do that noisily. |
| 892 | maxsize = 5147 |
Benjamin Peterson | 46d4440 | 2009-07-01 00:45:43 +0000 | [diff] [blame] | 893 | self.assertFalse(maxsize * memuse + overhead > 20 * _1M) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 894 | else: |
| 895 | maxsize = int((max_memuse - overhead) / memuse) |
| 896 | if maxsize < minsize: |
| 897 | # Really ought to print 'test skipped' or something |
| 898 | if verbose: |
| 899 | sys.stderr.write("Skipping %s because of memory " |
| 900 | "constraint\n" % (f.__name__,)) |
| 901 | return |
| 902 | # Try to keep some breathing room in memory use |
| 903 | maxsize = max(maxsize - 50 * _1M, minsize) |
| 904 | return f(self, maxsize) |
| 905 | wrapper.minsize = minsize |
| 906 | wrapper.memuse = memuse |
| 907 | wrapper.overhead = overhead |
| 908 | return wrapper |
| 909 | return decorator |
| 910 | |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 911 | def precisionbigmemtest(size, memuse, overhead=5*_1M): |
| 912 | def decorator(f): |
| 913 | def wrapper(self): |
Antoine Pitrou | 7cdb495 | 2009-03-07 23:40:49 +0000 | [diff] [blame] | 914 | size = wrapper.size |
| 915 | memuse = wrapper.memuse |
| 916 | overhead = wrapper.overhead |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 917 | if not real_max_memuse: |
| 918 | maxsize = 5147 |
| 919 | else: |
| 920 | maxsize = size |
| 921 | |
| 922 | if real_max_memuse and real_max_memuse < maxsize * memuse: |
| 923 | if verbose: |
| 924 | sys.stderr.write("Skipping %s because of memory " |
| 925 | "constraint\n" % (f.__name__,)) |
| 926 | return |
| 927 | |
| 928 | return f(self, maxsize) |
| 929 | wrapper.size = size |
| 930 | wrapper.memuse = memuse |
| 931 | wrapper.overhead = overhead |
| 932 | return wrapper |
| 933 | return decorator |
| 934 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 935 | def bigaddrspacetest(f): |
| 936 | """Decorator for tests that fill the address space.""" |
| 937 | def wrapper(self): |
| 938 | if max_memuse < MAX_Py_ssize_t: |
| 939 | if verbose: |
| 940 | sys.stderr.write("Skipping %s because of memory " |
| 941 | "constraint\n" % (f.__name__,)) |
| 942 | else: |
| 943 | return f(self) |
| 944 | return wrapper |
| 945 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 946 | #======================================================================= |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 947 | # unittest integration. |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 948 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 949 | class BasicTestRunner: |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 950 | def run(self, test): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 951 | result = unittest.TestResult() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 952 | test(result) |
| 953 | return result |
| 954 | |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 955 | def _id(obj): |
| 956 | return obj |
| 957 | |
| 958 | def requires_resource(resource): |
| 959 | if resource_is_enabled(resource): |
| 960 | return _id |
| 961 | else: |
| 962 | return unittest.skip("resource {0!r} is not enabled".format(resource)) |
| 963 | |
| 964 | def cpython_only(test): |
| 965 | """ |
| 966 | Decorator for tests only applicable on CPython. |
| 967 | """ |
| 968 | return impl_detail(cpython=True)(test) |
| 969 | |
| 970 | def impl_detail(msg=None, **guards): |
| 971 | if check_impl_detail(**guards): |
| 972 | return _id |
| 973 | if msg is None: |
| 974 | guardnames, default = _parse_guards(guards) |
| 975 | if default: |
| 976 | msg = "implementation detail not available on {0}" |
| 977 | else: |
| 978 | msg = "implementation detail specific to {0}" |
| 979 | guardnames = sorted(guardnames.keys()) |
| 980 | msg = msg.format(' or '.join(guardnames)) |
| 981 | return unittest.skip(msg) |
| 982 | |
| 983 | def _parse_guards(guards): |
| 984 | # Returns a tuple ({platform_name: run_me}, default_value) |
| 985 | if not guards: |
| 986 | return ({'cpython': True}, False) |
Eric Smith | 886b40a | 2009-04-26 21:26:45 +0000 | [diff] [blame] | 987 | is_true = list(guards.values())[0] |
| 988 | 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] | 989 | return (guards, not is_true) |
| 990 | |
| 991 | # Use the following check to guard CPython's implementation-specific tests -- |
| 992 | # or to run them only on the implementation(s) guarded by the arguments. |
| 993 | def check_impl_detail(**guards): |
| 994 | """This function returns True or False depending on the host platform. |
| 995 | Examples: |
| 996 | if check_impl_detail(): # only on CPython (default) |
| 997 | if check_impl_detail(jython=True): # only on Jython |
| 998 | if check_impl_detail(cpython=False): # everywhere except on CPython |
| 999 | """ |
| 1000 | guards, default = _parse_guards(guards) |
| 1001 | return guards.get(platform.python_implementation().lower(), default) |
| 1002 | |
| 1003 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1004 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1005 | def _run_suite(suite): |
Barry Warsaw | c88425e | 2001-09-20 06:31:22 +0000 | [diff] [blame] | 1006 | """Run tests from a unittest.TestSuite-derived class.""" |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1007 | if verbose: |
Fred Drake | 84a5934 | 2001-03-23 04:21:17 +0000 | [diff] [blame] | 1008 | runner = unittest.TextTestRunner(sys.stdout, verbosity=2) |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1009 | else: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1010 | runner = BasicTestRunner() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 1011 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1012 | result = runner.run(suite) |
| 1013 | if not result.wasSuccessful(): |
Fred Drake | 14f6c18 | 2001-07-16 18:51:32 +0000 | [diff] [blame] | 1014 | if len(result.errors) == 1 and not result.failures: |
| 1015 | err = result.errors[0][1] |
| 1016 | elif len(result.failures) == 1 and not result.errors: |
| 1017 | err = result.failures[0][1] |
| 1018 | else: |
R. David Murray | 723357e | 2009-10-19 18:06:17 +0000 | [diff] [blame] | 1019 | err = "multiple errors occurred" |
| 1020 | if not verbose: err += "; run in verbose mode for details" |
Tim Peters | 2d84f2c | 2001-09-08 03:37:56 +0000 | [diff] [blame] | 1021 | raise TestFailed(err) |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1022 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 1023 | |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1024 | def run_unittest(*classes): |
| 1025 | """Run tests from unittest.TestCase-derived classes.""" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1026 | valid_types = (unittest.TestSuite, unittest.TestCase) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 1027 | suite = unittest.TestSuite() |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1028 | for cls in classes: |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1029 | if isinstance(cls, str): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1030 | if cls in sys.modules: |
| 1031 | suite.addTest(unittest.findTestCases(sys.modules[cls])) |
| 1032 | else: |
| 1033 | raise ValueError("str arguments must be keys in sys.modules") |
| 1034 | elif isinstance(cls, valid_types): |
Raymond Hettinger | 21d9987 | 2003-07-16 02:59:32 +0000 | [diff] [blame] | 1035 | suite.addTest(cls) |
| 1036 | else: |
| 1037 | suite.addTest(unittest.makeSuite(cls)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1038 | _run_suite(suite) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 1039 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 1040 | |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1041 | #======================================================================= |
| 1042 | # doctest driver. |
| 1043 | |
| 1044 | def run_doctest(module, verbosity=None): |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 1045 | """Run doctest on the given module. Return (#failures, #tests). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1046 | |
| 1047 | If optional argument verbosity is not specified (or is None), pass |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1048 | support's belief about verbosity on to doctest. Else doctest's |
Tim Peters | bea3fb8 | 2001-09-10 01:39:21 +0000 | [diff] [blame] | 1049 | usual behavior is used (it searches sys.argv for -v). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1050 | """ |
| 1051 | |
| 1052 | import doctest |
| 1053 | |
| 1054 | if verbosity is None: |
| 1055 | verbosity = verbose |
| 1056 | else: |
| 1057 | verbosity = None |
| 1058 | |
Tim Peters | 342ca75 | 2001-09-25 19:13:20 +0000 | [diff] [blame] | 1059 | # Direct doctest output (normally just errors) to real stdout; doctest |
| 1060 | # output shouldn't be compared by regrtest. |
| 1061 | save_stdout = sys.stdout |
Tim Peters | 8dee809 | 2001-09-25 20:05:11 +0000 | [diff] [blame] | 1062 | sys.stdout = get_original_stdout() |
Tim Peters | 342ca75 | 2001-09-25 19:13:20 +0000 | [diff] [blame] | 1063 | try: |
| 1064 | f, t = doctest.testmod(module, verbose=verbosity) |
| 1065 | if f: |
| 1066 | raise TestFailed("%d of %d doctests failed" % (f, t)) |
| 1067 | finally: |
| 1068 | sys.stdout = save_stdout |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 1069 | if verbose: |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 1070 | print('doctest (%s) ... %d tests with zero failures' % |
| 1071 | (module.__name__, t)) |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 1072 | return f, t |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1073 | |
Antoine Pitrou | 060cee2 | 2009-11-13 16:29:04 +0000 | [diff] [blame] | 1074 | |
| 1075 | #======================================================================= |
| 1076 | # Support for saving and restoring the imported modules. |
| 1077 | |
| 1078 | def modules_setup(): |
| 1079 | return sys.modules.copy(), |
| 1080 | |
| 1081 | def modules_cleanup(oldmodules): |
| 1082 | # Encoders/decoders are registered permanently within the internal |
| 1083 | # codec cache. If we destroy the corresponding modules their |
| 1084 | # globals will be set to None which will trip up the cached functions. |
| 1085 | encodings = [(k, v) for k, v in sys.modules.items() |
| 1086 | if k.startswith('encodings.')] |
| 1087 | sys.modules.clear() |
| 1088 | sys.modules.update(encodings) |
| 1089 | sys.modules.update(oldmodules) |
| 1090 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1091 | #======================================================================= |
| 1092 | # Threading support to prevent reporting refleaks when running regrtest.py -R |
| 1093 | |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1094 | # NOTE: we use thread._count() rather than threading.enumerate() (or the |
| 1095 | # moral equivalent thereof) because a threading.Thread object is still alive |
| 1096 | # until its __bootstrap() method has returned, even after it has been |
| 1097 | # unregistered from the threading module. |
| 1098 | # thread._count(), on the other hand, only gets decremented *after* the |
| 1099 | # __bootstrap() method has returned, which gives us reliable reference counts |
| 1100 | # at the end of a test run. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1101 | |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1102 | def threading_setup(): |
| 1103 | import _thread |
| 1104 | return _thread._count(), |
| 1105 | |
| 1106 | def threading_cleanup(nb_threads): |
| 1107 | import _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1108 | |
| 1109 | _MAX_COUNT = 10 |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1110 | for count in range(_MAX_COUNT): |
| 1111 | n = _thread._count() |
| 1112 | if n == nb_threads: |
| 1113 | break |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1114 | time.sleep(0.1) |
Antoine Pitrou | 65c9c64 | 2009-10-30 17:25:12 +0000 | [diff] [blame] | 1115 | # XXX print a warning in case of failure? |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1116 | |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 1117 | def reap_threads(func): |
| 1118 | @functools.wraps(func) |
| 1119 | def decorator(*args): |
| 1120 | key = threading_setup() |
| 1121 | try: |
| 1122 | return func(*args) |
| 1123 | finally: |
| 1124 | threading_cleanup(*key) |
| 1125 | return decorator |
| 1126 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1127 | def reap_children(): |
| 1128 | """Use this function at the end of test_main() whenever sub-processes |
| 1129 | are started. This will help ensure that no extra children (zombies) |
| 1130 | stick around to hog resources and create problems when looking |
| 1131 | for refleaks. |
| 1132 | """ |
| 1133 | |
| 1134 | # Reap all our dead child processes so we don't leave zombies around. |
| 1135 | # 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] | 1136 | if hasattr(os, 'waitpid'): |
| 1137 | any_process = -1 |
| 1138 | while True: |
| 1139 | try: |
| 1140 | # This will raise an exception on Windows. That's ok. |
| 1141 | pid, status = os.waitpid(any_process, os.WNOHANG) |
| 1142 | if pid == 0: |
| 1143 | break |
| 1144 | except: |
| 1145 | break |
Collin Winter | f2bf2b3 | 2010-03-17 00:41:56 +0000 | [diff] [blame] | 1146 | |
| 1147 | @contextlib.contextmanager |
| 1148 | def swap_attr(obj, attr, new_val): |
| 1149 | """Temporary swap out an attribute with a new object. |
| 1150 | |
| 1151 | Usage: |
| 1152 | with swap_attr(obj, "attr", 5): |
| 1153 | ... |
| 1154 | |
| 1155 | This will set obj.attr to 5 for the duration of the with: block, |
| 1156 | restoring the old value at the end of the block. If `attr` doesn't |
| 1157 | exist on `obj`, it will be created and then deleted at the end of the |
| 1158 | block. |
| 1159 | """ |
| 1160 | if hasattr(obj, attr): |
| 1161 | real_val = getattr(obj, attr) |
| 1162 | setattr(obj, attr, new_val) |
| 1163 | try: |
| 1164 | yield |
| 1165 | finally: |
| 1166 | setattr(obj, attr, real_val) |
| 1167 | else: |
| 1168 | setattr(obj, attr, new_val) |
| 1169 | try: |
| 1170 | yield |
| 1171 | finally: |
| 1172 | delattr(obj, attr) |
| 1173 | |
| 1174 | @contextlib.contextmanager |
| 1175 | def swap_item(obj, item, new_val): |
| 1176 | """Temporary swap out an item with a new object. |
| 1177 | |
| 1178 | Usage: |
| 1179 | with swap_item(obj, "item", 5): |
| 1180 | ... |
| 1181 | |
| 1182 | This will set obj["item"] to 5 for the duration of the with: block, |
| 1183 | restoring the old value at the end of the block. If `item` doesn't |
| 1184 | exist on `obj`, it will be created and then deleted at the end of the |
| 1185 | block. |
| 1186 | """ |
| 1187 | if item in obj: |
| 1188 | real_val = obj[item] |
| 1189 | obj[item] = new_val |
| 1190 | try: |
| 1191 | yield |
| 1192 | finally: |
| 1193 | obj[item] = real_val |
| 1194 | else: |
| 1195 | obj[item] = new_val |
| 1196 | try: |
| 1197 | yield |
| 1198 | finally: |
| 1199 | del obj[item] |