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