0001 """Supporting definitions for the Python regression tests.""" 0002 0003 if __name__ != 'test.test_support': 0004 raise ImportError, 'test_support must be imported from the test package' 0005 0006 import sys 0007 0008 class Error(Exception): 0009 """Base class for regression test exceptions.""" 0010 0011 class TestFailed(Error): 0012 """Test failed.""" 0013 0014 class TestSkipped(Error): 0015 """Test skipped. 0016 0017 This can be raised to indicate that a test was deliberatly 0018 skipped, but not because a feature wasn't available. For 0019 example, if some resource can't be used, such as the network 0020 appears to be unavailable, this should be raised instead of 0021 TestFailed. 0022 """ 0023 0024 class ResourceDenied(TestSkipped): 0025 """Test skipped because it requested a disallowed resource. 0026 0027 This is raised when a test calls requires() for a resource that 0028 has not be enabled. It is used to distinguish between expected 0029 and unexpected skips. 0030 """ 0031 0032 verbose = 1 # Flag set to 0 by regrtest.py 0033 use_resources = None # Flag set to [] by regrtest.py 0034 0035 # _original_stdout is meant to hold stdout at the time regrtest began. 0036 # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. 0037 # The point is to have some flavor of stdout the user can actually see. 0038 _original_stdout = None 0039 def record_original_stdout(stdout): 0040 global _original_stdout 0041 _original_stdout = stdout 0042 0043 def get_original_stdout(): 0044 return _original_stdout or sys.stdout 0045 0046 def unload(name): 0047 try: 0048 del sys.modules[name] 0049 except KeyError: 0050 pass 0051 0052 def forget(modname): 0053 '''"Forget" a module was ever imported by removing it from sys.modules and 0054 deleting any .pyc and .pyo files.''' 0055 unload(modname) 0056 import os 0057 for dirname in sys.path: 0058 try: 0059 os.unlink(os.path.join(dirname, modname + os.extsep + 'pyc')) 0060 except os.error: 0061 pass 0062 # Deleting the .pyo file cannot be within the 'try' for the .pyc since 0063 # the chance exists that there is no .pyc (and thus the 'try' statement 0064 # is exited) but there is a .pyo file. 0065 try: 0066 os.unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) 0067 except os.error: 0068 pass 0069 0070 def is_resource_enabled(resource): 0071 """Test whether a resource is enabled. Known resources are set by 0072 regrtest.py.""" 0073 return use_resources is not None and resource in use_resources 0074 0075 def requires(resource, msg=None): 0076 """Raise ResourceDenied if the specified resource is not available. 0077 0078 If the caller's module is __main__ then automatically return True. The 0079 possibility of False being returned occurs when regrtest.py is executing.""" 0080 # see if the caller's module is __main__ - if so, treat as if 0081 # the resource was set 0082 if sys._getframe().f_back.f_globals.get("__name__") == "__main__": 0083 return 0084 if not is_resource_enabled(resource): 0085 if msg is None: 0086 msg = "Use of the `%s' resource not enabled" % resource 0087 raise ResourceDenied(msg) 0088 0089 FUZZ = 1e-6 0090 0091 def fcmp(x, y): # fuzzy comparison function 0092 if type(x) == type(0.0) or type(y) == type(0.0): 0093 try: 0094 x, y = coerce(x, y) 0095 fuzz = (abs(x) + abs(y)) * FUZZ 0096 if abs(x-y) <= fuzz: 0097 return 0 0098 except: 0099 pass 0100 elif type(x) == type(y) and type(x) in (type(()), type([])): 0101 for i in range(min(len(x), len(y))): 0102 outcome = fcmp(x[i], y[i]) 0103 if outcome != 0: 0104 return outcome 0105 return cmp(len(x), len(y)) 0106 return cmp(x, y) 0107 0108 try: 0109 unicode 0110 have_unicode = 1 0111 except NameError: 0112 have_unicode = 0 0113 0114 is_jython = sys.platform.startswith('java') 0115 0116 import os 0117 # Filename used for testing 0118 if os.name == 'java': 0119 # Jython disallows @ in module names 0120 TESTFN = '$test' 0121 elif os.name == 'riscos': 0122 TESTFN = 'testfile' 0123 else: 0124 TESTFN = '@test' 0125 # Unicode name only used if TEST_FN_ENCODING exists for the platform. 0126 if have_unicode: 0127 # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() 0128 # TESTFN_UNICODE is a filename that can be encoded using the 0129 # file system encoding, but *not* with the default (ascii) encoding 0130 if isinstance('', unicode): 0131 # python -U 0132 # XXX perhaps unicode() should accept Unicode strings? 0133 TESTFN_UNICODE = "@test-\xe0\xf2" 0134 else: 0135 # 2 latin characters. 0136 TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1") 0137 TESTFN_ENCODING = sys.getfilesystemencoding() 0138 # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be 0139 # able to be encoded by *either* the default or filesystem encoding. 0140 # This test really only makes sense on Windows NT platforms 0141 # which have special Unicode support in posixmodule. 0142 if (not hasattr(sys, "getwindowsversion") or 0143 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME 0144 TESTFN_UNICODE_UNENCODEABLE = None 0145 else: 0146 # Japanese characters (I think - from bug 846133) 0147 TESTFN_UNICODE_UNENCODEABLE = u"@test-\u5171\u6709\u3055\u308c\u308b" 0148 try: 0149 # XXX - Note - should be using TESTFN_ENCODING here - but for 0150 # Windows, "mbcs" currently always operates as if in 0151 # errors=ignore' mode - hence we get '?' characters rather than 0152 # the exception. 'Latin1' operates as we expect - ie, fails. 0153 # See [ 850997 ] mbcs encoding ignores errors 0154 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1") 0155 except UnicodeEncodeError: 0156 pass 0157 else: 0158 print \ 0159 'WARNING: The filename %r CAN be encoded by the filesystem. ' \ 0160 'Unicode filename tests may not be effective' \ 0161 % TESTFN_UNICODE_UNENCODEABLE 0162 0163 # Make sure we can write to TESTFN, try in /tmp if we can't 0164 fp = None 0165 try: 0166 fp = open(TESTFN, 'w+') 0167 except IOError: 0168 TMP_TESTFN = os.path.join('/tmp', TESTFN) 0169 try: 0170 fp = open(TMP_TESTFN, 'w+') 0171 TESTFN = TMP_TESTFN 0172 del TMP_TESTFN 0173 except IOError: 0174 print ('WARNING: tests will fail, unable to write to: %s or %s' % 0175 (TESTFN, TMP_TESTFN)) 0176 if fp is not None: 0177 fp.close() 0178 try: 0179 os.unlink(TESTFN) 0180 except: 0181 pass 0182 del os, fp 0183 0184 from os import unlink 0185 0186 def findfile(file, here=__file__): 0187 """Try to find a file on sys.path and the working directory. If it is not 0188 found the argument passed to the function is returned (this does not 0189 necessarily signal failure; could still be the legitimate path).""" 0190 import os 0191 if os.path.isabs(file): 0192 return file 0193 path = sys.path 0194 path = [os.path.dirname(here)] + path 0195 for dn in path: 0196 fn = os.path.join(dn, file) 0197 if os.path.exists(fn): return fn 0198 return file 0199 0200 def verify(condition, reason='test failed'): 0201 """Verify that condition is true. If not, raise TestFailed. 0202 0203 The optional argument reason can be given to provide 0204 a better error text. 0205 """ 0206 0207 if not condition: 0208 raise TestFailed(reason) 0209 0210 def vereq(a, b): 0211 """Raise TestFailed if a == b is false. 0212 0213 This is better than verify(a == b) because, in case of failure, the 0214 error message incorporates repr(a) and repr(b) so you can see the 0215 inputs. 0216 0217 Note that "not (a == b)" isn't necessarily the same as "a != b"; the 0218 former is tested. 0219 """ 0220 0221 if not (a == b): 0222 raise TestFailed, "%r == %r" % (a, b) 0223 0224 def sortdict(dict): 0225 "Like repr(dict), but in sorted order." 0226 items = dict.items() 0227 items.sort() 0228 reprpairs = ["%r: %r" % pair for pair in items] 0229 withcommas = ", ".join(reprpairs) 0230 return "{%s}" % withcommas 0231 0232 def check_syntax(statement): 0233 try: 0234 compile(statement, '<string>', 'exec') 0235 except SyntaxError: 0236 pass 0237 else: 0238 print 'Missing SyntaxError: "%s"' % statement 0239 0240 0241 0242 #======================================================================= 0243 # Preliminary PyUNIT integration. 0244 0245 import unittest 0246 0247 0248 class BasicTestRunner: 0249 def run(self, test): 0250 result = unittest.TestResult() 0251 test(result) 0252 return result 0253 0254 0255 def run_suite(suite, testclass=None): 0256 """Run tests from a unittest.TestSuite-derived class.""" 0257 if verbose: 0258 runner = unittest.TextTestRunner(sys.stdout, verbosity=2) 0259 else: 0260 runner = BasicTestRunner() 0261 0262 result = runner.run(suite) 0263 if not result.wasSuccessful(): 0264 if len(result.errors) == 1 and not result.failures: 0265 err = result.errors[0][1] 0266 elif len(result.failures) == 1 and not result.errors: 0267 err = result.failures[0][1] 0268 else: 0269 if testclass is None: 0270 msg = "errors occurred; run in verbose mode for details" 0271 else: 0272 msg = "errors occurred in %s.%s" \ 0273 % (testclass.__module__, testclass.__name__) 0274 raise TestFailed(msg) 0275 raise TestFailed(err) 0276 0277 0278 def run_unittest(*classes): 0279 """Run tests from unittest.TestCase-derived classes.""" 0280 suite = unittest.TestSuite() 0281 for cls in classes: 0282 if isinstance(cls, (unittest.TestSuite, unittest.TestCase)): 0283 suite.addTest(cls) 0284 else: 0285 suite.addTest(unittest.makeSuite(cls)) 0286 if len(classes)==1: 0287 testclass = classes[0] 0288 else: 0289 testclass = None 0290 run_suite(suite, testclass) 0291 0292 0293 #======================================================================= 0294 # doctest driver. 0295 0296 def run_doctest(module, verbosity=None): 0297 """Run doctest on the given module. Return (#failures, #tests). 0298 0299 If optional argument verbosity is not specified (or is None), pass 0300 test_support's belief about verbosity on to doctest. Else doctest's 0301 usual behavior is used (it searches sys.argv for -v). 0302 """ 0303 0304 import doctest 0305 0306 if verbosity is None: 0307 verbosity = verbose 0308 else: 0309 verbosity = None 0310 0311 # Direct doctest output (normally just errors) to real stdout; doctest 0312 # output shouldn't be compared by regrtest. 0313 save_stdout = sys.stdout 0314 sys.stdout = get_original_stdout() 0315 try: 0316 f, t = doctest.testmod(module, verbose=verbosity) 0317 if f: 0318 raise TestFailed("%d of %d doctests failed" % (f, t)) 0319 finally: 0320 sys.stdout = save_stdout 0321 if verbose: 0322 print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t) 0323 return f, t 0324
Generated by PyXR 0.9.4