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 | |
Barry Warsaw | 408b6d3 | 2002-07-30 23:27:12 +0000 | [diff] [blame] | 3 | if __name__ != 'test.test_support': |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4 | raise ImportError('test_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 | |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 16 | class Error(Exception): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 17 | """Base class for regression test exceptions.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 18 | |
| 19 | class TestFailed(Error): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 20 | """Test failed.""" |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 21 | |
| 22 | class TestSkipped(Error): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 23 | """Test skipped. |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 24 | |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 25 | This can be raised to indicate that a test was deliberatly |
| 26 | skipped, but not because a feature wasn't available. For |
| 27 | example, if some resource can't be used, such as the network |
| 28 | appears to be unavailable, this should be raised instead of |
| 29 | TestFailed. |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 30 | """ |
Fred Drake | 1790dd4 | 2000-07-24 06:55:00 +0000 | [diff] [blame] | 31 | |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 32 | class ResourceDenied(TestSkipped): |
| 33 | """Test skipped because it requested a disallowed resource. |
| 34 | |
| 35 | This is raised when a test calls requires() for a resource that |
| 36 | has not be enabled. It is used to distinguish between expected |
| 37 | and unexpected skips. |
| 38 | """ |
| 39 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 40 | verbose = 1 # Flag set to 0 by regrtest.py |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 41 | use_resources = None # Flag set to [] by regrtest.py |
| 42 | max_memuse = 0 # Disable bigmem tests (they will still be run with |
| 43 | # small sizes, to make sure they work.) |
Guido van Rossum | 531661c | 1996-12-20 02:58:22 +0000 | [diff] [blame] | 44 | |
Tim Peters | 8dee809 | 2001-09-25 20:05:11 +0000 | [diff] [blame] | 45 | # _original_stdout is meant to hold stdout at the time regrtest began. |
| 46 | # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. |
| 47 | # The point is to have some flavor of stdout the user can actually see. |
| 48 | _original_stdout = None |
| 49 | def record_original_stdout(stdout): |
| 50 | global _original_stdout |
| 51 | _original_stdout = stdout |
| 52 | |
| 53 | def get_original_stdout(): |
| 54 | return _original_stdout or sys.stdout |
| 55 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 56 | def unload(name): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 57 | try: |
| 58 | del sys.modules[name] |
| 59 | except KeyError: |
| 60 | pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 61 | |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 62 | def unlink(filename): |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 63 | try: |
| 64 | os.unlink(filename) |
| 65 | except OSError: |
| 66 | pass |
| 67 | |
Christian Heimes | 23daade0 | 2008-02-25 12:39:23 +0000 | [diff] [blame^] | 68 | def rmtree(path): |
| 69 | try: |
| 70 | shutil.rmtree(path) |
| 71 | except OSError as e: |
| 72 | # Unix returns ENOENT, Windows returns ESRCH. |
| 73 | if e.errno not in (errno.ENOENT, errno.ESRCH): |
| 74 | raise |
| 75 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 76 | def forget(modname): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 77 | '''"Forget" a module was ever imported by removing it from sys.modules and |
| 78 | deleting any .pyc and .pyo files.''' |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 79 | unload(modname) |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 80 | for dirname in sys.path: |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 81 | unlink(os.path.join(dirname, modname + '.pyc')) |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 82 | # Deleting the .pyo file cannot be within the 'try' for the .pyc since |
| 83 | # the chance exists that there is no .pyc (and thus the 'try' statement |
| 84 | # is exited) but there is a .pyo file. |
Skip Montanaro | 7a98be2 | 2007-08-16 14:35:24 +0000 | [diff] [blame] | 85 | unlink(os.path.join(dirname, modname + '.pyo')) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 86 | |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 87 | def is_resource_enabled(resource): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 88 | """Test whether a resource is enabled. Known resources are set by |
| 89 | regrtest.py.""" |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 90 | return use_resources is not None and resource in use_resources |
| 91 | |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 92 | def requires(resource, msg=None): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 93 | """Raise ResourceDenied if the specified resource is not available. |
| 94 | |
| 95 | If the caller's module is __main__ then automatically return True. The |
| 96 | possibility of False being returned occurs when regrtest.py is executing.""" |
Skip Montanaro | d839ecd | 2003-04-24 19:06:57 +0000 | [diff] [blame] | 97 | # see if the caller's module is __main__ - if so, treat as if |
| 98 | # the resource was set |
| 99 | if sys._getframe().f_back.f_globals.get("__name__") == "__main__": |
| 100 | return |
Tim Peters | b4ee4eb | 2002-12-04 03:26:57 +0000 | [diff] [blame] | 101 | if not is_resource_enabled(resource): |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 102 | if msg is None: |
| 103 | msg = "Use of the `%s' resource not enabled" % resource |
Fred Drake | 9a0db07 | 2003-02-03 15:19:30 +0000 | [diff] [blame] | 104 | raise ResourceDenied(msg) |
Barry Warsaw | c0fb605 | 2001-08-20 22:29:23 +0000 | [diff] [blame] | 105 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 106 | def bind_port(sock, host='', preferred_port=54321): |
| 107 | """Try to bind the sock to a port. If we are running multiple |
| 108 | tests and we don't try multiple ports, the test can fails. This |
| 109 | makes the test more robust.""" |
| 110 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 111 | # Find some random ports that hopefully no one is listening on. |
| 112 | # Ideally each test would clean up after itself and not continue listening |
| 113 | # on any ports. However, this isn't the case. The last port (0) is |
| 114 | # a stop-gap that asks the O/S to assign a port. Whenever the warning |
| 115 | # message below is printed, the test that is listening on the port should |
| 116 | # be fixed to close the socket at the end of the test. |
| 117 | # Another reason why we can't use a port is another process (possibly |
| 118 | # another instance of the test suite) is using the same port. |
| 119 | for port in [preferred_port, 9907, 10243, 32999, 0]: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 120 | try: |
| 121 | sock.bind((host, port)) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 122 | if port == 0: |
| 123 | port = sock.getsockname()[1] |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 124 | return port |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 125 | except socket.error as e: |
Guido van Rossum | e2c8f2d | 2007-05-09 23:43:17 +0000 | [diff] [blame] | 126 | (err, msg) = e.args |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 127 | if err != errno.EADDRINUSE: |
| 128 | raise |
Georg Brandl | f01fe69 | 2008-02-05 21:00:53 +0000 | [diff] [blame] | 129 | print(' WARNING: failed to listen on port %d, ' % port + |
| 130 | 'trying another', file=sys.__stderr__) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 131 | raise TestFailed('unable to find port to listen on') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 132 | |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 133 | FUZZ = 1e-6 |
| 134 | |
| 135 | def fcmp(x, y): # fuzzy comparison function |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 136 | if isinstance(x, float) or isinstance(y, float): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 137 | try: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 138 | fuzz = (abs(x) + abs(y)) * FUZZ |
| 139 | if abs(x-y) <= fuzz: |
| 140 | return 0 |
| 141 | except: |
| 142 | pass |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 143 | elif type(x) == type(y) and isinstance(x, (tuple, list)): |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 144 | for i in range(min(len(x), len(y))): |
| 145 | outcome = fcmp(x[i], y[i]) |
Fred Drake | 132dce2 | 2000-12-12 23:11:42 +0000 | [diff] [blame] | 146 | if outcome != 0: |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 147 | return outcome |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 148 | return (len(x) > len(y)) - (len(x) < len(y)) |
| 149 | return (x > y) - (x < y) |
Guido van Rossum | 35fb82a | 1993-01-26 13:04:43 +0000 | [diff] [blame] | 150 | |
Martin v. Löwis | 339d0f7 | 2001-08-17 18:39:25 +0000 | [diff] [blame] | 151 | try: |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 152 | str |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 153 | have_unicode = True |
Martin v. Löwis | 339d0f7 | 2001-08-17 18:39:25 +0000 | [diff] [blame] | 154 | except NameError: |
Neal Norwitz | 7921299 | 2006-08-21 16:27:31 +0000 | [diff] [blame] | 155 | have_unicode = False |
Martin v. Löwis | 339d0f7 | 2001-08-17 18:39:25 +0000 | [diff] [blame] | 156 | |
Finn Bock | 57bc5fa | 2002-11-01 18:02:03 +0000 | [diff] [blame] | 157 | is_jython = sys.platform.startswith('java') |
| 158 | |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 159 | # Filename used for testing |
| 160 | if os.name == 'java': |
| 161 | # Jython disallows @ in module names |
| 162 | TESTFN = '$test' |
Martin v. Löwis | a94568a | 2003-05-10 07:36:56 +0000 | [diff] [blame] | 163 | else: |
Barry Warsaw | 559f668 | 2001-03-23 18:04:02 +0000 | [diff] [blame] | 164 | TESTFN = '@test' |
Walter Dörwald | 9b77553 | 2007-06-08 14:30:53 +0000 | [diff] [blame] | 165 | |
| 166 | # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() |
| 167 | # TESTFN_UNICODE is a filename that can be encoded using the |
| 168 | # file system encoding, but *not* with the default (ascii) encoding |
| 169 | TESTFN_UNICODE = "@test-\xe0\xf2" |
| 170 | TESTFN_ENCODING = sys.getfilesystemencoding() |
| 171 | # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be |
| 172 | # able to be encoded by *either* the default or filesystem encoding. |
| 173 | # This test really only makes sense on Windows NT platforms |
| 174 | # which have special Unicode support in posixmodule. |
| 175 | if (not hasattr(sys, "getwindowsversion") or |
| 176 | sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME |
| 177 | TESTFN_UNICODE_UNENCODEABLE = None |
| 178 | else: |
| 179 | # Japanese characters (I think - from bug 846133) |
| 180 | TESTFN_UNICODE_UNENCODEABLE = "@test-\u5171\u6709\u3055\u308c\u308b" |
| 181 | try: |
| 182 | # XXX - Note - should be using TESTFN_ENCODING here - but for |
| 183 | # Windows, "mbcs" currently always operates as if in |
| 184 | # errors=ignore' mode - hence we get '?' characters rather than |
| 185 | # the exception. 'Latin1' operates as we expect - ie, fails. |
| 186 | # See [ 850997 ] mbcs encoding ignores errors |
| 187 | TESTFN_UNICODE_UNENCODEABLE.encode("Latin1") |
| 188 | except UnicodeEncodeError: |
| 189 | pass |
Martin v. Löwis | 2411a2d | 2002-11-09 19:57:26 +0000 | [diff] [blame] | 190 | else: |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 191 | print('WARNING: The filename %r CAN be encoded by the filesystem. ' |
| 192 | 'Unicode filename tests may not be effective' |
| 193 | % TESTFN_UNICODE_UNENCODEABLE) |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 194 | |
| 195 | # Make sure we can write to TESTFN, try in /tmp if we can't |
| 196 | fp = None |
| 197 | try: |
| 198 | fp = open(TESTFN, 'w+') |
| 199 | except IOError: |
| 200 | TMP_TESTFN = os.path.join('/tmp', TESTFN) |
| 201 | try: |
| 202 | fp = open(TMP_TESTFN, 'w+') |
| 203 | TESTFN = TMP_TESTFN |
| 204 | del TMP_TESTFN |
| 205 | except IOError: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 206 | print(('WARNING: tests will fail, unable to write to: %s or %s' % |
| 207 | (TESTFN, TMP_TESTFN))) |
Neal Norwitz | 26a1eef | 2002-11-03 00:35:53 +0000 | [diff] [blame] | 208 | if fp is not None: |
| 209 | fp.close() |
Neal Norwitz | 0e17f8c | 2006-01-23 07:51:27 +0000 | [diff] [blame] | 210 | unlink(TESTFN) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 211 | del fp |
Guido van Rossum | a8f7e59 | 2001-03-13 09:31:07 +0000 | [diff] [blame] | 212 | |
Guido van Rossum | e26132c | 1998-04-23 20:13:30 +0000 | [diff] [blame] | 213 | def findfile(file, here=__file__): |
Brett Cannon | f1cfb62 | 2003-05-04 21:15:27 +0000 | [diff] [blame] | 214 | """Try to find a file on sys.path and the working directory. If it is not |
| 215 | found the argument passed to the function is returned (this does not |
| 216 | necessarily signal failure; could still be the legitimate path).""" |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 217 | if os.path.isabs(file): |
| 218 | return file |
Fred Drake | 004d5e6 | 2000-10-23 17:22:08 +0000 | [diff] [blame] | 219 | path = sys.path |
| 220 | path = [os.path.dirname(here)] + path |
| 221 | for dn in path: |
| 222 | fn = os.path.join(dn, file) |
| 223 | if os.path.exists(fn): return fn |
| 224 | return file |
Marc-André Lemburg | 3661908 | 2001-01-17 19:11:13 +0000 | [diff] [blame] | 225 | |
| 226 | def verify(condition, reason='test failed'): |
Guido van Rossum | a1374e4 | 2001-01-19 19:01:56 +0000 | [diff] [blame] | 227 | """Verify that condition is true. If not, raise TestFailed. |
Marc-André Lemburg | 3661908 | 2001-01-17 19:11:13 +0000 | [diff] [blame] | 228 | |
Skip Montanaro | c955f89 | 2001-01-20 19:12:54 +0000 | [diff] [blame] | 229 | The optional argument reason can be given to provide |
Tim Peters | 983874d | 2001-01-19 05:59:21 +0000 | [diff] [blame] | 230 | a better error text. |
Tim Peters | d2bf3b7 | 2001-01-18 02:22:22 +0000 | [diff] [blame] | 231 | """ |
Tim Peters | 983874d | 2001-01-19 05:59:21 +0000 | [diff] [blame] | 232 | |
Tim Peters | d2bf3b7 | 2001-01-18 02:22:22 +0000 | [diff] [blame] | 233 | if not condition: |
Guido van Rossum | a1374e4 | 2001-01-19 19:01:56 +0000 | [diff] [blame] | 234 | raise TestFailed(reason) |
Jeremy Hylton | 4779399 | 2001-02-19 15:35:26 +0000 | [diff] [blame] | 235 | |
Tim Peters | c2fe618 | 2001-10-30 23:20:46 +0000 | [diff] [blame] | 236 | def vereq(a, b): |
Tim Peters | 7790297 | 2001-12-29 17:34:57 +0000 | [diff] [blame] | 237 | """Raise TestFailed if a == b is false. |
| 238 | |
| 239 | This is better than verify(a == b) because, in case of failure, the |
| 240 | error message incorporates repr(a) and repr(b) so you can see the |
| 241 | inputs. |
| 242 | |
| 243 | Note that "not (a == b)" isn't necessarily the same as "a != b"; the |
| 244 | former is tested. |
| 245 | """ |
| 246 | |
Tim Peters | c2fe618 | 2001-10-30 23:20:46 +0000 | [diff] [blame] | 247 | if not (a == b): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 248 | raise TestFailed("%r == %r" % (a, b)) |
Tim Peters | c2fe618 | 2001-10-30 23:20:46 +0000 | [diff] [blame] | 249 | |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 250 | def sortdict(dict): |
| 251 | "Like repr(dict), but in sorted order." |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 252 | items = sorted(dict.items()) |
Tim Peters | 2f228e7 | 2001-05-13 00:19:31 +0000 | [diff] [blame] | 253 | reprpairs = ["%r: %r" % pair for pair in items] |
| 254 | withcommas = ", ".join(reprpairs) |
| 255 | return "{%s}" % withcommas |
| 256 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 257 | def check_syntax_error(testcase, statement): |
Jeremy Hylton | 4779399 | 2001-02-19 15:35:26 +0000 | [diff] [blame] | 258 | try: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 259 | compile(statement, '<test string>', 'exec') |
Jeremy Hylton | 4779399 | 2001-02-19 15:35:26 +0000 | [diff] [blame] | 260 | except SyntaxError: |
| 261 | pass |
| 262 | else: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 263 | testcase.fail('Missing SyntaxError: "%s"' % statement) |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 264 | |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 265 | def open_urlresource(url, *args, **kw): |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 266 | import urllib, urlparse |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 267 | |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 268 | requires('urlfetch') |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 269 | filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL! |
| 270 | |
| 271 | for path in [os.path.curdir, os.path.pardir]: |
| 272 | fn = os.path.join(path, filename) |
| 273 | if os.path.exists(fn): |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 274 | return open(fn, *args, **kw) |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 275 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 276 | print('\tfetching %s ...' % url, file=get_original_stdout()) |
Hye-Shik Chang | aaa2f1d | 2005-12-10 17:44:27 +0000 | [diff] [blame] | 277 | fn, _ = urllib.urlretrieve(url, filename) |
Martin v. Löwis | 234a34a | 2007-08-30 20:58:02 +0000 | [diff] [blame] | 278 | return open(fn, *args, **kw) |
Thomas Wouters | 9fe394c | 2007-02-05 01:24:16 +0000 | [diff] [blame] | 279 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 280 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 281 | class WarningMessage(object): |
| 282 | "Holds the result of the latest showwarning() call" |
| 283 | def __init__(self): |
| 284 | self.message = None |
| 285 | self.category = None |
| 286 | self.filename = None |
| 287 | self.lineno = None |
| 288 | |
| 289 | def _showwarning(self, message, category, filename, lineno, file=None): |
| 290 | self.message = message |
| 291 | self.category = category |
| 292 | self.filename = filename |
| 293 | self.lineno = lineno |
| 294 | |
| 295 | @contextlib.contextmanager |
| 296 | def catch_warning(): |
| 297 | """ |
| 298 | Guard the warnings filter from being permanently changed and record the |
| 299 | data of the last warning that has been issued. |
| 300 | |
| 301 | Use like this: |
| 302 | |
Guido van Rossum | af554a0 | 2007-08-16 23:48:43 +0000 | [diff] [blame] | 303 | with catch_warning() as w: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 304 | warnings.warn("foo") |
| 305 | assert str(w.message) == "foo" |
| 306 | """ |
| 307 | warning = WarningMessage() |
| 308 | original_filters = warnings.filters[:] |
| 309 | original_showwarning = warnings.showwarning |
| 310 | warnings.showwarning = warning._showwarning |
| 311 | try: |
| 312 | yield warning |
| 313 | finally: |
| 314 | warnings.showwarning = original_showwarning |
| 315 | warnings.filters = original_filters |
| 316 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 317 | class EnvironmentVarGuard(object): |
| 318 | |
| 319 | """Class to help protect the environment variable properly. Can be used as |
| 320 | a context manager.""" |
| 321 | |
| 322 | def __init__(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 323 | self._environ = os.environ |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 324 | self._unset = set() |
| 325 | self._reset = dict() |
| 326 | |
| 327 | def set(self, envvar, value): |
| 328 | if envvar not in self._environ: |
| 329 | self._unset.add(envvar) |
| 330 | else: |
| 331 | self._reset[envvar] = self._environ[envvar] |
| 332 | self._environ[envvar] = value |
| 333 | |
| 334 | def unset(self, envvar): |
| 335 | if envvar in self._environ: |
| 336 | self._reset[envvar] = self._environ[envvar] |
| 337 | del self._environ[envvar] |
| 338 | |
| 339 | def __enter__(self): |
| 340 | return self |
| 341 | |
| 342 | def __exit__(self, *ignore_exc): |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 343 | for envvar, value in self._reset.items(): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 344 | self._environ[envvar] = value |
| 345 | for unset in self._unset: |
| 346 | del self._environ[unset] |
| 347 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 348 | class TransientResource(object): |
| 349 | |
| 350 | """Raise ResourceDenied if an exception is raised while the context manager |
| 351 | is in effect that matches the specified exception and attributes.""" |
| 352 | |
| 353 | def __init__(self, exc, **kwargs): |
| 354 | self.exc = exc |
| 355 | self.attrs = kwargs |
| 356 | |
| 357 | def __enter__(self): |
| 358 | return self |
| 359 | |
| 360 | def __exit__(self, type_=None, value=None, traceback=None): |
| 361 | """If type_ is a subclass of self.exc and value has attributes matching |
| 362 | self.attrs, raise ResourceDenied. Otherwise let the exception |
| 363 | propagate (if any).""" |
| 364 | if type_ is not None and issubclass(self.exc, type_): |
| 365 | for attr, attr_value in self.attrs.items(): |
| 366 | if not hasattr(value, attr): |
| 367 | break |
| 368 | if getattr(value, attr) != attr_value: |
| 369 | break |
| 370 | else: |
| 371 | raise ResourceDenied("an optional resource is not available") |
| 372 | |
| 373 | |
| 374 | def transient_internet(): |
| 375 | """Return a context manager that raises ResourceDenied when various issues |
| 376 | with the Internet connection manifest themselves as exceptions.""" |
| 377 | time_out = TransientResource(IOError, errno=errno.ETIMEDOUT) |
| 378 | socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET) |
| 379 | ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET) |
| 380 | return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset) |
| 381 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 382 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 383 | @contextlib.contextmanager |
| 384 | def captured_stdout(): |
| 385 | """Run the with statement body using a StringIO object as sys.stdout. |
| 386 | Example use:: |
| 387 | |
| 388 | with captured_stdout() as s: |
| 389 | print "hello" |
| 390 | assert s.getvalue() == "hello" |
| 391 | """ |
| 392 | import io |
| 393 | orig_stdout = sys.stdout |
| 394 | sys.stdout = io.StringIO() |
| 395 | yield sys.stdout |
| 396 | sys.stdout = orig_stdout |
| 397 | |
| 398 | |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 399 | #======================================================================= |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 400 | # Decorator for running a function in a different locale, correctly resetting |
| 401 | # it afterwards. |
| 402 | |
| 403 | def run_with_locale(catstr, *locales): |
| 404 | def decorator(func): |
| 405 | def inner(*args, **kwds): |
| 406 | try: |
| 407 | import locale |
| 408 | category = getattr(locale, catstr) |
| 409 | orig_locale = locale.setlocale(category) |
| 410 | except AttributeError: |
| 411 | # if the test author gives us an invalid category string |
| 412 | raise |
| 413 | except: |
| 414 | # cannot retrieve original locale, so do nothing |
| 415 | locale = orig_locale = None |
| 416 | else: |
| 417 | for loc in locales: |
| 418 | try: |
| 419 | locale.setlocale(category, loc) |
| 420 | break |
| 421 | except: |
| 422 | pass |
| 423 | |
| 424 | # now run the function, resetting the locale on exceptions |
| 425 | try: |
| 426 | return func(*args, **kwds) |
| 427 | finally: |
| 428 | if locale and orig_locale: |
| 429 | locale.setlocale(category, orig_locale) |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 430 | inner.__name__ = func.__name__ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 431 | inner.__doc__ = func.__doc__ |
| 432 | return inner |
| 433 | return decorator |
| 434 | |
| 435 | #======================================================================= |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 436 | # Big-memory-test support. Separate from 'resources' because memory use |
| 437 | # should be configurable. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 438 | |
| 439 | # Some handy shorthands. Note that these are used for byte-limits as well |
| 440 | # as size-limits, in the various bigmem tests |
| 441 | _1M = 1024*1024 |
| 442 | _1G = 1024 * _1M |
| 443 | _2G = 2 * _1G |
| 444 | |
Thomas Wouters | d2cf20e | 2007-08-30 22:57:53 +0000 | [diff] [blame] | 445 | MAX_Py_ssize_t = sys.maxsize |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 446 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 447 | def set_memlimit(limit): |
| 448 | import re |
| 449 | global max_memuse |
| 450 | sizes = { |
| 451 | 'k': 1024, |
| 452 | 'm': _1M, |
| 453 | 'g': _1G, |
| 454 | 't': 1024*_1G, |
| 455 | } |
| 456 | m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit, |
| 457 | re.IGNORECASE | re.VERBOSE) |
| 458 | if m is None: |
| 459 | raise ValueError('Invalid memory limit %r' % (limit,)) |
| 460 | memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()]) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 461 | if memlimit > MAX_Py_ssize_t: |
| 462 | memlimit = MAX_Py_ssize_t |
| 463 | if memlimit < _2G - 1: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 464 | raise ValueError('Memory limit %r too low to be useful' % (limit,)) |
| 465 | max_memuse = memlimit |
| 466 | |
| 467 | def bigmemtest(minsize, memuse, overhead=5*_1M): |
| 468 | """Decorator for bigmem tests. |
| 469 | |
| 470 | 'minsize' is the minimum useful size for the test (in arbitrary, |
| 471 | test-interpreted units.) 'memuse' is the number of 'bytes per size' for |
| 472 | the test, or a good estimate of it. 'overhead' specifies fixed overhead, |
| 473 | independant of the testsize, and defaults to 5Mb. |
| 474 | |
| 475 | The decorator tries to guess a good value for 'size' and passes it to |
| 476 | the decorated test function. If minsize * memuse is more than the |
| 477 | allowed memory use (as defined by max_memuse), the test is skipped. |
| 478 | Otherwise, minsize is adjusted upward to use up to max_memuse. |
| 479 | """ |
| 480 | def decorator(f): |
| 481 | def wrapper(self): |
| 482 | if not max_memuse: |
| 483 | # If max_memuse is 0 (the default), |
| 484 | # we still want to run the tests with size set to a few kb, |
| 485 | # to make sure they work. We still want to avoid using |
| 486 | # too much memory, though, but we do that noisily. |
| 487 | maxsize = 5147 |
| 488 | self.failIf(maxsize * memuse + overhead > 20 * _1M) |
| 489 | else: |
| 490 | maxsize = int((max_memuse - overhead) / memuse) |
| 491 | if maxsize < minsize: |
| 492 | # Really ought to print 'test skipped' or something |
| 493 | if verbose: |
| 494 | sys.stderr.write("Skipping %s because of memory " |
| 495 | "constraint\n" % (f.__name__,)) |
| 496 | return |
| 497 | # Try to keep some breathing room in memory use |
| 498 | maxsize = max(maxsize - 50 * _1M, minsize) |
| 499 | return f(self, maxsize) |
| 500 | wrapper.minsize = minsize |
| 501 | wrapper.memuse = memuse |
| 502 | wrapper.overhead = overhead |
| 503 | return wrapper |
| 504 | return decorator |
| 505 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 506 | def bigaddrspacetest(f): |
| 507 | """Decorator for tests that fill the address space.""" |
| 508 | def wrapper(self): |
| 509 | if max_memuse < MAX_Py_ssize_t: |
| 510 | if verbose: |
| 511 | sys.stderr.write("Skipping %s because of memory " |
| 512 | "constraint\n" % (f.__name__,)) |
| 513 | else: |
| 514 | return f(self) |
| 515 | return wrapper |
| 516 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 517 | #======================================================================= |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 518 | # unittest integration. |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 519 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 520 | class BasicTestRunner: |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 521 | def run(self, test): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 522 | result = unittest.TestResult() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 523 | test(result) |
| 524 | return result |
| 525 | |
| 526 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 527 | def _run_suite(suite): |
Barry Warsaw | c88425e | 2001-09-20 06:31:22 +0000 | [diff] [blame] | 528 | """Run tests from a unittest.TestSuite-derived class.""" |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 529 | if verbose: |
Fred Drake | 84a5934 | 2001-03-23 04:21:17 +0000 | [diff] [blame] | 530 | runner = unittest.TextTestRunner(sys.stdout, verbosity=2) |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 531 | else: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 532 | runner = BasicTestRunner() |
Fred Drake | cd1b1dd | 2001-03-21 18:26:33 +0000 | [diff] [blame] | 533 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 534 | result = runner.run(suite) |
| 535 | if not result.wasSuccessful(): |
Fred Drake | 14f6c18 | 2001-07-16 18:51:32 +0000 | [diff] [blame] | 536 | if len(result.errors) == 1 and not result.failures: |
| 537 | err = result.errors[0][1] |
| 538 | elif len(result.failures) == 1 and not result.errors: |
| 539 | err = result.failures[0][1] |
| 540 | else: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 541 | err = "errors occurred; run in verbose mode for details" |
Tim Peters | 2d84f2c | 2001-09-08 03:37:56 +0000 | [diff] [blame] | 542 | raise TestFailed(err) |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 543 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 544 | |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 545 | def run_unittest(*classes): |
| 546 | """Run tests from unittest.TestCase-derived classes.""" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 547 | valid_types = (unittest.TestSuite, unittest.TestCase) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 548 | suite = unittest.TestSuite() |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 549 | for cls in classes: |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 550 | if isinstance(cls, str): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 551 | if cls in sys.modules: |
| 552 | suite.addTest(unittest.findTestCases(sys.modules[cls])) |
| 553 | else: |
| 554 | raise ValueError("str arguments must be keys in sys.modules") |
| 555 | elif isinstance(cls, valid_types): |
Raymond Hettinger | 21d9987 | 2003-07-16 02:59:32 +0000 | [diff] [blame] | 556 | suite.addTest(cls) |
| 557 | else: |
| 558 | suite.addTest(unittest.makeSuite(cls)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 559 | _run_suite(suite) |
Raymond Hettinger | 9dcbbea | 2003-04-27 07:54:23 +0000 | [diff] [blame] | 560 | |
Barry Warsaw | c10d690 | 2001-09-20 06:30:41 +0000 | [diff] [blame] | 561 | |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 562 | #======================================================================= |
| 563 | # doctest driver. |
| 564 | |
| 565 | def run_doctest(module, verbosity=None): |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 566 | """Run doctest on the given module. Return (#failures, #tests). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 567 | |
| 568 | If optional argument verbosity is not specified (or is None), pass |
Tim Peters | bea3fb8 | 2001-09-10 01:39:21 +0000 | [diff] [blame] | 569 | test_support's belief about verbosity on to doctest. Else doctest's |
| 570 | usual behavior is used (it searches sys.argv for -v). |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 571 | """ |
| 572 | |
| 573 | import doctest |
| 574 | |
| 575 | if verbosity is None: |
| 576 | verbosity = verbose |
| 577 | else: |
| 578 | verbosity = None |
| 579 | |
Tim Peters | 342ca75 | 2001-09-25 19:13:20 +0000 | [diff] [blame] | 580 | # Direct doctest output (normally just errors) to real stdout; doctest |
| 581 | # output shouldn't be compared by regrtest. |
| 582 | save_stdout = sys.stdout |
Tim Peters | 8dee809 | 2001-09-25 20:05:11 +0000 | [diff] [blame] | 583 | sys.stdout = get_original_stdout() |
Tim Peters | 342ca75 | 2001-09-25 19:13:20 +0000 | [diff] [blame] | 584 | try: |
| 585 | f, t = doctest.testmod(module, verbose=verbosity) |
| 586 | if f: |
| 587 | raise TestFailed("%d of %d doctests failed" % (f, t)) |
| 588 | finally: |
| 589 | sys.stdout = save_stdout |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 590 | if verbose: |
Georg Brandl | db02844 | 2008-02-05 20:48:58 +0000 | [diff] [blame] | 591 | print('doctest (%s) ... %d tests with zero failures' % |
| 592 | (module.__name__, t)) |
Raymond Hettinger | 35b34bd | 2003-05-17 00:58:33 +0000 | [diff] [blame] | 593 | return f, t |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 594 | |
| 595 | #======================================================================= |
| 596 | # Threading support to prevent reporting refleaks when running regrtest.py -R |
| 597 | |
| 598 | def threading_setup(): |
| 599 | import threading |
| 600 | return len(threading._active), len(threading._limbo) |
| 601 | |
| 602 | def threading_cleanup(num_active, num_limbo): |
| 603 | import threading |
| 604 | import time |
| 605 | |
| 606 | _MAX_COUNT = 10 |
| 607 | count = 0 |
| 608 | while len(threading._active) != num_active and count < _MAX_COUNT: |
| 609 | count += 1 |
| 610 | time.sleep(0.1) |
| 611 | |
| 612 | count = 0 |
| 613 | while len(threading._limbo) != num_limbo and count < _MAX_COUNT: |
| 614 | count += 1 |
| 615 | time.sleep(0.1) |
| 616 | |
| 617 | def reap_children(): |
| 618 | """Use this function at the end of test_main() whenever sub-processes |
| 619 | are started. This will help ensure that no extra children (zombies) |
| 620 | stick around to hog resources and create problems when looking |
| 621 | for refleaks. |
| 622 | """ |
| 623 | |
| 624 | # Reap all our dead child processes so we don't leave zombies around. |
| 625 | # 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] | 626 | if hasattr(os, 'waitpid'): |
| 627 | any_process = -1 |
| 628 | while True: |
| 629 | try: |
| 630 | # This will raise an exception on Windows. That's ok. |
| 631 | pid, status = os.waitpid(any_process, os.WNOHANG) |
| 632 | if pid == 0: |
| 633 | break |
| 634 | except: |
| 635 | break |