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