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