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 |
| 8 | import socket |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 9 | import sys |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 10 | import os |
| 11 | import os.path |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 12 | import shutil |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 13 | import warnings |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 14 | import unittest |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 15 | |
Benjamin Peterson | 744c2cd | 2008-05-26 16:26:37 +0000 | [diff] [blame] | 16 | __all__ = ["Error", "TestFailed", "TestSkipped", "ResourceDenied", "import_module", |
| 17 | "verbose", "use_resources", "max_memuse", "record_original_stdout", |
| 18 | "get_original_stdout", "unload", "unlink", "rmtree", "forget", |
| 19 | "is_resource_enabled", "requires", "find_unused_port", "bind_port", |
Benjamin Peterson | 79e4803 | 2008-05-26 17:44:33 +0000 | [diff] [blame] | 20 | "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "findfile", "verify", |
| 21 | "vereq", "sortdict", "check_syntax_error", "open_urlresource", |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 22 | "check_warnings", "CleanImport", "EnvironmentVarGuard", |
Benjamin Peterson | 79e4803 | 2008-05-26 17:44:33 +0000 | [diff] [blame] | 23 | "TransientResource", "captured_output", "captured_stdout", |
| 24 | "TransientResource", "transient_internet", "run_with_locale", |
| 25 | "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner", |
| 26 | "run_unittest", "run_doctest", "threading_setup", "threading_cleanup", |
| 27 | "reap_children"] |
Benjamin Peterson | 744c2cd | 2008-05-26 16:26:37 +0000 | [diff] [blame] | 28 | |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 29 | class Error(Exception): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 30 | """Base class for regression test exceptions.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 31 | |
| 32 | class TestFailed(Error): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 33 | """Test failed.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 34 | |
| 35 | class TestSkipped(Error): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 36 | """Test skipped. |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 37 | |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 38 | This can be raised to indicate that a test was deliberatly |
| 39 | skipped, but not because a feature wasn't available. For |
| 40 | example, if some resource can't be used, such as the network |
| 41 | appears to be unavailable, this should be raised instead of |
| 42 | TestFailed. |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 43 | """ |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 44 | |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 45 | class ResourceDenied(TestSkipped): |
| 46 | """Test skipped because it requested a disallowed resource. |
| 47 | |
| 48 | This is raised when a test calls requires() for a resource that |
| 49 | has not be enabled. It is used to distinguish between expected |
| 50 | and unexpected skips. |
| 51 | """ |
| 52 | |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 53 | def import_module(name, deprecated=False): |
| 54 | """Import the module to be tested, raising TestSkipped if it is not |
| 55 | available.""" |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 56 | with warnings.catch_warnings(): |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 57 | if deprecated: |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 58 | warnings.filterwarnings("ignore", ".+ (module|package)", |
| 59 | DeprecationWarning) |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 60 | try: |
| 61 | module = __import__(name, level=0) |
| 62 | except ImportError: |
| 63 | raise TestSkipped("No module named " + name) |
| 64 | else: |
| 65 | return module |
| 66 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 67 | verbose = 1 # Flag set to 0 by regrtest.py |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 68 | use_resources = None # Flag set to [] by regrtest.py |
| 69 | max_memuse = 0 # Disable bigmem tests (they will still be run with |
| 70 | # small sizes, to make sure they work.) |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 71 | real_max_memuse = 0 |
Guido van Rossum | 531661c | 1996-12-20 02:58:22 +0000 | [diff] [blame] | 72 | |
Tim Peters | 8dee809 | 2001-09-25 20:05:11 +0000 | [diff] [blame] | 73 | # _original_stdout is meant to hold stdout at the time regrtest began. |
| 74 | # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. |
| 75 | # The point is to have some flavor of stdout the user can actually see. |
| 76 | _original_stdout = None |
| 77 | def record_original_stdout(stdout): |
| 78 | global _original_stdout |
| 79 | _original_stdout = stdout |
| 80 | |
| 81 | def get_original_stdout(): |
| 82 | return _original_stdout or sys.stdout |
| 83 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 84 | def unload(name): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 85 | try: |
| 86 | del sys.modules[name] |
| 87 | except KeyError: |
| 88 | pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 89 | |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 90 | def unlink(filename): |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 91 | try: |
| 92 | os.unlink(filename) |
| 93 | except OSError: |
| 94 | pass |
| 95 | |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame] | 96 | def rmtree(path): |
| 97 | try: |
| 98 | shutil.rmtree(path) |
| 99 | except OSError as e: |
| 100 | # Unix returns ENOENT, Windows returns ESRCH. |
| 101 | if e.errno not in (errno.ENOENT, errno.ESRCH): |
| 102 | raise |
| 103 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 104 | def forget(modname): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 105 | '''"Forget" a module was ever imported by removing it from sys.modules and |
| 106 | deleting any .pyc and .pyo files.''' |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 107 | unload(modname) |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 108 | for dirname in sys.path: |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 109 | unlink(os.path.join(dirname, modname + '.pyc')) |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 110 | # Deleting the .pyo file cannot be within the 'try' for the .pyc since |
| 111 | # the chance exists that there is no .pyc (and thus the 'try' statement |
| 112 | # is exited) but there is a .pyo file. |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 113 | unlink(os.path.join(dirname, modname + '.pyo')) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 114 | |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 115 | def is_resource_enabled(resource): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 116 | """Test whether a resource is enabled. Known resources are set by |
| 117 | regrtest.py.""" |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 118 | return use_resources is not None and resource in use_resources |
| 119 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 120 | def requires(resource, msg=None): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 121 | """Raise ResourceDenied if the specified resource is not available. |
| 122 | |
| 123 | If the caller's module is __main__ then automatically return True. The |
| 124 | possibility of False being returned occurs when regrtest.py is executing.""" |
Skip Montanaro | d839ecd | 2003-04-24 19:06:57 +0000 | [diff] [blame] | 125 | # see if the caller's module is __main__ - if so, treat as if |
| 126 | # the resource was set |
| 127 | if sys._getframe().f_back.f_globals.get("__name__") == "__main__": |
| 128 | return |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 129 | if not is_resource_enabled(resource): |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 130 | if msg is None: |
| 131 | msg = "Use of the `%s' resource not enabled" % resource |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 132 | raise ResourceDenied(msg) |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 133 | |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 134 | HOST = 'localhost' |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 135 | |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 136 | def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): |
| 137 | """Returns an unused port that should be suitable for binding. This is |
| 138 | achieved by creating a temporary socket with the same family and type as |
| 139 | the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to |
| 140 | the specified host address (defaults to 0.0.0.0) with the port set to 0, |
| 141 | eliciting an unused ephemeral port from the OS. The temporary socket is |
| 142 | then closed and deleted, and the ephemeral port is returned. |
| 143 | |
| 144 | Either this method or bind_port() should be used for any tests where a |
| 145 | server socket needs to be bound to a particular port for the duration of |
| 146 | the test. Which one to use depends on whether the calling code is creating |
| 147 | a python socket, or if an unused port needs to be provided in a constructor |
| 148 | or passed to an external program (i.e. the -accept argument to openssl's |
| 149 | s_server mode). Always prefer bind_port() over find_unused_port() where |
| 150 | possible. Hard coded ports should *NEVER* be used. As soon as a server |
| 151 | socket is bound to a hard coded port, the ability to run multiple instances |
| 152 | of the test simultaneously on the same host is compromised, which makes the |
| 153 | test a ticking time bomb in a buildbot environment. On Unix buildbots, this |
| 154 | may simply manifest as a failed test, which can be recovered from without |
| 155 | intervention in most cases, but on Windows, the entire python process can |
| 156 | completely and utterly wedge, requiring someone to log in to the buildbot |
| 157 | and manually kill the affected process. |
| 158 | |
| 159 | (This is easy to reproduce on Windows, unfortunately, and can be traced to |
| 160 | the SO_REUSEADDR socket option having different semantics on Windows versus |
| 161 | Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, |
| 162 | listen and then accept connections on identical host/ports. An EADDRINUSE |
| 163 | socket.error will be raised at some point (depending on the platform and |
| 164 | the order bind and listen were called on each socket). |
| 165 | |
| 166 | However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE |
| 167 | will ever be raised when attempting to bind two identical host/ports. When |
| 168 | accept() is called on each socket, the second caller's process will steal |
| 169 | the port from the first caller, leaving them both in an awkwardly wedged |
| 170 | state where they'll no longer respond to any signals or graceful kills, and |
| 171 | must be forcibly killed via OpenProcess()/TerminateProcess(). |
| 172 | |
| 173 | The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option |
| 174 | instead of SO_REUSEADDR, which effectively affords the same semantics as |
| 175 | SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open |
| 176 | Source world compared to Windows ones, this is a common mistake. A quick |
| 177 | look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when |
| 178 | openssl.exe is called with the 's_server' option, for example. See |
| 179 | http://bugs.python.org/issue2550 for more info. The following site also |
| 180 | has a very thorough description about the implications of both REUSEADDR |
| 181 | and EXCLUSIVEADDRUSE on Windows: |
| 182 | http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) |
| 183 | |
| 184 | XXX: although this approach is a vast improvement on previous attempts to |
| 185 | elicit unused ports, it rests heavily on the assumption that the ephemeral |
| 186 | port returned to us by the OS won't immediately be dished back out to some |
| 187 | other process when we close and delete our temporary socket but before our |
| 188 | calling code has a chance to bind the returned port. We can deal with this |
| 189 | issue if/when we come across it. |
| 190 | """ |
| 191 | |
| 192 | tempsock = socket.socket(family, socktype) |
| 193 | port = bind_port(tempsock) |
| 194 | tempsock.close() |
| 195 | del tempsock |
| 196 | return port |
| 197 | |
| 198 | def bind_port(sock, host=HOST): |
| 199 | """Bind the socket to a free port and return the port number. Relies on |
| 200 | ephemeral ports in order to ensure we are using an unbound port. This is |
| 201 | important as many tests may be running simultaneously, especially in a |
| 202 | buildbot environment. This method raises an exception if the sock.family |
| 203 | is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR |
| 204 | or SO_REUSEPORT set on it. Tests should *never* set these socket options |
| 205 | for TCP/IP sockets. The only case for setting these options is testing |
| 206 | multicasting via multiple UDP sockets. |
| 207 | |
| 208 | Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. |
| 209 | on Windows), it will be set on the socket. This will prevent anyone else |
| 210 | from bind()'ing to our host/port for the duration of the test. |
| 211 | """ |
| 212 | |
| 213 | if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: |
| 214 | if hasattr(socket, 'SO_REUSEADDR'): |
| 215 | if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: |
| 216 | raise TestFailed("tests should never set the SO_REUSEADDR " \ |
| 217 | "socket option on TCP/IP sockets!") |
| 218 | if hasattr(socket, 'SO_REUSEPORT'): |
| 219 | if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: |
| 220 | raise TestFailed("tests should never set the SO_REUSEPORT " \ |
| 221 | "socket option on TCP/IP sockets!") |
| 222 | if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): |
| 223 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) |
| 224 | |
| 225 | sock.bind((host, 0)) |
| 226 | port = sock.getsockname()[1] |
| 227 | return port |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 228 | |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 229 | FUZZ = 1e-6 |
| 230 | |
| 231 | def fcmp(x, y): # fuzzy comparison function |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 232 | if isinstance(x, float) or isinstance(y, float): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 233 | try: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 234 | fuzz = (abs(x) + abs(y)) * FUZZ |
| 235 | if abs(x-y) <= fuzz: |
| 236 | return 0 |
| 237 | except: |
| 238 | pass |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 239 | elif type(x) == type(y) and isinstance(x, (tuple, list)): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 240 | for i in range(min(len(x), len(y))): |
| 241 | outcome = fcmp(x[i], y[i]) |
Fred Drake | 132dce2 | 2000-12-12 23:11:42 +0000 | [diff] [blame] | 242 | if outcome != 0: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 243 | return outcome |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 244 | return (len(x) > len(y)) - (len(x) < len(y)) |
| 245 | return (x > y) - (x < y) |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 246 | |
Finn Bock | 57bc5fa | 2002-11-01 18:02:03 +0000 | [diff] [blame] | 247 | is_jython = sys.platform.startswith('java') |
| 248 | |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 249 | # Filename used for testing |
| 250 | if os.name == 'java': |
| 251 | # Jython disallows @ in module names |
| 252 | TESTFN = '$test' |
Martin v. Löwis | a94568a | 2003-05-10 07:36:56 +0000 | [diff] [blame] | 253 | else: |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 254 | TESTFN = '@test' |
Walter Dörwald | 9b77553 | 2007-06-08 14:30:53 +0000 | [diff] [blame] | 255 | |
| 256 | # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() |
| 257 | # TESTFN_UNICODE is a filename that can be encoded using the |
| 258 | # file system encoding, but *not* with the default (ascii) encoding |
| 259 | TESTFN_UNICODE = "@test-\xe0\xf2" |
| 260 | TESTFN_ENCODING = sys.getfilesystemencoding() |
| 261 | # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be |
| 262 | # able to be encoded by *either* the default or filesystem encoding. |
| 263 | # This test really only makes sense on Windows NT platforms |
| 264 | # which have special Unicode support in posixmodule. |
| 265 | if (not hasattr(sys, "getwindowsversion") or |
| 266 | sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME |
| 267 | TESTFN_UNICODE_UNENCODEABLE = None |
| 268 | else: |
| 269 | # Japanese characters (I think - from bug 846133) |
| 270 | TESTFN_UNICODE_UNENCODEABLE = "@test-\u5171\u6709\u3055\u308c\u308b" |
| 271 | try: |
| 272 | # XXX - Note - should be using TESTFN_ENCODING here - but for |
| 273 | # Windows, "mbcs" currently always operates as if in |
| 274 | # errors=ignore' mode - hence we get '?' characters rather than |
| 275 | # the exception. 'Latin1' operates as we expect - ie, fails. |
| 276 | # See [ 850997 ] mbcs encoding ignores errors |
| 277 | TESTFN_UNICODE_UNENCODEABLE.encode("Latin1") |
| 278 | except UnicodeEncodeError: |
| 279 | pass |
Martin v. Löwis | 2411a2d | 2002-11-09 19:57:26 +0000 | [diff] [blame] | 280 | else: |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 281 | print('WARNING: The filename %r CAN be encoded by the filesystem. ' |
| 282 | 'Unicode filename tests may not be effective' |
| 283 | % TESTFN_UNICODE_UNENCODEABLE) |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 284 | |
| 285 | # Make sure we can write to TESTFN, try in /tmp if we can't |
| 286 | fp = None |
| 287 | try: |
| 288 | fp = open(TESTFN, 'w+') |
| 289 | except IOError: |
| 290 | TMP_TESTFN = os.path.join('/tmp', TESTFN) |
| 291 | try: |
| 292 | fp = open(TMP_TESTFN, 'w+') |
| 293 | TESTFN = TMP_TESTFN |
| 294 | del TMP_TESTFN |
| 295 | except IOError: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 296 | print(('WARNING: tests will fail, unable to write to: %s or %s' % |
| 297 | (TESTFN, TMP_TESTFN))) |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 298 | if fp is not None: |
| 299 | fp.close() |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 300 | unlink(TESTFN) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 301 | del fp |
Guido van Rossum | a8f7e59 | 2001-03-13 09:31:07 +0000 | [diff] [blame] | 302 | |
Guido van Rossum | e26132c | 1998-04-23 20:13:30 +0000 | [diff] [blame] | 303 | def findfile(file, here=__file__): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 304 | """Try to find a file on sys.path and the working directory. If it is not |
| 305 | found the argument passed to the function is returned (this does not |
| 306 | necessarily signal failure; could still be the legitimate path).""" |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 307 | if os.path.isabs(file): |
| 308 | return file |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 309 | path = sys.path |
| 310 | path = [os.path.dirname(here)] + path |
| 311 | for dn in path: |
| 312 | fn = os.path.join(dn, file) |
| 313 | if os.path.exists(fn): return fn |
| 314 | return file |
Marc-André Lemburg | 3661908 | 2001-01-17 19:11:13 +0000 | [diff] [blame] | 315 | |
| 316 | def verify(condition, reason='test failed'): |
Guido van Rossum | a1374e4 | 2001-01-19 19:01:56 +0000 | [diff] [blame] | 317 | """Verify that condition is true. If not, raise TestFailed. |
Marc-André Lemburg | 3661908 | 2001-01-17 19:11:13 +0000 | [diff] [blame] | 318 | |
Skip Montanaro | c955f89 | 2001-01-20 19:12:54 +0000 | [diff] [blame] | 319 | The optional argument reason can be given to provide |
Tim Peters | 983874d | 2001-01-19 05:59:21 +0000 | [diff] [blame] | 320 | a better error text. |
Tim Peters | d2bf3b7 | 2001-01-18 02:22:22 +0000 | [diff] [blame] | 321 | """ |
Tim Peters | 983874d | 2001-01-19 05:59:21 +0000 | [diff] [blame] | 322 | |
Tim Peters | d2bf3b7 | 2001-01-18 02:22:22 +0000 | [diff] [blame] | 323 | if not condition: |
Guido van Rossum | a1374e4 | 2001-01-19 19:01:56 +0000 | [diff] [blame] | 324 | raise TestFailed(reason) |
Jeremy Hylton | 4779399 | 2001-02-19 15:35:26 +0000 | [diff] [blame] | 325 | |
Tim Peters | c2fe618 | 2001-10-30 23:20:46 +0000 | [diff] [blame] | 326 | def vereq(a, b): |
Tim Peters | 7790297 | 2001-12-29 17:34:57 +0000 | [diff] [blame] | 327 | """Raise TestFailed if a == b is false. |
| 328 | |
| 329 | This is better than verify(a == b) because, in case of failure, the |
| 330 | error message incorporates repr(a) and repr(b) so you can see the |
| 331 | inputs. |
| 332 | |
| 333 | Note that "not (a == b)" isn't necessarily the same as "a != b"; the |
| 334 | former is tested. |
| 335 | """ |
| 336 | |
Tim Peters | c2fe618 | 2001-10-30 23:20:46 +0000 | [diff] [blame] | 337 | if not (a == b): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 338 | raise TestFailed("%r == %r" % (a, b)) |
Tim Peters | c2fe618 | 2001-10-30 23:20:46 +0000 | [diff] [blame] | 339 | |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 340 | def sortdict(dict): |
| 341 | "Like repr(dict), but in sorted order." |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 342 | items = sorted(dict.items()) |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 343 | reprpairs = ["%r: %r" % pair for pair in items] |
| 344 | withcommas = ", ".join(reprpairs) |
| 345 | return "{%s}" % withcommas |
| 346 | |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 347 | def make_bad_fd(): |
| 348 | """ |
| 349 | Create an invalid file descriptor by opening and closing a file and return |
| 350 | its fd. |
| 351 | """ |
| 352 | file = open(TESTFN, "wb") |
| 353 | try: |
| 354 | return file.fileno() |
| 355 | finally: |
| 356 | file.close() |
| 357 | unlink(TESTFN) |
| 358 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 359 | def check_syntax_error(testcase, statement): |
Jeremy Hylton | 4779399 | 2001-02-19 15:35:26 +0000 | [diff] [blame] | 360 | try: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 361 | compile(statement, '<test string>', 'exec') |
Jeremy Hylton | 4779399 | 2001-02-19 15:35:26 +0000 | [diff] [blame] | 362 | except SyntaxError: |
| 363 | pass |
| 364 | else: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 365 | testcase.fail('Missing SyntaxError: "%s"' % statement) |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 366 | |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 367 | def open_urlresource(url, *args, **kw): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 368 | import urllib.request, urllib.parse |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 369 | |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 370 | requires('urlfetch') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 371 | filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL! |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 372 | |
| 373 | for path in [os.path.curdir, os.path.pardir]: |
| 374 | fn = os.path.join(path, filename) |
| 375 | if os.path.exists(fn): |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 376 | return open(fn, *args, **kw) |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 377 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 378 | print('\tfetching %s ...' % url, file=get_original_stdout()) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 379 | fn, _ = urllib.request.urlretrieve(url, filename) |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 380 | return open(fn, *args, **kw) |
Thomas Wouters | 9fe394c | 2007-02-05 01:24:16 +0000 | [diff] [blame] | 381 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 382 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 383 | class WarningsRecorder(object): |
| 384 | """Convenience wrapper for the warnings list returned on |
| 385 | entry to the warnings.catch_warnings() context manager. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 386 | """ |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 387 | def __init__(self, warnings_list): |
| 388 | self.warnings = warnings_list |
| 389 | |
| 390 | def __getattr__(self, attr): |
| 391 | if self.warnings: |
| 392 | return getattr(self.warnings[-1], attr) |
| 393 | elif attr in warnings.WarningMessage._WARNING_DETAILS: |
| 394 | return None |
| 395 | raise AttributeError("%r has no attribute %r" % (self, attr)) |
| 396 | |
| 397 | def reset(self): |
| 398 | del self.warnings[:] |
| 399 | |
| 400 | @contextlib.contextmanager |
| 401 | def check_warnings(): |
| 402 | with warnings.catch_warnings(record=True) as w: |
| 403 | yield WarningsRecorder(w) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 404 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 405 | |
| 406 | class CleanImport(object): |
| 407 | """Context manager to force import to return a new module reference. |
| 408 | |
| 409 | This is useful for testing module-level behaviours, such as |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 410 | the emission of a DeprecationWarning on import. |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 411 | |
| 412 | Use like this: |
| 413 | |
| 414 | with CleanImport("foo"): |
| 415 | __import__("foo") # new reference |
| 416 | """ |
| 417 | |
| 418 | def __init__(self, *module_names): |
| 419 | self.original_modules = sys.modules.copy() |
| 420 | for module_name in module_names: |
| 421 | if module_name in sys.modules: |
| 422 | module = sys.modules[module_name] |
| 423 | # It is possible that module_name is just an alias for |
| 424 | # another module (e.g. stub for modules renamed in 3.x). |
| 425 | # In that case, we also need delete the real module to clear |
| 426 | # the import cache. |
| 427 | if module.__name__ != module_name: |
| 428 | del sys.modules[module.__name__] |
| 429 | del sys.modules[module_name] |
| 430 | |
| 431 | def __enter__(self): |
| 432 | return self |
| 433 | |
| 434 | def __exit__(self, *ignore_exc): |
| 435 | sys.modules.update(self.original_modules) |
| 436 | |
| 437 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 438 | class EnvironmentVarGuard(object): |
| 439 | |
| 440 | """Class to help protect the environment variable properly. Can be used as |
| 441 | a context manager.""" |
| 442 | |
| 443 | def __init__(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 444 | self._environ = os.environ |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 445 | self._unset = set() |
| 446 | self._reset = dict() |
| 447 | |
| 448 | def set(self, envvar, value): |
| 449 | if envvar not in self._environ: |
| 450 | self._unset.add(envvar) |
| 451 | else: |
| 452 | self._reset[envvar] = self._environ[envvar] |
| 453 | self._environ[envvar] = value |
| 454 | |
| 455 | def unset(self, envvar): |
| 456 | if envvar in self._environ: |
| 457 | self._reset[envvar] = self._environ[envvar] |
| 458 | del self._environ[envvar] |
| 459 | |
| 460 | def __enter__(self): |
| 461 | return self |
| 462 | |
| 463 | def __exit__(self, *ignore_exc): |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 464 | for envvar, value in self._reset.items(): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 465 | self._environ[envvar] = value |
| 466 | for unset in self._unset: |
| 467 | del self._environ[unset] |
| 468 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 469 | class TransientResource(object): |
| 470 | |
| 471 | """Raise ResourceDenied if an exception is raised while the context manager |
| 472 | is in effect that matches the specified exception and attributes.""" |
| 473 | |
| 474 | def __init__(self, exc, **kwargs): |
| 475 | self.exc = exc |
| 476 | self.attrs = kwargs |
| 477 | |
| 478 | def __enter__(self): |
| 479 | return self |
| 480 | |
| 481 | def __exit__(self, type_=None, value=None, traceback=None): |
| 482 | """If type_ is a subclass of self.exc and value has attributes matching |
| 483 | self.attrs, raise ResourceDenied. Otherwise let the exception |
| 484 | propagate (if any).""" |
| 485 | if type_ is not None and issubclass(self.exc, type_): |
| 486 | for attr, attr_value in self.attrs.items(): |
| 487 | if not hasattr(value, attr): |
| 488 | break |
| 489 | if getattr(value, attr) != attr_value: |
| 490 | break |
| 491 | else: |
| 492 | raise ResourceDenied("an optional resource is not available") |
| 493 | |
| 494 | |
| 495 | def transient_internet(): |
| 496 | """Return a context manager that raises ResourceDenied when various issues |
| 497 | with the Internet connection manifest themselves as exceptions.""" |
| 498 | time_out = TransientResource(IOError, errno=errno.ETIMEDOUT) |
| 499 | socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET) |
| 500 | ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET) |
| 501 | return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset) |
| 502 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 503 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 504 | @contextlib.contextmanager |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 505 | def captured_output(stream_name): |
| 506 | """Run the 'with' statement body using a StringIO object in place of a |
| 507 | specific attribute on the sys module. |
| 508 | Example use (with 'stream_name=stdout'):: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 509 | |
| 510 | with captured_stdout() as s: |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 511 | print("hello") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 512 | assert s.getvalue() == "hello" |
| 513 | """ |
| 514 | import io |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 515 | orig_stdout = getattr(sys, stream_name) |
| 516 | setattr(sys, stream_name, io.StringIO()) |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 517 | try: |
| 518 | yield getattr(sys, stream_name) |
| 519 | finally: |
| 520 | setattr(sys, stream_name, orig_stdout) |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 521 | |
| 522 | def captured_stdout(): |
| 523 | return captured_output("stdout") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 524 | |
| 525 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 526 | #======================================================================= |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 527 | # Decorator for running a function in a different locale, correctly resetting |
| 528 | # it afterwards. |
| 529 | |
| 530 | def run_with_locale(catstr, *locales): |
| 531 | def decorator(func): |
| 532 | def inner(*args, **kwds): |
| 533 | try: |
| 534 | import locale |
| 535 | category = getattr(locale, catstr) |
| 536 | orig_locale = locale.setlocale(category) |
| 537 | except AttributeError: |
| 538 | # if the test author gives us an invalid category string |
| 539 | raise |
| 540 | except: |
| 541 | # cannot retrieve original locale, so do nothing |
| 542 | locale = orig_locale = None |
| 543 | else: |
| 544 | for loc in locales: |
| 545 | try: |
| 546 | locale.setlocale(category, loc) |
| 547 | break |
| 548 | except: |
| 549 | pass |
| 550 | |
| 551 | # now run the function, resetting the locale on exceptions |
| 552 | try: |
| 553 | return func(*args, **kwds) |
| 554 | finally: |
| 555 | if locale and orig_locale: |
| 556 | locale.setlocale(category, orig_locale) |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 557 | inner.__name__ = func.__name__ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 558 | inner.__doc__ = func.__doc__ |
| 559 | return inner |
| 560 | return decorator |
| 561 | |
| 562 | #======================================================================= |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 563 | # Big-memory-test support. Separate from 'resources' because memory use |
| 564 | # should be configurable. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 565 | |
| 566 | # Some handy shorthands. Note that these are used for byte-limits as well |
| 567 | # as size-limits, in the various bigmem tests |
| 568 | _1M = 1024*1024 |
| 569 | _1G = 1024 * _1M |
| 570 | _2G = 2 * _1G |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 571 | _4G = 4 * _1G |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 572 | |
Thomas Wouters | d2cf20e | 2007-08-30 22:57:53 +0000 | [diff] [blame] | 573 | MAX_Py_ssize_t = sys.maxsize |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 574 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 575 | def set_memlimit(limit): |
| 576 | import re |
| 577 | global max_memuse |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 578 | global real_max_memuse |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 579 | sizes = { |
| 580 | 'k': 1024, |
| 581 | 'm': _1M, |
| 582 | 'g': _1G, |
| 583 | 't': 1024*_1G, |
| 584 | } |
| 585 | m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit, |
| 586 | re.IGNORECASE | re.VERBOSE) |
| 587 | if m is None: |
| 588 | raise ValueError('Invalid memory limit %r' % (limit,)) |
| 589 | memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()]) |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 590 | real_max_memuse = memlimit |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 591 | if memlimit > MAX_Py_ssize_t: |
| 592 | memlimit = MAX_Py_ssize_t |
| 593 | if memlimit < _2G - 1: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 594 | raise ValueError('Memory limit %r too low to be useful' % (limit,)) |
| 595 | max_memuse = memlimit |
| 596 | |
| 597 | def bigmemtest(minsize, memuse, overhead=5*_1M): |
| 598 | """Decorator for bigmem tests. |
| 599 | |
| 600 | 'minsize' is the minimum useful size for the test (in arbitrary, |
| 601 | test-interpreted units.) 'memuse' is the number of 'bytes per size' for |
| 602 | the test, or a good estimate of it. 'overhead' specifies fixed overhead, |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 603 | independent of the testsize, and defaults to 5Mb. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 604 | |
| 605 | The decorator tries to guess a good value for 'size' and passes it to |
| 606 | the decorated test function. If minsize * memuse is more than the |
| 607 | allowed memory use (as defined by max_memuse), the test is skipped. |
| 608 | Otherwise, minsize is adjusted upward to use up to max_memuse. |
| 609 | """ |
| 610 | def decorator(f): |
| 611 | def wrapper(self): |
| 612 | if not max_memuse: |
| 613 | # If max_memuse is 0 (the default), |
| 614 | # we still want to run the tests with size set to a few kb, |
| 615 | # to make sure they work. We still want to avoid using |
| 616 | # too much memory, though, but we do that noisily. |
| 617 | maxsize = 5147 |
| 618 | self.failIf(maxsize * memuse + overhead > 20 * _1M) |
| 619 | else: |
| 620 | maxsize = int((max_memuse - overhead) / memuse) |
| 621 | if maxsize < minsize: |
| 622 | # Really ought to print 'test skipped' or something |
| 623 | if verbose: |
| 624 | sys.stderr.write("Skipping %s because of memory " |
| 625 | "constraint\n" % (f.__name__,)) |
| 626 | return |
| 627 | # Try to keep some breathing room in memory use |
| 628 | maxsize = max(maxsize - 50 * _1M, minsize) |
| 629 | return f(self, maxsize) |
| 630 | wrapper.minsize = minsize |
| 631 | wrapper.memuse = memuse |
| 632 | wrapper.overhead = overhead |
| 633 | return wrapper |
| 634 | return decorator |
| 635 | |
Neal Norwitz | 3ce5d92 | 2008-08-24 07:08:55 +0000 | [diff] [blame] | 636 | def precisionbigmemtest(size, memuse, overhead=5*_1M): |
| 637 | def decorator(f): |
| 638 | def wrapper(self): |
| 639 | if not real_max_memuse: |
| 640 | maxsize = 5147 |
| 641 | else: |
| 642 | maxsize = size |
| 643 | |
| 644 | if real_max_memuse and real_max_memuse < maxsize * memuse: |
| 645 | if verbose: |
| 646 | sys.stderr.write("Skipping %s because of memory " |
| 647 | "constraint\n" % (f.__name__,)) |
| 648 | return |
| 649 | |
| 650 | return f(self, maxsize) |
| 651 | wrapper.size = size |
| 652 | wrapper.memuse = memuse |
| 653 | wrapper.overhead = overhead |
| 654 | return wrapper |
| 655 | return decorator |
| 656 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 657 | def bigaddrspacetest(f): |
| 658 | """Decorator for tests that fill the address space.""" |
| 659 | def wrapper(self): |
| 660 | if max_memuse < MAX_Py_ssize_t: |
| 661 | if verbose: |
| 662 | sys.stderr.write("Skipping %s because of memory " |
| 663 | "constraint\n" % (f.__name__,)) |
| 664 | else: |
| 665 | return f(self) |
| 666 | return wrapper |
| 667 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 668 | #======================================================================= |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 669 | # unittest integration. |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 670 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 671 | class BasicTestRunner: |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 672 | def run(self, test): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 673 | result = unittest.TestResult() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 674 | test(result) |
| 675 | return result |
| 676 | |
| 677 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 678 | def _run_suite(suite): |
Barry Warsaw | c88425e | 2001-09-20 06:31:22 +0000 | [diff] [blame] | 679 | """Run tests from a unittest.TestSuite-derived class.""" |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 680 | if verbose: |
Fred Drake | 84a5934 | 2001-03-23 04:21:17 +0000 | [diff] [blame] | 681 | runner = unittest.TextTestRunner(sys.stdout, verbosity=2) |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 682 | else: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 683 | runner = BasicTestRunner() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 684 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 685 | result = runner.run(suite) |
| 686 | if not result.wasSuccessful(): |
Fred Drake | 14f6c18 | 2001-07-16 18:51:32 +0000 | [diff] [blame] | 687 | if len(result.errors) == 1 and not result.failures: |
| 688 | err = result.errors[0][1] |
| 689 | elif len(result.failures) == 1 and not result.errors: |
| 690 | err = result.failures[0][1] |
| 691 | else: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 692 | err = "errors occurred; run in verbose mode for details" |
Tim Peters | 2d84f2c | 2001-09-08 03:37:56 +0000 | [diff] [blame] | 693 | raise TestFailed(err) |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 694 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 695 | |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 696 | def run_unittest(*classes): |
| 697 | """Run tests from unittest.TestCase-derived classes.""" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 698 | valid_types = (unittest.TestSuite, unittest.TestCase) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 699 | suite = unittest.TestSuite() |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 700 | for cls in classes: |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 701 | if isinstance(cls, str): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 702 | if cls in sys.modules: |
| 703 | suite.addTest(unittest.findTestCases(sys.modules[cls])) |
| 704 | else: |
| 705 | raise ValueError("str arguments must be keys in sys.modules") |
| 706 | elif isinstance(cls, valid_types): |
Raymond Hettinger | 21d9987 | 2003-07-16 02:59:32 +0000 | [diff] [blame] | 707 | suite.addTest(cls) |
| 708 | else: |
| 709 | suite.addTest(unittest.makeSuite(cls)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 710 | _run_suite(suite) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 711 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 712 | |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 713 | #======================================================================= |
| 714 | # doctest driver. |
| 715 | |
| 716 | def run_doctest(module, verbosity=None): |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 717 | """Run doctest on the given module. Return (#failures, #tests). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 718 | |
| 719 | If optional argument verbosity is not specified (or is None), pass |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 720 | support's belief about verbosity on to doctest. Else doctest's |
Tim Peters | bea3fb8 | 2001-09-10 01:39:21 +0000 | [diff] [blame] | 721 | usual behavior is used (it searches sys.argv for -v). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 722 | """ |
| 723 | |
| 724 | import doctest |
| 725 | |
| 726 | if verbosity is None: |
| 727 | verbosity = verbose |
| 728 | else: |
| 729 | verbosity = None |
| 730 | |
Tim Peters | 342ca75 | 2001-09-25 19:13:20 +0000 | [diff] [blame] | 731 | # Direct doctest output (normally just errors) to real stdout; doctest |
| 732 | # output shouldn't be compared by regrtest. |
| 733 | save_stdout = sys.stdout |
Tim Peters | 8dee809 | 2001-09-25 20:05:11 +0000 | [diff] [blame] | 734 | sys.stdout = get_original_stdout() |
Tim Peters | 342ca75 | 2001-09-25 19:13:20 +0000 | [diff] [blame] | 735 | try: |
| 736 | f, t = doctest.testmod(module, verbose=verbosity) |
| 737 | if f: |
| 738 | raise TestFailed("%d of %d doctests failed" % (f, t)) |
| 739 | finally: |
| 740 | sys.stdout = save_stdout |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 741 | if verbose: |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 742 | print('doctest (%s) ... %d tests with zero failures' % |
| 743 | (module.__name__, t)) |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 744 | return f, t |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 745 | |
| 746 | #======================================================================= |
| 747 | # Threading support to prevent reporting refleaks when running regrtest.py -R |
| 748 | |
| 749 | def threading_setup(): |
| 750 | import threading |
| 751 | return len(threading._active), len(threading._limbo) |
| 752 | |
| 753 | def threading_cleanup(num_active, num_limbo): |
| 754 | import threading |
| 755 | import time |
| 756 | |
| 757 | _MAX_COUNT = 10 |
| 758 | count = 0 |
| 759 | while len(threading._active) != num_active and count < _MAX_COUNT: |
| 760 | count += 1 |
| 761 | time.sleep(0.1) |
| 762 | |
| 763 | count = 0 |
| 764 | while len(threading._limbo) != num_limbo and count < _MAX_COUNT: |
| 765 | count += 1 |
| 766 | time.sleep(0.1) |
| 767 | |
| 768 | def reap_children(): |
| 769 | """Use this function at the end of test_main() whenever sub-processes |
| 770 | are started. This will help ensure that no extra children (zombies) |
| 771 | stick around to hog resources and create problems when looking |
| 772 | for refleaks. |
| 773 | """ |
| 774 | |
| 775 | # Reap all our dead child processes so we don't leave zombies around. |
| 776 | # 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] | 777 | if hasattr(os, 'waitpid'): |
| 778 | any_process = -1 |
| 779 | while True: |
| 780 | try: |
| 781 | # This will raise an exception on Windows. That's ok. |
| 782 | pid, status = os.waitpid(any_process, os.WNOHANG) |
| 783 | if pid == 0: |
| 784 | break |
| 785 | except: |
| 786 | break |