Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(4431)

Delta Between Two Patch Sets: Lib/test/support.py

Issue 12231: regrtest: add -k and -K options to filter tests by function/file names
Left Patch Set: Created 1 year, 11 months ago
Right Patch Set: Created 1 year, 10 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/regrtest.py ('k') | Lib/unittest/loader.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 """Supporting definitions for the Python regression tests.""" 1 """Supporting definitions for the Python regression tests."""
2 2
3 if __name__ != 'test.support': 3 if __name__ != 'test.support':
4 raise ImportError('support must be imported from the test package') 4 raise ImportError('support must be imported from the test package')
5 5
6 import contextlib 6 import contextlib
7 import errno 7 import errno
8 import functools 8 import functools
9 import gc 9 import gc
10 import socket 10 import socket
(...skipping 19 matching lines...) Expand all
30 30
31 try: 31 try:
32 import zlib 32 import zlib
33 except ImportError: 33 except ImportError:
34 zlib = None 34 zlib = None
35 35
36 __all__ = [ 36 __all__ = [
37 "Error", "TestFailed", "ResourceDenied", "import_module", 37 "Error", "TestFailed", "ResourceDenied", "import_module",
38 "verbose", "use_resources", "max_memuse", "record_original_stdout", 38 "verbose", "use_resources", "max_memuse", "record_original_stdout",
39 "get_original_stdout", "unload", "unlink", "rmtree", "forget", 39 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
40 "is_resource_enabled", "requires", "find_unused_port", "bind_port", 40 "is_resource_enabled", "requires", "requires_linux_version",
41 "requires_mac_ver", "find_unused_port", "bind_port",
41 "IPV6_ENABLED", "is_jython", "TESTFN", "HOST", "SAVEDCWD", "temp_cwd", 42 "IPV6_ENABLED", "is_jython", "TESTFN", "HOST", "SAVEDCWD", "temp_cwd",
42 "findfile", "sortdict", "check_syntax_error", "open_urlresource", 43 "findfile", "create_empty_file", "sortdict", "check_syntax_error", "open_url resource",
43 "check_warnings", "CleanImport", "EnvironmentVarGuard", "TransientResource", 44 "check_warnings", "CleanImport", "EnvironmentVarGuard", "TransientResource",
44 "captured_stdout", "captured_stdin", "captured_stderr", "time_out", 45 "captured_stdout", "captured_stdin", "captured_stderr", "time_out",
45 "socket_peer_reset", "ioerror_peer_reset", "run_with_locale", 'temp_umask', 46 "socket_peer_reset", "ioerror_peer_reset", "run_with_locale", 'temp_umask',
46 "transient_internet", "set_memlimit", "bigmemtest", "bigaddrspacetest", 47 "transient_internet", "set_memlimit", "bigmemtest", "bigaddrspacetest",
47 "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup", 48 "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
48 "threading_cleanup", "reap_children", "cpython_only", "check_impl_detail", 49 "threading_cleanup", "reap_children", "cpython_only", "check_impl_detail",
49 "get_attribute", "swap_item", "swap_attr", "requires_IEEE_754", 50 "get_attribute", "swap_item", "swap_attr", "requires_IEEE_754",
50 "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink", 51 "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink",
51 "import_fresh_module", "requires_zlib", "PIPE_MAX_SIZE" 52 "import_fresh_module", "requires_zlib", "PIPE_MAX_SIZE"
52 ] 53 ]
(...skipping 231 matching lines...) Expand 10 before | Expand all | Expand 10 after
284 raise unittest.SkipTest("Cannot use the 'gui' resource") 285 raise unittest.SkipTest("Cannot use the 'gui' resource")
285 # see if the caller's module is __main__ - if so, treat as if 286 # see if the caller's module is __main__ - if so, treat as if
286 # the resource was set 287 # the resource was set
287 if sys._getframe(1).f_globals.get("__name__") == "__main__": 288 if sys._getframe(1).f_globals.get("__name__") == "__main__":
288 return 289 return
289 if not is_resource_enabled(resource): 290 if not is_resource_enabled(resource):
290 if msg is None: 291 if msg is None:
291 msg = "Use of the `%s' resource not enabled" % resource 292 msg = "Use of the `%s' resource not enabled" % resource
292 raise ResourceDenied(msg) 293 raise ResourceDenied(msg)
293 294
294 def linux_version(): 295 def requires_linux_version(*min_version):
295 try: 296 """Decorator raising SkipTest if the OS is Linux and the kernel version is
296 # platform.release() is something like '2.6.33.7-desktop-2mnb' 297 less than min_version.
297 version_string = platform.release().split('-')[0] 298
298 return tuple(map(int, version_string.split('.'))) 299 For example, @requires_linux_version(2, 6, 35) raises SkipTest if the Linux
299 except ValueError: 300 kernel version is less than 2.6.35.
300 return 0, 0, 0 301 """
302 def decorator(func):
303 @functools.wraps(func)
304 def wrapper(*args, **kw):
305 if sys.platform.startswith('linux'):
306 version_txt = platform.release().split('-', 1)[0]
307 try:
308 version = tuple(map(int, version_txt.split('.')))
309 except ValueError:
310 pass
311 else:
312 if version < min_version:
313 min_version_txt = '.'.join(map(str, min_version))
314 raise unittest.SkipTest(
315 "Linux kernel %s or higher required, not %s"
316 % (min_version_txt, version_txt))
317 return func(*args, **kw)
318 wrapper.min_version = min_version
319 return wrapper
320 return decorator
321
322 def requires_mac_ver(*min_version):
323 """Decorator raising SkipTest if the OS is Mac OS X and the OS X
324 version if less than min_version.
325
326 For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
327 is lesser than 10.5.
328 """
329 def decorator(func):
330 @functools.wraps(func)
331 def wrapper(*args, **kw):
332 if sys.platform == 'darwin':
333 version_txt = platform.mac_ver()[0]
334 try:
335 version = tuple(map(int, version_txt.split('.')))
336 except ValueError:
337 pass
338 else:
339 if version < min_version:
340 min_version_txt = '.'.join(map(str, min_version))
341 raise unittest.SkipTest(
342 "Mac OS X %s or higher required, not %s"
343 % (min_version_txt, version_txt))
344 return func(*args, **kw)
345 wrapper.min_version = min_version
346 return wrapper
347 return decorator
348
301 349
302 HOST = 'localhost' 350 HOST = 'localhost'
303 351
304 def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): 352 def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
305 """Returns an unused port that should be suitable for binding. This is 353 """Returns an unused port that should be suitable for binding. This is
306 achieved by creating a temporary socket with the same family and type as 354 achieved by creating a temporary socket with the same family and type as
307 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to 355 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
308 the specified host address (defaults to 0.0.0.0) with the port set to 0, 356 the specified host address (defaults to 0.0.0.0) with the port set to 0,
309 eliciting an unused ephemeral port from the OS. The temporary socket is 357 eliciting an unused ephemeral port from the OS. The temporary socket is
310 then closed and deleted, and the ephemeral port is returned. 358 then closed and deleted, and the ephemeral port is returned.
(...skipping 230 matching lines...) Expand 10 before | Expand all | Expand 10 after
541 return file 589 return file
542 if subdir is not None: 590 if subdir is not None:
543 file = os.path.join(subdir, file) 591 file = os.path.join(subdir, file)
544 path = sys.path 592 path = sys.path
545 path = [os.path.dirname(here)] + path 593 path = [os.path.dirname(here)] + path
546 for dn in path: 594 for dn in path:
547 fn = os.path.join(dn, file) 595 fn = os.path.join(dn, file)
548 if os.path.exists(fn): return fn 596 if os.path.exists(fn): return fn
549 return file 597 return file
550 598
599 def create_empty_file(filename):
600 """Create an empty file. If the file already exists, truncate it."""
601 fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
602 os.close(fd)
603
551 def sortdict(dict): 604 def sortdict(dict):
552 "Like repr(dict), but in sorted order." 605 "Like repr(dict), but in sorted order."
553 items = sorted(dict.items()) 606 items = sorted(dict.items())
554 reprpairs = ["%r: %r" % pair for pair in items] 607 reprpairs = ["%r: %r" % pair for pair in items]
555 withcommas = ", ".join(reprpairs) 608 withcommas = ", ".join(reprpairs)
556 return "{%s}" % withcommas 609 return "{%s}" % withcommas
557 610
558 def make_bad_fd(): 611 def make_bad_fd():
559 """ 612 """
560 Create an invalid file descriptor by opening and closing a file and return 613 Create an invalid file descriptor by opening and closing a file and return
(...skipping 691 matching lines...) Expand 10 before | Expand all | Expand 10 after
1252 usual behavior is used (it searches sys.argv for -v). 1305 usual behavior is used (it searches sys.argv for -v).
1253 """ 1306 """
1254 1307
1255 import doctest 1308 import doctest
1256 1309
1257 if verbosity is None: 1310 if verbosity is None:
1258 verbosity = verbose 1311 verbosity = verbose
1259 else: 1312 else:
1260 verbosity = None 1313 verbosity = None
1261 1314
1262 # Direct doctest output (normally just errors) to real stdout; doctest 1315 f, t = doctest.testmod(module, verbose=verbosity)
1263 # output shouldn't be compared by regrtest. 1316 if f:
1264 save_stdout = sys.stdout 1317 raise TestFailed("%d of %d doctests failed" % (f, t))
1265 sys.stdout = get_original_stdout()
1266 try:
1267 f, t = doctest.testmod(module, verbose=verbosity)
1268 if f:
1269 raise TestFailed("%d of %d doctests failed" % (f, t))
1270 finally:
1271 sys.stdout = save_stdout
1272 if verbose: 1318 if verbose:
1273 print('doctest (%s) ... %d tests with zero failures' % 1319 print('doctest (%s) ... %d tests with zero failures' %
1274 (module.__name__, t)) 1320 (module.__name__, t))
1275 return f, t 1321 return f, t
1276 1322
1277 1323
1278 #======================================================================= 1324 #=======================================================================
1279 # Support for saving and restoring the imported modules. 1325 # Support for saving and restoring the imported modules.
1280 1326
1281 def modules_setup(): 1327 def modules_setup():
(...skipping 233 matching lines...) Expand 10 before | Expand all | Expand 10 after
1515 1561
1516 _can_symlink = None 1562 _can_symlink = None
1517 def can_symlink(): 1563 def can_symlink():
1518 global _can_symlink 1564 global _can_symlink
1519 if _can_symlink is not None: 1565 if _can_symlink is not None:
1520 return _can_symlink 1566 return _can_symlink
1521 symlink_path = TESTFN + "can_symlink" 1567 symlink_path = TESTFN + "can_symlink"
1522 try: 1568 try:
1523 os.symlink(TESTFN, symlink_path) 1569 os.symlink(TESTFN, symlink_path)
1524 can = True 1570 can = True
1571 except (OSError, NotImplementedError, AttributeError):
1572 can = False
1573 else:
1525 os.remove(symlink_path) 1574 os.remove(symlink_path)
1526 except (OSError, NotImplementedError):
1527 can = False
1528 _can_symlink = can 1575 _can_symlink = can
1529 return can 1576 return can
1530 1577
1531 def skip_unless_symlink(test): 1578 def skip_unless_symlink(test):
1532 """Skip decorator for tests that require functional symlink""" 1579 """Skip decorator for tests that require functional symlink"""
1533 ok = can_symlink() 1580 ok = can_symlink()
1534 msg = "Requires functional symlink implementation" 1581 msg = "Requires functional symlink implementation"
1535 return test if ok else unittest.skip(msg)(test) 1582 return test if ok else unittest.skip(msg)(test)
1536 1583
1537 def patch(test_instance, object_to_patch, attr_name, new_value): 1584 def patch(test_instance, object_to_patch, attr_name, new_value):
(...skipping 21 matching lines...) Expand all
1559 def cleanup(): 1606 def cleanup():
1560 if attr_is_local: 1607 if attr_is_local:
1561 setattr(object_to_patch, attr_name, old_value) 1608 setattr(object_to_patch, attr_name, old_value)
1562 else: 1609 else:
1563 delattr(object_to_patch, attr_name) 1610 delattr(object_to_patch, attr_name)
1564 1611
1565 test_instance.addCleanup(cleanup) 1612 test_instance.addCleanup(cleanup)
1566 1613
1567 # actually override the attribute 1614 # actually override the attribute
1568 setattr(object_to_patch, attr_name, new_value) 1615 setattr(object_to_patch, attr_name, new_value)
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld cbc36f91f3f7