blob: 1d0f11f0472ae52d2199930a035dda2aee03d614 [file] [log] [blame]
Brett Cannonf1cfb622003-05-04 21:15:27 +00001"""Supporting definitions for the Python regression tests."""
Guido van Rossum3bead091992-01-27 17:00:37 +00002
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003if __name__ != 'test.support':
4 raise ImportError('support must be imported from the test package')
Barry Warsaw408b6d32002-07-30 23:27:12 +00005
Victor Stinner47ae7632014-07-21 21:40:19 +02006import collections.abc
Guido van Rossumd8faa362007-04-27 19:54:29 +00007import contextlib
8import errno
Serhiy Storchaka263dcd22015-04-01 13:01:14 +03009import faulthandler
Victor Stinner47ae7632014-07-21 21:40:19 +020010import fnmatch
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000011import functools
Benjamin Peterson8cc7d882009-06-01 23:14:51 +000012import gc
R. David Murraya21e4ca2009-03-31 23:16:50 +000013import importlib
Brett Cannon9529fbf2013-06-15 17:11:25 -040014import importlib.util
Vinay Sajip129fd042010-12-10 08:19:38 +000015import logging.handlers
Berker Peksag52c0c332015-04-08 11:24:27 +030016import nntplib
Victor Stinner47ae7632014-07-21 21:40:19 +020017import os
18import platform
19import re
20import shutil
21import socket
22import stat
Antoine Pitrou75e78b62011-10-04 11:51:23 +020023import struct
Victor Stinner47ae7632014-07-21 21:40:19 +020024import subprocess
25import sys
26import sysconfig
Hynek Schlawacke02ba102012-05-23 11:22:44 +020027import tempfile
Victor Stinner47ae7632014-07-21 21:40:19 +020028import time
29import unittest
Berker Peksag8b63d3a2014-10-25 05:42:30 +030030import urllib.error
Victor Stinner47ae7632014-07-21 21:40:19 +020031import warnings
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000032
Victor Stinner45df8202010-04-28 22:31:17 +000033try:
Antoine Pitrou707f2282011-07-15 22:29:44 +020034 import _thread, threading
Brett Cannon260fbe82013-07-04 18:16:15 -040035except ImportError:
Victor Stinner45df8202010-04-28 22:31:17 +000036 _thread = None
Antoine Pitrou707f2282011-07-15 22:29:44 +020037 threading = None
38try:
39 import multiprocessing.process
Brett Cannon260fbe82013-07-04 18:16:15 -040040except ImportError:
Antoine Pitrou707f2282011-07-15 22:29:44 +020041 multiprocessing = None
42
Antoine Pitrou75e78b62011-10-04 11:51:23 +020043try:
Ezio Melotticad648c2011-05-19 21:25:10 +030044 import zlib
Brett Cannon260fbe82013-07-04 18:16:15 -040045except ImportError:
Ezio Melotticad648c2011-05-19 21:25:10 +030046 zlib = None
47
Martin v. Löwisf6b16a42012-05-01 07:58:44 +020048try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +030049 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040050except ImportError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +030051 gzip = None
52
53try:
Martin v. Löwisf6b16a42012-05-01 07:58:44 +020054 import bz2
Brett Cannon260fbe82013-07-04 18:16:15 -040055except ImportError:
Martin v. Löwisf6b16a42012-05-01 07:58:44 +020056 bz2 = None
57
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +020058try:
59 import lzma
Brett Cannon260fbe82013-07-04 18:16:15 -040060except ImportError:
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +020061 lzma = None
62
Antoine Pitroub0478b32013-09-06 20:50:00 +020063try:
64 import resource
65except ImportError:
66 resource = None
67
Barry Warsaw28a691b2010-04-17 00:19:56 +000068__all__ = [
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010069 # globals
70 "PIPE_MAX_SIZE", "verbose", "max_memuse", "use_resources", "failfast",
71 # exceptions
72 "Error", "TestFailed", "ResourceDenied",
73 # imports
74 "import_module", "import_fresh_module", "CleanImport",
75 # modules
76 "unload", "forget",
77 # io
78 "record_original_stdout", "get_original_stdout", "captured_stdout",
79 "captured_stdin", "captured_stderr",
80 # filesystem
81 "TESTFN", "SAVEDCWD", "unlink", "rmtree", "temp_cwd", "findfile",
Brett Cannonfe77f4e2013-11-22 16:14:10 -050082 "create_empty_file", "can_symlink", "fs_is_case_insensitive",
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010083 # unittest
Charles-François Natali87b3c922011-10-03 19:40:37 +020084 "is_resource_enabled", "requires", "requires_freebsd_version",
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010085 "requires_linux_version", "requires_mac_ver", "check_syntax_error",
86 "TransientResource", "time_out", "socket_peer_reset", "ioerror_peer_reset",
87 "transient_internet", "BasicTestRunner", "run_unittest", "run_doctest",
88 "skip_unless_symlink", "requires_gzip", "requires_bz2", "requires_lzma",
89 "bigmemtest", "bigaddrspacetest", "cpython_only", "get_attribute",
90 "requires_IEEE_754", "skip_unless_xattr", "requires_zlib",
Zachary Waref012ba42014-07-23 12:00:29 -050091 "anticipate_failure", "load_package_tests",
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010092 # sys
93 "is_jython", "check_impl_detail",
94 # network
95 "HOST", "IPV6_ENABLED", "find_unused_port", "bind_port", "open_urlresource",
96 # processes
97 'temp_umask', "reap_children",
98 # logging
99 "TestHandler",
100 # threads
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300101 "threading_setup", "threading_cleanup", "reap_threads", "start_threads",
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +0100102 # miscellaneous
103 "check_warnings", "EnvironmentVarGuard", "run_with_locale", "swap_item",
104 "swap_attr", "Matcher", "set_memlimit", "SuppressCrashReport", "sortdict",
105 "run_with_tz",
Antoine Pitrou4d7979b2010-09-07 21:22:56 +0000106 ]
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000107
Fred Drake1790dd42000-07-24 06:55:00 +0000108class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +0000109 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +0000110
111class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +0000112 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +0000113
Benjamin Petersone549ead2009-03-28 21:42:05 +0000114class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +0000115 """Test skipped because it requested a disallowed resource.
116
117 This is raised when a test calls requires() for a resource that
118 has not be enabled. It is used to distinguish between expected
119 and unexpected skips.
120 """
121
Nick Coghlanfce769e2009-04-11 14:30:59 +0000122@contextlib.contextmanager
123def _ignore_deprecated_imports(ignore=True):
124 """Context manager to suppress package and module deprecation
125 warnings when importing them.
126
Brett Cannond1877262012-11-17 20:46:26 -0500127 If ignore is False, this context manager has no effect.
128 """
Nick Coghlanfce769e2009-04-11 14:30:59 +0000129 if ignore:
130 with warnings.catch_warnings():
131 warnings.filterwarnings("ignore", ".+ (module|package)",
132 DeprecationWarning)
133 yield
134 else:
135 yield
136
137
Brett Cannond1877262012-11-17 20:46:26 -0500138def import_module(name, deprecated=False, *, required_on=()):
R. David Murraya21e4ca2009-03-31 23:16:50 +0000139 """Import and return the module to be tested, raising SkipTest if
140 it is not available.
141
142 If deprecated is True, any module or package deprecation messages
Brett Cannond1877262012-11-17 20:46:26 -0500143 will be suppressed. If a module is required on a platform but optional for
144 others, set required_on to an iterable of platform prefixes which will be
145 compared against sys.platform.
146 """
Nick Coghlanfce769e2009-04-11 14:30:59 +0000147 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +0000148 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +0000149 return importlib.import_module(name)
Brett Cannon260fbe82013-07-04 18:16:15 -0400150 except ImportError as msg:
Brett Cannond1877262012-11-17 20:46:26 -0500151 if sys.platform.startswith(tuple(required_on)):
152 raise
R. David Murraya21e4ca2009-03-31 23:16:50 +0000153 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +0000154
155
Nick Coghlan47384702009-04-22 16:13:36 +0000156def _save_and_remove_module(name, orig_modules):
157 """Helper function to save and remove a module from sys.modules
158
Eli Benderskyba5517d2013-08-11 15:38:08 -0700159 Raise ImportError if the module can't be imported.
160 """
Ezio Melottifec3ad12011-05-14 06:02:25 +0300161 # try to import the module and raise an error if it can't be imported
162 if name not in sys.modules:
Ezio Melotti199e0852011-05-09 06:41:55 +0300163 __import__(name)
Nick Coghlan47384702009-04-22 16:13:36 +0000164 del sys.modules[name]
Ezio Melottifec3ad12011-05-14 06:02:25 +0300165 for modname in list(sys.modules):
166 if modname == name or modname.startswith(name + '.'):
167 orig_modules[modname] = sys.modules[modname]
168 del sys.modules[modname]
Nick Coghlan47384702009-04-22 16:13:36 +0000169
170def _save_and_block_module(name, orig_modules):
171 """Helper function to save and block a module in sys.modules
172
Eli Benderskyba5517d2013-08-11 15:38:08 -0700173 Return True if the module was in sys.modules, False otherwise.
174 """
Nick Coghlan47384702009-04-22 16:13:36 +0000175 saved = True
176 try:
177 orig_modules[name] = sys.modules[name]
178 except KeyError:
179 saved = False
Alexander Belopolsky903396e2010-07-13 14:50:16 +0000180 sys.modules[name] = None
Nick Coghlan47384702009-04-22 16:13:36 +0000181 return saved
182
183
Nick Coghlan2496f332011-09-19 20:26:31 +1000184def anticipate_failure(condition):
185 """Decorator to mark a test that is known to be broken in some cases
186
187 Any use of this decorator should have a comment identifying the
188 associated tracker issue.
189 """
190 if condition:
191 return unittest.expectedFailure
192 return lambda f: f
193
Zachary Waref012ba42014-07-23 12:00:29 -0500194def load_package_tests(pkg_dir, loader, standard_tests, pattern):
195 """Generic load_tests implementation for simple test packages.
196
197 Most packages can implement load_tests using this function as follows:
198
199 def load_tests(*args):
200 return load_package_tests(os.path.dirname(__file__), *args)
201 """
202 if pattern is None:
203 pattern = "test*"
204 top_dir = os.path.dirname( # Lib
205 os.path.dirname( # test
206 os.path.dirname(__file__))) # support
207 package_tests = loader.discover(start_dir=pkg_dir,
208 top_level_dir=top_dir,
209 pattern=pattern)
210 standard_tests.addTests(package_tests)
211 return standard_tests
212
Nick Coghlan2496f332011-09-19 20:26:31 +1000213
Nick Coghlan47384702009-04-22 16:13:36 +0000214def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Eli Benderskyba5517d2013-08-11 15:38:08 -0700215 """Import and return a module, deliberately bypassing sys.modules.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000216
Eli Benderskyba5517d2013-08-11 15:38:08 -0700217 This function imports and returns a fresh copy of the named Python module
218 by removing the named module from sys.modules before doing the import.
219 Note that unlike reload, the original module is not affected by
220 this operation.
Nick Coghlan47384702009-04-22 16:13:36 +0000221
Eli Benderskyba5517d2013-08-11 15:38:08 -0700222 *fresh* is an iterable of additional module names that are also removed
223 from the sys.modules cache before doing the import.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000224
Eli Benderskyba5517d2013-08-11 15:38:08 -0700225 *blocked* is an iterable of module names that are replaced with None
226 in the module cache during the import to ensure that attempts to import
227 them raise ImportError.
228
229 The named module and any modules named in the *fresh* and *blocked*
230 parameters are saved before starting the import and then reinserted into
231 sys.modules when the fresh import is complete.
232
233 Module and package deprecation messages are suppressed during this import
234 if *deprecated* is True.
235
236 This function will raise ImportError if the named module cannot be
237 imported.
238 """
Ezio Melotti6b60fb92011-05-14 06:47:51 +0300239 # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
240 # to make sure that this utility function is working as expected
Nick Coghlanfce769e2009-04-11 14:30:59 +0000241 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000242 # Keep track of modules saved for later restoration as well
243 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000244 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000245 names_to_remove = []
246 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000247 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000248 for fresh_name in fresh:
249 _save_and_remove_module(fresh_name, orig_modules)
250 for blocked_name in blocked:
251 if not _save_and_block_module(blocked_name, orig_modules):
252 names_to_remove.append(blocked_name)
253 fresh_module = importlib.import_module(name)
Brett Cannon260fbe82013-07-04 18:16:15 -0400254 except ImportError:
Ezio Melotti199e0852011-05-09 06:41:55 +0300255 fresh_module = None
Nick Coghlanfce769e2009-04-11 14:30:59 +0000256 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000257 for orig_name, module in orig_modules.items():
258 sys.modules[orig_name] = module
259 for name_to_remove in names_to_remove:
260 del sys.modules[name_to_remove]
261 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000262
Benjamin Peterson699adb92008-05-08 22:27:58 +0000263
R. David Murraya21e4ca2009-03-31 23:16:50 +0000264def get_attribute(obj, name):
265 """Get an attribute, raising SkipTest if AttributeError is raised."""
266 try:
267 attribute = getattr(obj, name)
268 except AttributeError:
Éric Araujo4300f692011-10-05 01:50:22 +0200269 raise unittest.SkipTest("object %r has no attribute %r" % (obj, name))
R. David Murraya21e4ca2009-03-31 23:16:50 +0000270 else:
271 return attribute
272
Barry Warsawc0fb6052001-08-20 22:29:23 +0000273verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000274use_resources = None # Flag set to [] by regrtest.py
275max_memuse = 0 # Disable bigmem tests (they will still be run with
276 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000277real_max_memuse = 0
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200278failfast = False
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200279match_tests = None
Guido van Rossum531661c1996-12-20 02:58:22 +0000280
Tim Peters8dee8092001-09-25 20:05:11 +0000281# _original_stdout is meant to hold stdout at the time regrtest began.
282# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
283# The point is to have some flavor of stdout the user can actually see.
284_original_stdout = None
285def record_original_stdout(stdout):
286 global _original_stdout
287 _original_stdout = stdout
288
289def get_original_stdout():
290 return _original_stdout or sys.stdout
291
Guido van Rossum3bead091992-01-27 17:00:37 +0000292def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000293 try:
294 del sys.modules[name]
295 except KeyError:
296 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000297
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500298if sys.platform.startswith("win"):
299 def _waitfor(func, pathname, waitall=False):
Ezio Melottib5bc3532013-08-17 16:11:40 +0300300 # Perform the operation
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500301 func(pathname)
302 # Now setup the wait loop
303 if waitall:
304 dirname = pathname
305 else:
306 dirname, name = os.path.split(pathname)
307 dirname = dirname or '.'
308 # Check for `pathname` to be removed from the filesystem.
309 # The exponential backoff of the timeout amounts to a total
310 # of ~1 second after which the deletion is probably an error
311 # anyway.
312 # Testing on a i7@4.3GHz shows that usually only 1 iteration is
313 # required when contention occurs.
314 timeout = 0.001
315 while timeout < 1.0:
Ezio Melottib5bc3532013-08-17 16:11:40 +0300316 # Note we are only testing for the existence of the file(s) in
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500317 # the contents of the directory regardless of any security or
318 # access rights. If we have made it this far, we have sufficient
319 # permissions to do that much using Python's equivalent of the
320 # Windows API FindFirstFile.
321 # Other Windows APIs can fail or give incorrect results when
322 # dealing with files that are pending deletion.
323 L = os.listdir(dirname)
324 if not (L if waitall else name in L):
325 return
326 # Increase the timeout and try again
327 time.sleep(timeout)
328 timeout *= 2
329 warnings.warn('tests may fail, delete still pending for ' + pathname,
330 RuntimeWarning, stacklevel=4)
331
332 def _unlink(filename):
333 _waitfor(os.unlink, filename)
334
335 def _rmdir(dirname):
336 _waitfor(os.rmdir, dirname)
337
338 def _rmtree(path):
339 def _rmtree_inner(path):
340 for name in os.listdir(path):
341 fullname = os.path.join(path, name)
Victor Stinner67f87062014-07-21 19:18:12 +0200342 try:
343 mode = os.lstat(fullname).st_mode
344 except OSError as exc:
345 print("support.rmtree(): os.lstat(%r) failed with %s" % (fullname, exc),
346 file=sys.__stderr__)
347 mode = 0
348 if stat.S_ISDIR(mode):
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500349 _waitfor(_rmtree_inner, fullname, waitall=True)
350 os.rmdir(fullname)
351 else:
352 os.unlink(fullname)
353 _waitfor(_rmtree_inner, path, waitall=True)
354 _waitfor(os.rmdir, path)
355else:
356 _unlink = os.unlink
357 _rmdir = os.rmdir
358 _rmtree = shutil.rmtree
359
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000360def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000361 try:
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500362 _unlink(filename)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100363 except (FileNotFoundError, NotADirectoryError):
364 pass
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000365
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500366def rmdir(dirname):
367 try:
368 _rmdir(dirname)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100369 except FileNotFoundError:
370 pass
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500371
Christian Heimes23daade02008-02-25 12:39:23 +0000372def rmtree(path):
373 try:
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500374 _rmtree(path)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100375 except FileNotFoundError:
376 pass
Christian Heimes23daade02008-02-25 12:39:23 +0000377
Barry Warsaw28a691b2010-04-17 00:19:56 +0000378def make_legacy_pyc(source):
Brett Cannonf299abd2015-04-13 14:21:02 -0400379 """Move a PEP 3147/488 pyc file to its legacy pyc location.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000380
381 :param source: The file system path to the source file. The source file
Brett Cannonf299abd2015-04-13 14:21:02 -0400382 does not need to exist, however the PEP 3147/488 pyc file must exist.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000383 :return: The file system path to the legacy pyc file.
384 """
Brett Cannon9529fbf2013-06-15 17:11:25 -0400385 pyc_file = importlib.util.cache_from_source(source)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000386 up_one = os.path.dirname(os.path.abspath(source))
Brett Cannonf299abd2015-04-13 14:21:02 -0400387 legacy_pyc = os.path.join(up_one, source + 'c')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000388 os.rename(pyc_file, legacy_pyc)
389 return legacy_pyc
390
Guido van Rossum3bead091992-01-27 17:00:37 +0000391def forget(modname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000392 """'Forget' a module was ever imported.
393
Brett Cannonf299abd2015-04-13 14:21:02 -0400394 This removes the module from sys.modules and deletes any PEP 3147/488 or
395 legacy .pyc files.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000396 """
Fred Drake004d5e62000-10-23 17:22:08 +0000397 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000398 for dirname in sys.path:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000399 source = os.path.join(dirname, modname + '.py')
400 # It doesn't matter if they exist or not, unlink all possible
Brett Cannonf299abd2015-04-13 14:21:02 -0400401 # combinations of PEP 3147/488 and legacy pyc files.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000402 unlink(source + 'c')
Brett Cannonf299abd2015-04-13 14:21:02 -0400403 for opt in ('', 1, 2):
404 unlink(importlib.util.cache_from_source(source, optimization=opt))
Guido van Rossum3bead091992-01-27 17:00:37 +0000405
Zachary Warececed6b2014-05-02 10:51:07 -0500406# Check whether a gui is actually available
407def _is_gui_available():
408 if hasattr(_is_gui_available, 'result'):
409 return _is_gui_available.result
410 reason = None
411 if sys.platform.startswith('win'):
412 # if Python is running as a service (such as the buildbot service),
413 # gui interaction may be disallowed
414 import ctypes
415 import ctypes.wintypes
Antoine Pitroud20a5f62011-02-26 15:58:05 +0000416 UOI_FLAGS = 1
417 WSF_VISIBLE = 0x0001
418 class USEROBJECTFLAGS(ctypes.Structure):
419 _fields_ = [("fInherit", ctypes.wintypes.BOOL),
420 ("fReserved", ctypes.wintypes.BOOL),
421 ("dwFlags", ctypes.wintypes.DWORD)]
422 dll = ctypes.windll.user32
423 h = dll.GetProcessWindowStation()
424 if not h:
425 raise ctypes.WinError()
426 uof = USEROBJECTFLAGS()
427 needed = ctypes.wintypes.DWORD()
428 res = dll.GetUserObjectInformationW(h,
429 UOI_FLAGS,
430 ctypes.byref(uof),
431 ctypes.sizeof(uof),
432 ctypes.byref(needed))
433 if not res:
434 raise ctypes.WinError()
Zachary Warececed6b2014-05-02 10:51:07 -0500435 if not bool(uof.dwFlags & WSF_VISIBLE):
436 reason = "gui not available (WSF_VISIBLE flag not set)"
437 elif sys.platform == 'darwin':
438 # The Aqua Tk implementations on OS X can abort the process if
439 # being called in an environment where a window server connection
440 # cannot be made, for instance when invoked by a buildbot or ssh
441 # process not running under the same user id as the current console
442 # user. To avoid that, raise an exception if the window manager
443 # connection is not available.
444 from ctypes import cdll, c_int, pointer, Structure
445 from ctypes.util import find_library
446
447 app_services = cdll.LoadLibrary(find_library("ApplicationServices"))
448
449 if app_services.CGMainDisplayID() == 0:
450 reason = "gui tests cannot run without OS X window manager"
451 else:
452 class ProcessSerialNumber(Structure):
453 _fields_ = [("highLongOfPSN", c_int),
454 ("lowLongOfPSN", c_int)]
455 psn = ProcessSerialNumber()
456 psn_p = pointer(psn)
457 if ( (app_services.GetCurrentProcess(psn_p) < 0) or
458 (app_services.SetFrontProcess(psn_p) < 0) ):
459 reason = "cannot run without OS X gui process"
460
461 # check on every platform whether tkinter can actually do anything
Ned Deily91f01e12014-11-01 19:29:22 -0700462 if not reason:
Zachary Warececed6b2014-05-02 10:51:07 -0500463 try:
464 from tkinter import Tk
465 root = Tk()
Ned Deily91f01e12014-11-01 19:29:22 -0700466 root.update()
Zachary Warececed6b2014-05-02 10:51:07 -0500467 root.destroy()
468 except Exception as e:
469 err_string = str(e)
470 if len(err_string) > 50:
471 err_string = err_string[:50] + ' [...]'
472 reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__,
473 err_string)
474
475 _is_gui_available.reason = reason
476 _is_gui_available.result = not reason
477
478 return _is_gui_available.result
Antoine Pitroud20a5f62011-02-26 15:58:05 +0000479
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000480def is_resource_enabled(resource):
Zachary Ware66f29282014-06-02 16:01:29 -0500481 """Test whether a resource is enabled.
482
483 Known resources are set by regrtest.py. If not running under regrtest.py,
484 all resources are assumed enabled unless use_resources has been set.
485 """
486 return use_resources is None or resource in use_resources
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000487
Barry Warsawc0fb6052001-08-20 22:29:23 +0000488def requires(resource, msg=None):
Zachary Ware66f29282014-06-02 16:01:29 -0500489 """Raise ResourceDenied if the specified resource is not available."""
Antoine Pitroud20a5f62011-02-26 15:58:05 +0000490 if resource == 'gui' and not _is_gui_available():
Zachary Warececed6b2014-05-02 10:51:07 -0500491 raise ResourceDenied(_is_gui_available.reason)
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000492 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000493 if msg is None:
Éric Araujoaf5bacf2011-07-15 17:50:15 +0200494 msg = "Use of the %r resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000495 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000496
Charles-François Natali87b3c922011-10-03 19:40:37 +0200497def _requires_unix_version(sysname, min_version):
498 """Decorator raising SkipTest if the OS is `sysname` and the version is less
499 than `min_version`.
Charles-François Natali239bb962011-06-03 12:55:15 +0200500
Charles-François Natali87b3c922011-10-03 19:40:37 +0200501 For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
502 the FreeBSD version is less than 7.2.
Charles-François Natali239bb962011-06-03 12:55:15 +0200503 """
504 def decorator(func):
505 @functools.wraps(func)
506 def wrapper(*args, **kw):
Charles-François Natali87b3c922011-10-03 19:40:37 +0200507 if platform.system() == sysname:
Charles-François Natali239bb962011-06-03 12:55:15 +0200508 version_txt = platform.release().split('-', 1)[0]
509 try:
510 version = tuple(map(int, version_txt.split('.')))
511 except ValueError:
512 pass
513 else:
514 if version < min_version:
515 min_version_txt = '.'.join(map(str, min_version))
516 raise unittest.SkipTest(
Charles-François Natali87b3c922011-10-03 19:40:37 +0200517 "%s version %s or higher required, not %s"
518 % (sysname, min_version_txt, version_txt))
Victor Stinner3b44a402013-08-28 12:26:28 +0200519 return func(*args, **kw)
520 wrapper.min_version = min_version
Charles-François Natali239bb962011-06-03 12:55:15 +0200521 return wrapper
522 return decorator
Victor Stinnerfea0f4d2011-05-24 00:24:19 +0200523
Charles-François Natali87b3c922011-10-03 19:40:37 +0200524def requires_freebsd_version(*min_version):
525 """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
526 less than `min_version`.
527
528 For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
529 version is less than 7.2.
530 """
531 return _requires_unix_version('FreeBSD', min_version)
532
533def requires_linux_version(*min_version):
534 """Decorator raising SkipTest if the OS is Linux and the Linux version is
535 less than `min_version`.
536
537 For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
538 version is less than 2.6.32.
539 """
540 return _requires_unix_version('Linux', min_version)
541
Victor Stinnerfce92332011-06-01 12:28:04 +0200542def requires_mac_ver(*min_version):
Victor Stinner88701e22011-06-01 13:13:04 +0200543 """Decorator raising SkipTest if the OS is Mac OS X and the OS X
544 version if less than min_version.
Victor Stinnerfce92332011-06-01 12:28:04 +0200545
Victor Stinner88701e22011-06-01 13:13:04 +0200546 For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
547 is lesser than 10.5.
Victor Stinnerfce92332011-06-01 12:28:04 +0200548 """
Victor Stinner88701e22011-06-01 13:13:04 +0200549 def decorator(func):
550 @functools.wraps(func)
551 def wrapper(*args, **kw):
552 if sys.platform == 'darwin':
553 version_txt = platform.mac_ver()[0]
554 try:
555 version = tuple(map(int, version_txt.split('.')))
556 except ValueError:
557 pass
558 else:
559 if version < min_version:
560 min_version_txt = '.'.join(map(str, min_version))
561 raise unittest.SkipTest(
562 "Mac OS X %s or higher required, not %s"
563 % (min_version_txt, version_txt))
564 return func(*args, **kw)
565 wrapper.min_version = min_version
566 return wrapper
567 return decorator
568
Victor Stinnerfce92332011-06-01 12:28:04 +0200569
Antoine Pitrouf6fbf562013-08-22 00:39:46 +0200570# Don't use "localhost", since resolving it uses the DNS under recent
571# Windows versions (see issue #18792).
572HOST = "127.0.0.1"
573HOSTv6 = "::1"
574
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000575
Christian Heimes5e696852008-04-09 08:37:03 +0000576def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
577 """Returns an unused port that should be suitable for binding. This is
578 achieved by creating a temporary socket with the same family and type as
579 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
580 the specified host address (defaults to 0.0.0.0) with the port set to 0,
581 eliciting an unused ephemeral port from the OS. The temporary socket is
582 then closed and deleted, and the ephemeral port is returned.
583
584 Either this method or bind_port() should be used for any tests where a
585 server socket needs to be bound to a particular port for the duration of
586 the test. Which one to use depends on whether the calling code is creating
587 a python socket, or if an unused port needs to be provided in a constructor
588 or passed to an external program (i.e. the -accept argument to openssl's
589 s_server mode). Always prefer bind_port() over find_unused_port() where
590 possible. Hard coded ports should *NEVER* be used. As soon as a server
591 socket is bound to a hard coded port, the ability to run multiple instances
592 of the test simultaneously on the same host is compromised, which makes the
593 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
594 may simply manifest as a failed test, which can be recovered from without
595 intervention in most cases, but on Windows, the entire python process can
596 completely and utterly wedge, requiring someone to log in to the buildbot
597 and manually kill the affected process.
598
599 (This is easy to reproduce on Windows, unfortunately, and can be traced to
600 the SO_REUSEADDR socket option having different semantics on Windows versus
601 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
602 listen and then accept connections on identical host/ports. An EADDRINUSE
Andrew Svetlov0832af62012-12-18 23:10:48 +0200603 OSError will be raised at some point (depending on the platform and
Christian Heimes5e696852008-04-09 08:37:03 +0000604 the order bind and listen were called on each socket).
605
606 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
607 will ever be raised when attempting to bind two identical host/ports. When
608 accept() is called on each socket, the second caller's process will steal
609 the port from the first caller, leaving them both in an awkwardly wedged
610 state where they'll no longer respond to any signals or graceful kills, and
611 must be forcibly killed via OpenProcess()/TerminateProcess().
612
613 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
614 instead of SO_REUSEADDR, which effectively affords the same semantics as
615 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
616 Source world compared to Windows ones, this is a common mistake. A quick
617 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
618 openssl.exe is called with the 's_server' option, for example. See
619 http://bugs.python.org/issue2550 for more info. The following site also
620 has a very thorough description about the implications of both REUSEADDR
621 and EXCLUSIVEADDRUSE on Windows:
622 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
623
624 XXX: although this approach is a vast improvement on previous attempts to
625 elicit unused ports, it rests heavily on the assumption that the ephemeral
626 port returned to us by the OS won't immediately be dished back out to some
627 other process when we close and delete our temporary socket but before our
628 calling code has a chance to bind the returned port. We can deal with this
629 issue if/when we come across it.
630 """
631
632 tempsock = socket.socket(family, socktype)
633 port = bind_port(tempsock)
634 tempsock.close()
635 del tempsock
636 return port
637
638def bind_port(sock, host=HOST):
639 """Bind the socket to a free port and return the port number. Relies on
640 ephemeral ports in order to ensure we are using an unbound port. This is
641 important as many tests may be running simultaneously, especially in a
642 buildbot environment. This method raises an exception if the sock.family
643 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
644 or SO_REUSEPORT set on it. Tests should *never* set these socket options
645 for TCP/IP sockets. The only case for setting these options is testing
646 multicasting via multiple UDP sockets.
647
648 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
649 on Windows), it will be set on the socket. This will prevent anyone else
650 from bind()'ing to our host/port for the duration of the test.
651 """
652
653 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
654 if hasattr(socket, 'SO_REUSEADDR'):
655 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
656 raise TestFailed("tests should never set the SO_REUSEADDR " \
657 "socket option on TCP/IP sockets!")
658 if hasattr(socket, 'SO_REUSEPORT'):
Gregory P. Smith162307f2013-11-17 22:19:32 +0000659 try:
660 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
661 raise TestFailed("tests should never set the SO_REUSEPORT " \
662 "socket option on TCP/IP sockets!")
663 except OSError:
664 # Python's socket module was compiled using modern headers
665 # thus defining SO_REUSEPORT but this process is running
666 # under an older kernel that does not support SO_REUSEPORT.
667 pass
Christian Heimes5e696852008-04-09 08:37:03 +0000668 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
669 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
670
671 sock.bind((host, 0))
672 port = sock.getsockname()[1]
673 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000674
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200675def _is_ipv6_enabled():
676 """Check whether IPv6 is enabled on this host."""
677 if socket.has_ipv6:
Ross Lagerwall121d59f2012-07-07 18:40:32 +0200678 sock = None
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200679 try:
680 sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
Charles-François Natalifcfb3242013-08-31 14:40:49 +0200681 sock.bind((HOSTv6, 0))
Ross Lagerwall121d59f2012-07-07 18:40:32 +0200682 return True
Andrew Svetlov0832af62012-12-18 23:10:48 +0200683 except OSError:
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200684 pass
Ross Lagerwall121d59f2012-07-07 18:40:32 +0200685 finally:
686 if sock:
687 sock.close()
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200688 return False
689
690IPV6_ENABLED = _is_ipv6_enabled()
691
Benjamin Peterson2615e9e2014-11-25 15:16:55 -0600692def system_must_validate_cert(f):
693 """Skip the test on TLS certificate validation failures."""
694 @functools.wraps(f)
695 def dec(*args, **kwargs):
696 try:
697 f(*args, **kwargs)
698 except IOError as e:
Benjamin Peterson61508042014-11-25 15:43:58 -0600699 if "CERTIFICATE_VERIFY_FAILED" in str(e):
Benjamin Peterson2615e9e2014-11-25 15:16:55 -0600700 raise unittest.SkipTest("system does not contain "
701 "necessary certificates")
702 raise
703 return dec
Charles-François Natali2d517212011-05-29 16:36:44 +0200704
Antoine Pitroue1a16742013-04-24 23:31:38 +0200705# A constant likely larger than the underlying OS pipe buffer size, to
706# make writes blocking.
707# Windows limit seems to be around 512 B, and many Unix kernels have a
708# 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
709# (see issue #17835 for a discussion of this number).
Charles-François Natali5fd26422013-08-29 19:01:40 +0200710PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
Charles-François Natali2d517212011-05-29 16:36:44 +0200711
Charles-François Natali5fd26422013-08-29 19:01:40 +0200712# A constant likely larger than the underlying OS socket buffer size, to make
713# writes blocking.
714# The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
715# on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
716# for a discussion of this number).
717SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1
Charles-François Natali2d517212011-05-29 16:36:44 +0200718
Eric Smithf24a0d92010-12-04 13:32:18 +0000719# decorator for skipping tests on non-IEEE 754 platforms
720requires_IEEE_754 = unittest.skipUnless(
721 float.__getformat__("double").startswith("IEEE"),
722 "test requires IEEE 754 doubles")
723
Ezio Melotticad648c2011-05-19 21:25:10 +0300724requires_zlib = unittest.skipUnless(zlib, 'requires zlib')
725
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300726requires_gzip = unittest.skipUnless(gzip, 'requires gzip')
727
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200728requires_bz2 = unittest.skipUnless(bz2, 'requires bz2')
729
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200730requires_lzma = unittest.skipUnless(lzma, 'requires lzma')
731
Finn Bock57bc5fa2002-11-01 18:02:03 +0000732is_jython = sys.platform.startswith('java')
733
Barry Warsaw559f6682001-03-23 18:04:02 +0000734# Filename used for testing
735if os.name == 'java':
736 # Jython disallows @ in module names
737 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000738else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000739 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000740
Antoine Pitrou88909542009-06-29 13:54:42 +0000741# Disambiguate TESTFN for parallel testing, while letting it remain a valid
742# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000743TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000744
Victor Stinner8b219b22012-11-06 23:23:43 +0100745# FS_NONASCII: non-ASCII character encodable by os.fsencode(),
746# or None if there is no such character.
747FS_NONASCII = None
748for character in (
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100749 # First try printable and common characters to have a readable filename.
750 # For each character, the encoding list are just example of encodings able
751 # to encode the character (the list is not exhaustive).
752
753 # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
Victor Stinner8b219b22012-11-06 23:23:43 +0100754 '\u00E6',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100755 # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
756 '\u0130',
757 # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
Victor Stinner8b219b22012-11-06 23:23:43 +0100758 '\u0141',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100759 # U+03C6 (Greek Small Letter Phi): cp1253
760 '\u03C6',
761 # U+041A (Cyrillic Capital Letter Ka): cp1251
Victor Stinner8b219b22012-11-06 23:23:43 +0100762 '\u041A',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100763 # U+05D0 (Hebrew Letter Alef): Encodable to cp424
Victor Stinner8b219b22012-11-06 23:23:43 +0100764 '\u05D0',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100765 # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
766 '\u060C',
767 # U+062A (Arabic Letter Teh): cp720
768 '\u062A',
769 # U+0E01 (Thai Character Ko Kai): cp874
Victor Stinner8b219b22012-11-06 23:23:43 +0100770 '\u0E01',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100771
772 # Then try more "special" characters. "special" because they may be
773 # interpreted or displayed differently depending on the exact locale
774 # encoding and the font.
775
776 # U+00A0 (No-Break Space)
777 '\u00A0',
778 # U+20AC (Euro Sign)
779 '\u20AC',
Victor Stinner8b219b22012-11-06 23:23:43 +0100780):
781 try:
782 os.fsdecode(os.fsencode(character))
783 except UnicodeError:
784 pass
785 else:
786 FS_NONASCII = character
787 break
Michael Foord2d9c2d52010-05-04 22:29:10 +0000788
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000789# TESTFN_UNICODE is a non-ascii filename
790TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
Victor Stinner74a833f2010-08-18 21:06:23 +0000791if sys.platform == 'darwin':
792 # In Mac OS X's VFS API file names are, by definition, canonically
793 # decomposed Unicode, encoded using UTF-8. See QA1173:
794 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
795 import unicodedata
796 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
Antoine Pitrou88909542009-06-29 13:54:42 +0000797TESTFN_ENCODING = sys.getfilesystemencoding()
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000798
Victor Stinner09c449c2010-08-13 22:23:24 +0000799# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000800# encoded by the filesystem encoding (in strict mode). It can be None if we
801# cannot generate such filename.
Victor Stinnera0241c82010-08-15 19:28:21 +0000802TESTFN_UNENCODABLE = None
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000803if os.name in ('nt', 'ce'):
Victor Stinnera0241c82010-08-15 19:28:21 +0000804 # skip win32s (0) or Windows 9x/ME (1)
805 if sys.getwindowsversion().platform >= 2:
Victor Stinner8ce7df62010-09-10 11:19:59 +0000806 # Different kinds of characters from various languages to minimize the
807 # probability that the whole name is encodable to MBCS (issue #9819)
808 TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000809 try:
Victor Stinner09c449c2010-08-13 22:23:24 +0000810 TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000811 except UnicodeEncodeError:
812 pass
813 else:
814 print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
815 'Unicode filename tests may not be effective'
Victor Stinner09c449c2010-08-13 22:23:24 +0000816 % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
817 TESTFN_UNENCODABLE = None
Victor Stinnera0241c82010-08-15 19:28:21 +0000818# Mac OS X denies unencodable filenames (invalid utf-8)
Victor Stinner03c9e1d2010-08-14 17:35:20 +0000819elif sys.platform != 'darwin':
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000820 try:
821 # ascii and utf-8 cannot encode the byte 0xff
822 b'\xff'.decode(TESTFN_ENCODING)
823 except UnicodeDecodeError:
824 # 0xff will be encoded using the surrogate character u+DCFF
Victor Stinner09c449c2010-08-13 22:23:24 +0000825 TESTFN_UNENCODABLE = TESTFN \
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000826 + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
827 else:
828 # File system encoding (eg. ISO-8859-* encodings) can encode
829 # the byte 0xff. Skip some unicode filename tests.
Victor Stinnera0241c82010-08-15 19:28:21 +0000830 pass
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000831
Victor Stinner292c8352012-10-30 02:17:38 +0100832# TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be
833# decoded from the filesystem encoding (in strict mode). It can be None if we
Victor Stinnerff3d5152012-11-10 12:07:39 +0100834# cannot generate such filename (ex: the latin1 encoding can decode any byte
835# sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks
836# to the surrogateescape error handler (PEP 383), but not from the filesystem
837# encoding in strict mode.
Victor Stinner292c8352012-10-30 02:17:38 +0100838TESTFN_UNDECODABLE = None
Victor Stinnerff3d5152012-11-10 12:07:39 +0100839for name in (
840 # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows
841 # accepts it to create a file or a directory, or don't accept to enter to
842 # such directory (when the bytes name is used). So test b'\xe7' first: it is
843 # not decodable from cp932.
844 b'\xe7w\xf0',
845 # undecodable from ASCII, UTF-8
846 b'\xff',
847 # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856
848 # and cp857
849 b'\xae\xd5'
850 # undecodable from UTF-8 (UNIX and Mac OS X)
851 b'\xed\xb2\x80', b'\xed\xb4\x80',
Victor Stinnerfe907e12012-12-04 11:55:04 +0100852 # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252,
853 # cp1253, cp1254, cp1255, cp1257, cp1258
854 b'\x81\x98',
Victor Stinnerff3d5152012-11-10 12:07:39 +0100855):
Victor Stinner292c8352012-10-30 02:17:38 +0100856 try:
Victor Stinnerff3d5152012-11-10 12:07:39 +0100857 name.decode(TESTFN_ENCODING)
Victor Stinnera0c811e2012-10-31 22:16:38 +0100858 except UnicodeDecodeError:
Victor Stinnerff3d5152012-11-10 12:07:39 +0100859 TESTFN_UNDECODABLE = os.fsencode(TESTFN) + name
Victor Stinner292c8352012-10-30 02:17:38 +0100860 break
861
Victor Stinner8b219b22012-11-06 23:23:43 +0100862if FS_NONASCII:
Victor Stinner90a9d512012-11-06 23:40:22 +0100863 TESTFN_NONASCII = TESTFN + '-' + FS_NONASCII
Victor Stinner8b219b22012-11-06 23:23:43 +0100864else:
865 TESTFN_NONASCII = None
866
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000867# Save the initial cwd
868SAVEDCWD = os.getcwd()
869
870@contextlib.contextmanager
Nick Coghlan55175962013-07-28 22:11:50 +1000871def temp_dir(path=None, quiet=False):
872 """Return a context manager that creates a temporary directory.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000873
Nick Coghlan55175962013-07-28 22:11:50 +1000874 Arguments:
Nick Coghland26c18a2010-08-17 13:06:11 +0000875
Nick Coghlan55175962013-07-28 22:11:50 +1000876 path: the directory to create temporarily. If omitted or None,
877 defaults to creating a temporary directory using tempfile.mkdtemp.
878
879 quiet: if False (the default), the context manager raises an exception
880 on error. Otherwise, if the path is specified and cannot be
881 created, only a warning is issued.
882
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000883 """
Nick Coghlan55175962013-07-28 22:11:50 +1000884 dir_created = False
Nick Coghland26c18a2010-08-17 13:06:11 +0000885 if path is None:
Nick Coghlan55175962013-07-28 22:11:50 +1000886 path = tempfile.mkdtemp()
887 dir_created = True
888 path = os.path.realpath(path)
889 else:
Nick Coghland26c18a2010-08-17 13:06:11 +0000890 try:
Nick Coghlan55175962013-07-28 22:11:50 +1000891 os.mkdir(path)
892 dir_created = True
Nick Coghland26c18a2010-08-17 13:06:11 +0000893 except OSError:
894 if not quiet:
895 raise
Nick Coghlan55175962013-07-28 22:11:50 +1000896 warnings.warn('tests may fail, unable to create temp dir: ' + path,
Nick Coghland26c18a2010-08-17 13:06:11 +0000897 RuntimeWarning, stacklevel=3)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000898 try:
Nick Coghlan55175962013-07-28 22:11:50 +1000899 yield path
900 finally:
901 if dir_created:
902 shutil.rmtree(path)
903
904@contextlib.contextmanager
905def change_cwd(path, quiet=False):
906 """Return a context manager that changes the current working directory.
907
908 Arguments:
909
910 path: the directory to use as the temporary current working directory.
911
912 quiet: if False (the default), the context manager raises an exception
913 on error. Otherwise, it issues only a warning and keeps the current
914 working directory the same.
915
916 """
917 saved_dir = os.getcwd()
918 try:
Nick Coghland26c18a2010-08-17 13:06:11 +0000919 os.chdir(path)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000920 except OSError:
921 if not quiet:
922 raise
Nick Coghlan55175962013-07-28 22:11:50 +1000923 warnings.warn('tests may fail, unable to change CWD to: ' + path,
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000924 RuntimeWarning, stacklevel=3)
925 try:
926 yield os.getcwd()
927 finally:
928 os.chdir(saved_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000929
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000930
Nick Coghlan55175962013-07-28 22:11:50 +1000931@contextlib.contextmanager
932def temp_cwd(name='tempcwd', quiet=False):
933 """
934 Context manager that temporarily creates and changes the CWD.
935
936 The function temporarily changes the current working directory
937 after creating a temporary directory in the current directory with
938 name *name*. If *name* is None, the temporary directory is
939 created using tempfile.mkdtemp.
940
941 If *quiet* is False (default) and it is not possible to
942 create or change the CWD, an error is raised. If *quiet* is True,
943 only a warning is raised and the original CWD is used.
944
945 """
946 with temp_dir(path=name, quiet=quiet) as temp_path:
947 with change_cwd(temp_path, quiet=quiet) as cwd_dir:
948 yield cwd_dir
949
Eli Bendersky6c519992011-07-23 08:48:53 +0300950if hasattr(os, "umask"):
951 @contextlib.contextmanager
952 def temp_umask(umask):
953 """Context manager that temporarily sets the process umask."""
954 oldmask = os.umask(umask)
955 try:
956 yield
957 finally:
958 os.umask(oldmask)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000959
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000960# TEST_HOME_DIR refers to the top level directory of the "test" package
Nick Coghlanfb15aa12013-07-28 20:56:19 +1000961# that contains Python's regression test suite
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000962TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__))
963TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000964
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000965# TEST_DATA_DIR is used as a target download location for remote resources
966TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data")
967
968def findfile(filename, subdir=None):
Nick Coghlanfb15aa12013-07-28 20:56:19 +1000969 """Try to find a file on sys.path or in the test directory. If it is not
Brett Cannonf1cfb622003-05-04 21:15:27 +0000970 found the argument passed to the function is returned (this does not
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000971 necessarily signal failure; could still be the legitimate path).
972
973 Setting *subdir* indicates a relative path to use to find the file
974 rather than looking directly in the path directories.
975 """
976 if os.path.isabs(filename):
977 return filename
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000978 if subdir is not None:
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000979 filename = os.path.join(subdir, filename)
980 path = [TEST_HOME_DIR] + sys.path
Fred Drake004d5e62000-10-23 17:22:08 +0000981 for dn in path:
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000982 fn = os.path.join(dn, filename)
Fred Drake004d5e62000-10-23 17:22:08 +0000983 if os.path.exists(fn): return fn
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000984 return filename
Marc-André Lemburg36619082001-01-17 19:11:13 +0000985
Victor Stinnerbf816222011-06-30 23:25:47 +0200986def create_empty_file(filename):
987 """Create an empty file. If the file already exists, truncate it."""
988 fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
989 os.close(fd)
990
Tim Peters2f228e72001-05-13 00:19:31 +0000991def sortdict(dict):
992 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000993 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000994 reprpairs = ["%r: %r" % pair for pair in items]
995 withcommas = ", ".join(reprpairs)
996 return "{%s}" % withcommas
997
Benjamin Peterson7522c742009-01-19 21:00:09 +0000998def make_bad_fd():
999 """
1000 Create an invalid file descriptor by opening and closing a file and return
1001 its fd.
1002 """
1003 file = open(TESTFN, "wb")
1004 try:
1005 return file.fileno()
1006 finally:
1007 file.close()
1008 unlink(TESTFN)
1009
Thomas Wouters89f507f2006-12-13 04:49:30 +00001010def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001011 testcase.assertRaises(SyntaxError, compile, statement,
1012 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001013
Martin v. Löwis234a34a2007-08-30 20:58:02 +00001014def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001015 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001016
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001017 check = kw.pop('check', None)
1018
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001019 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +00001020
Nick Coghlan0494c2a2013-09-08 11:40:34 +10001021 fn = os.path.join(TEST_DATA_DIR, filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001022
1023 def check_valid_file(fn):
1024 f = open(fn, *args, **kw)
1025 if check is None:
1026 return f
1027 elif check(f):
1028 f.seek(0)
1029 return f
1030 f.close()
1031
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001032 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001033 f = check_valid_file(fn)
1034 if f is not None:
1035 return f
1036 unlink(fn)
1037
1038 # Verify the requirement before downloading the file
1039 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +00001040
Berker Peksag0a2e8742014-12-10 02:34:11 +02001041 if verbose:
1042 print('\tfetching %s ...' % url, file=get_original_stdout())
Georg Brandl72a7f7c2014-11-06 15:33:30 +01001043 opener = urllib.request.build_opener()
1044 if gzip:
1045 opener.addheaders.append(('Accept-Encoding', 'gzip'))
1046 f = opener.open(url, timeout=15)
1047 if gzip and f.headers.get('Content-Encoding') == 'gzip':
1048 f = gzip.GzipFile(fileobj=f)
Antoine Pitroufd0680b2009-11-01 22:13:48 +00001049 try:
1050 with open(fn, "wb") as out:
1051 s = f.read()
1052 while s:
1053 out.write(s)
1054 s = f.read()
1055 finally:
1056 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001057
1058 f = check_valid_file(fn)
1059 if f is not None:
1060 return f
Éric Araujoaf5bacf2011-07-15 17:50:15 +02001061 raise TestFailed('invalid resource %r' % fn)
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001062
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001063
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001064class WarningsRecorder(object):
1065 """Convenience wrapper for the warnings list returned on
1066 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001067 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001068 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001069 self._warnings = warnings_list
1070 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001071
1072 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001073 if len(self._warnings) > self._last:
1074 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001075 elif attr in warnings.WarningMessage._WARNING_DETAILS:
1076 return None
1077 raise AttributeError("%r has no attribute %r" % (self, attr))
1078
Florent Xiclunab14930c2010-03-13 15:26:44 +00001079 @property
1080 def warnings(self):
1081 return self._warnings[self._last:]
1082
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001083 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001084 self._last = len(self._warnings)
1085
1086
1087def _filterwarnings(filters, quiet=False):
1088 """Catch the warnings, then check if all the expected
1089 warnings have been raised and re-raise unexpected warnings.
1090 If 'quiet' is True, only re-raise the unexpected warnings.
1091 """
1092 # Clear the warning registry of the calling module
1093 # in order to re-raise the warnings.
1094 frame = sys._getframe(2)
1095 registry = frame.f_globals.get('__warningregistry__')
1096 if registry:
1097 registry.clear()
1098 with warnings.catch_warnings(record=True) as w:
1099 # Set filter "always" to record all warnings. Because
1100 # test_warnings swap the module, we need to look up in
1101 # the sys.modules dictionary.
1102 sys.modules['warnings'].simplefilter("always")
1103 yield WarningsRecorder(w)
1104 # Filter the recorded warnings
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001105 reraise = list(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001106 missing = []
1107 for msg, cat in filters:
1108 seen = False
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001109 for w in reraise[:]:
1110 warning = w.message
Florent Xiclunab14930c2010-03-13 15:26:44 +00001111 # Filter out the matching messages
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001112 if (re.match(msg, str(warning), re.I) and
1113 issubclass(warning.__class__, cat)):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001114 seen = True
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001115 reraise.remove(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001116 if not seen and not quiet:
1117 # This filter caught nothing
1118 missing.append((msg, cat.__name__))
1119 if reraise:
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001120 raise AssertionError("unhandled warning %s" % reraise[0])
Florent Xiclunab14930c2010-03-13 15:26:44 +00001121 if missing:
1122 raise AssertionError("filter (%r, %s) did not catch any warning" %
1123 missing[0])
1124
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001125
1126@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +00001127def check_warnings(*filters, **kwargs):
1128 """Context manager to silence warnings.
1129
1130 Accept 2-tuples as positional arguments:
1131 ("message regexp", WarningCategory)
1132
1133 Optional argument:
1134 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506be2010-03-18 20:00:57 +00001135 (default True without argument,
1136 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001137
1138 Without argument, it defaults to:
Florent Xicluna53b506be2010-03-18 20:00:57 +00001139 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001140 """
Florent Xicluna53b506be2010-03-18 20:00:57 +00001141 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +00001142 if not filters:
1143 filters = (("", Warning),)
Florent Xicluna53b506be2010-03-18 20:00:57 +00001144 # Preserve backward compatibility
1145 if quiet is None:
1146 quiet = True
1147 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001149
1150class CleanImport(object):
1151 """Context manager to force import to return a new module reference.
1152
1153 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +00001154 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001155
1156 Use like this:
1157
1158 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +00001159 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001160 """
1161
1162 def __init__(self, *module_names):
1163 self.original_modules = sys.modules.copy()
1164 for module_name in module_names:
1165 if module_name in sys.modules:
1166 module = sys.modules[module_name]
1167 # It is possible that module_name is just an alias for
1168 # another module (e.g. stub for modules renamed in 3.x).
1169 # In that case, we also need delete the real module to clear
1170 # the import cache.
1171 if module.__name__ != module_name:
1172 del sys.modules[module.__name__]
1173 del sys.modules[module_name]
1174
1175 def __enter__(self):
1176 return self
1177
1178 def __exit__(self, *ignore_exc):
1179 sys.modules.update(self.original_modules)
1180
1181
Raymond Hettinger57d1a882011-02-23 00:46:28 +00001182class EnvironmentVarGuard(collections.abc.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001183
1184 """Class to help protect the environment variable properly. Can be used as
1185 a context manager."""
1186
1187 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +00001188 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +00001189 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001190
Walter Dörwald155374d2009-05-01 19:58:58 +00001191 def __getitem__(self, envvar):
1192 return self._environ[envvar]
1193
1194 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +00001195 # Remember the initial value on the first access
1196 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +00001197 self._changed[envvar] = self._environ.get(envvar)
1198 self._environ[envvar] = value
1199
1200 def __delitem__(self, envvar):
1201 # Remember the initial value on the first access
1202 if envvar not in self._changed:
1203 self._changed[envvar] = self._environ.get(envvar)
1204 if envvar in self._environ:
1205 del self._environ[envvar]
1206
1207 def keys(self):
1208 return self._environ.keys()
1209
1210 def __iter__(self):
1211 return iter(self._environ)
1212
1213 def __len__(self):
1214 return len(self._environ)
1215
1216 def set(self, envvar, value):
1217 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001218
1219 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +00001220 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001221
1222 def __enter__(self):
1223 return self
1224
1225 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +00001226 for (k, v) in self._changed.items():
1227 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +00001228 if k in self._environ:
1229 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +00001230 else:
Walter Dörwald155374d2009-05-01 19:58:58 +00001231 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +00001232 os.environ = self._environ
1233
1234
1235class DirsOnSysPath(object):
1236 """Context manager to temporarily add directories to sys.path.
1237
1238 This makes a copy of sys.path, appends any directories given
1239 as positional arguments, then reverts sys.path to the copied
1240 settings when the context ends.
1241
1242 Note that *all* sys.path modifications in the body of the
1243 context manager, including replacement of the object,
1244 will be reverted at the end of the block.
1245 """
1246
1247 def __init__(self, *paths):
1248 self.original_value = sys.path[:]
1249 self.original_object = sys.path
1250 sys.path.extend(paths)
1251
1252 def __enter__(self):
1253 return self
1254
1255 def __exit__(self, *ignore_exc):
1256 sys.path = self.original_object
1257 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +00001258
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001259
Guido van Rossumd8faa362007-04-27 19:54:29 +00001260class TransientResource(object):
1261
1262 """Raise ResourceDenied if an exception is raised while the context manager
1263 is in effect that matches the specified exception and attributes."""
1264
1265 def __init__(self, exc, **kwargs):
1266 self.exc = exc
1267 self.attrs = kwargs
1268
1269 def __enter__(self):
1270 return self
1271
1272 def __exit__(self, type_=None, value=None, traceback=None):
1273 """If type_ is a subclass of self.exc and value has attributes matching
1274 self.attrs, raise ResourceDenied. Otherwise let the exception
1275 propagate (if any)."""
1276 if type_ is not None and issubclass(self.exc, type_):
1277 for attr, attr_value in self.attrs.items():
1278 if not hasattr(value, attr):
1279 break
1280 if getattr(value, attr) != attr_value:
1281 break
1282 else:
1283 raise ResourceDenied("an optional resource is not available")
1284
Raymond Hettinger686057b2009-06-04 00:11:54 +00001285# Context managers that raise ResourceDenied when various issues
1286# with the Internet connection manifest themselves as exceptions.
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001287# XXX deprecate these and use transient_internet() instead
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001288time_out = TransientResource(OSError, errno=errno.ETIMEDOUT)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001289socket_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001290ioerror_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001291
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001292
Thomas Woutersed03b412007-08-28 21:37:11 +00001293@contextlib.contextmanager
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001294def transient_internet(resource_name, *, timeout=30.0, errnos=()):
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001295 """Return a context manager that raises ResourceDenied when various issues
1296 with the Internet connection manifest themselves as exceptions."""
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001297 default_errnos = [
1298 ('ECONNREFUSED', 111),
1299 ('ECONNRESET', 104),
Antoine Pitrou5d938cb2011-01-08 10:28:11 +00001300 ('EHOSTUNREACH', 113),
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001301 ('ENETUNREACH', 101),
1302 ('ETIMEDOUT', 110),
1303 ]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001304 default_gai_errnos = [
Antoine Pitrou4875c462011-07-09 02:31:24 +02001305 ('EAI_AGAIN', -3),
Charles-François Natali13859bf2011-12-10 13:16:44 +01001306 ('EAI_FAIL', -4),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001307 ('EAI_NONAME', -2),
1308 ('EAI_NODATA', -5),
Antoine Pitrou390ea0f2011-04-29 00:44:33 +02001309 # Encountered when trying to resolve IPv6-only hostnames
1310 ('WSANO_DATA', 11004),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001311 ]
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001312
Éric Araujoaf5bacf2011-07-15 17:50:15 +02001313 denied = ResourceDenied("Resource %r is not available" % resource_name)
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001314 captured_errnos = errnos
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001315 gai_errnos = []
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001316 if not captured_errnos:
1317 captured_errnos = [getattr(errno, name, num)
1318 for (name, num) in default_errnos]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001319 gai_errnos = [getattr(socket, name, num)
1320 for (name, num) in default_gai_errnos]
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001321
1322 def filter_error(err):
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001323 n = getattr(err, 'errno', None)
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001324 if (isinstance(err, socket.timeout) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001325 (isinstance(err, socket.gaierror) and n in gai_errnos) or
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001326 (isinstance(err, urllib.error.HTTPError) and
1327 500 <= err.code <= 599) or
Berker Peksag8b63d3a2014-10-25 05:42:30 +03001328 (isinstance(err, urllib.error.URLError) and
Ned Deilyce8f5de2015-03-22 01:14:48 -07001329 (("ConnectionRefusedError" in err.reason) or
1330 ("TimeoutError" in err.reason))) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001331 n in captured_errnos):
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001332 if not verbose:
1333 sys.stderr.write(denied.args[0] + "\n")
1334 raise denied from err
1335
1336 old_timeout = socket.getdefaulttimeout()
1337 try:
1338 if timeout is not None:
1339 socket.setdefaulttimeout(timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001340 yield
Berker Peksag52c0c332015-04-08 11:24:27 +03001341 except nntplib.NNTPTemporaryError as err:
1342 if verbose:
1343 sys.stderr.write(denied.args[0] + "\n")
1344 raise denied from err
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001345 except OSError as err:
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001346 # urllib can wrap original socket errors multiple times (!), we must
1347 # unwrap to get at the original error.
1348 while True:
1349 a = err.args
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001350 if len(a) >= 1 and isinstance(a[0], OSError):
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001351 err = a[0]
1352 # The error can also be wrapped as args[1]:
1353 # except socket.error as msg:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001354 # raise OSError('socket error', msg).with_traceback(sys.exc_info()[2])
1355 elif len(a) >= 2 and isinstance(a[1], OSError):
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001356 err = a[1]
1357 else:
1358 break
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001359 filter_error(err)
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001360 raise
1361 # XXX should we catch generic exceptions and look for their
1362 # __cause__ or __context__?
1363 finally:
1364 socket.setdefaulttimeout(old_timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001365
1366
1367@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001368def captured_output(stream_name):
Ezio Melotti07352b02011-05-14 14:51:18 +03001369 """Return a context manager used by captured_stdout/stdin/stderr
Ezio Melottifc778fd2011-05-14 08:22:47 +03001370 that temporarily replaces the sys stream *stream_name* with a StringIO."""
Thomas Woutersed03b412007-08-28 21:37:11 +00001371 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001372 orig_stdout = getattr(sys, stream_name)
1373 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001374 try:
1375 yield getattr(sys, stream_name)
1376 finally:
1377 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001378
1379def captured_stdout():
Ezio Melottifc778fd2011-05-14 08:22:47 +03001380 """Capture the output of sys.stdout:
1381
R David Murray5a33f812013-07-11 12:28:40 -04001382 with captured_stdout() as stdout:
Ezio Melottifc778fd2011-05-14 08:22:47 +03001383 print("hello")
Serhiy Storchaka9f8a8912015-04-03 18:12:41 +03001384 self.assertEqual(stdout.getvalue(), "hello\\n")
Ezio Melottifc778fd2011-05-14 08:22:47 +03001385 """
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001386 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +00001387
Nick Coghlan6b22f3f2010-12-12 15:24:21 +00001388def captured_stderr():
R David Murray5a33f812013-07-11 12:28:40 -04001389 """Capture the output of sys.stderr:
1390
1391 with captured_stderr() as stderr:
1392 print("hello", file=sys.stderr)
Serhiy Storchaka9f8a8912015-04-03 18:12:41 +03001393 self.assertEqual(stderr.getvalue(), "hello\\n")
R David Murray5a33f812013-07-11 12:28:40 -04001394 """
Nick Coghlan6b22f3f2010-12-12 15:24:21 +00001395 return captured_output("stderr")
1396
Nick Coghlan6ead5522009-10-18 13:19:33 +00001397def captured_stdin():
R David Murray5a33f812013-07-11 12:28:40 -04001398 """Capture the input to sys.stdin:
1399
1400 with captured_stdin() as stdin:
Serhiy Storchaka9f8a8912015-04-03 18:12:41 +03001401 stdin.write('hello\\n')
R David Murray5a33f812013-07-11 12:28:40 -04001402 stdin.seek(0)
1403 # call test code that consumes from sys.stdin
1404 captured = input()
1405 self.assertEqual(captured, "hello")
1406 """
Nick Coghlan6ead5522009-10-18 13:19:33 +00001407 return captured_output("stdin")
1408
Ezio Melotti07352b02011-05-14 14:51:18 +03001409
Benjamin Petersone549ead2009-03-28 21:42:05 +00001410def gc_collect():
1411 """Force as many objects as possible to be collected.
1412
1413 In non-CPython implementations of Python, this is needed because timely
1414 deallocation is not guaranteed by the garbage collector. (Even in CPython
1415 this can be the case in case of reference cycles.) This means that __del__
1416 methods may be called later than expected and weakrefs may remain alive for
1417 longer than expected. This function tries its best to force all garbage
1418 objects to disappear.
1419 """
Benjamin Petersone549ead2009-03-28 21:42:05 +00001420 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +00001421 if is_jython:
1422 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00001423 gc.collect()
1424 gc.collect()
1425
Benjamin Peterson31f4beb2011-07-14 12:48:01 -05001426@contextlib.contextmanager
1427def disable_gc():
1428 have_gc = gc.isenabled()
1429 gc.disable()
1430 try:
1431 yield
1432 finally:
1433 if have_gc:
1434 gc.enable()
1435
Thomas Woutersed03b412007-08-28 21:37:11 +00001436
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001437def python_is_optimized():
1438 """Find if Python was built with optimizations."""
Antoine Pitrou64474542010-10-31 11:34:47 +00001439 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001440 final_opt = ""
1441 for opt in cflags.split():
1442 if opt.startswith('-O'):
1443 final_opt = opt
Victor Stinnerd7aa5242015-03-27 15:36:01 +01001444 return final_opt not in ('', '-O0', '-Og')
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001445
1446
Martin v. Löwis2b168442012-07-29 16:38:45 +02001447_header = 'nP'
1448_align = '0n'
Martin v. Löwis33f79972012-07-29 16:33:05 +02001449if hasattr(sys, "gettotalrefcount"):
1450 _header = '2P' + _header
Martin v. Löwis2b168442012-07-29 16:38:45 +02001451 _align = '0P'
1452_vheader = _header + 'n'
Martin v. Löwis33f79972012-07-29 16:33:05 +02001453
1454def calcobjsize(fmt):
Martin v. Löwis2b168442012-07-29 16:38:45 +02001455 return struct.calcsize(_header + fmt + _align)
Martin v. Löwis33f79972012-07-29 16:33:05 +02001456
1457def calcvobjsize(fmt):
Martin v. Löwis2b168442012-07-29 16:38:45 +02001458 return struct.calcsize(_vheader + fmt + _align)
Martin v. Löwis33f79972012-07-29 16:33:05 +02001459
1460
1461_TPFLAGS_HAVE_GC = 1<<14
1462_TPFLAGS_HEAPTYPE = 1<<9
1463
1464def check_sizeof(test, o, size):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001465 import _testcapi
Martin v. Löwis33f79972012-07-29 16:33:05 +02001466 result = sys.getsizeof(o)
1467 # add GC header size
1468 if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
1469 ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
1470 size += _testcapi.SIZEOF_PYGC_HEAD
1471 msg = 'wrong size for %s: got %d, expected %d' \
1472 % (type(o), result, size)
1473 test.assertEqual(result, size, msg)
1474
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001475#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001476# Decorator for running a function in a different locale, correctly resetting
1477# it afterwards.
1478
1479def run_with_locale(catstr, *locales):
1480 def decorator(func):
1481 def inner(*args, **kwds):
1482 try:
1483 import locale
1484 category = getattr(locale, catstr)
1485 orig_locale = locale.setlocale(category)
1486 except AttributeError:
1487 # if the test author gives us an invalid category string
1488 raise
1489 except:
1490 # cannot retrieve original locale, so do nothing
1491 locale = orig_locale = None
1492 else:
1493 for loc in locales:
1494 try:
1495 locale.setlocale(category, loc)
1496 break
1497 except:
1498 pass
1499
1500 # now run the function, resetting the locale on exceptions
1501 try:
1502 return func(*args, **kwds)
1503 finally:
1504 if locale and orig_locale:
1505 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +00001506 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +00001507 inner.__doc__ = func.__doc__
1508 return inner
1509 return decorator
1510
1511#=======================================================================
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001512# Decorator for running a function in a specific timezone, correctly
1513# resetting it afterwards.
1514
1515def run_with_tz(tz):
1516 def decorator(func):
1517 def inner(*args, **kwds):
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001518 try:
1519 tzset = time.tzset
1520 except AttributeError:
1521 raise unittest.SkipTest("tzset required")
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001522 if 'TZ' in os.environ:
1523 orig_tz = os.environ['TZ']
1524 else:
1525 orig_tz = None
1526 os.environ['TZ'] = tz
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001527 tzset()
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001528
1529 # now run the function, resetting the tz on exceptions
1530 try:
1531 return func(*args, **kwds)
1532 finally:
Benjamin Petersonb29614e2012-10-09 11:16:03 -04001533 if orig_tz is None:
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001534 del os.environ['TZ']
1535 else:
1536 os.environ['TZ'] = orig_tz
1537 time.tzset()
1538
1539 inner.__name__ = func.__name__
1540 inner.__doc__ = func.__doc__
1541 return inner
1542 return decorator
1543
1544#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +00001545# Big-memory-test support. Separate from 'resources' because memory use
1546# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001547
1548# Some handy shorthands. Note that these are used for byte-limits as well
1549# as size-limits, in the various bigmem tests
1550_1M = 1024*1024
1551_1G = 1024 * _1M
1552_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001553_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +00001554
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001555MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001556
Thomas Wouters477c8d52006-05-27 19:21:47 +00001557def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001558 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001559 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001560 sizes = {
1561 'k': 1024,
1562 'm': _1M,
1563 'g': _1G,
1564 't': 1024*_1G,
1565 }
1566 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
1567 re.IGNORECASE | re.VERBOSE)
1568 if m is None:
1569 raise ValueError('Invalid memory limit %r' % (limit,))
1570 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001571 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001572 if memlimit > MAX_Py_ssize_t:
1573 memlimit = MAX_Py_ssize_t
1574 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001575 raise ValueError('Memory limit %r too low to be useful' % (limit,))
1576 max_memuse = memlimit
1577
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001578class _MemoryWatchdog:
1579 """An object which periodically watches the process' memory consumption
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001580 and prints it out.
1581 """
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001582
1583 def __init__(self):
1584 self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
1585 self.started = False
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001586
1587 def start(self):
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001588 try:
Charles-François Natali55bce632012-03-24 10:06:23 +01001589 f = open(self.procfile, 'r')
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001590 except OSError as e:
1591 warnings.warn('/proc not available for stats: {}'.format(e),
1592 RuntimeWarning)
1593 sys.stderr.flush()
1594 return
Charles-François Natali55bce632012-03-24 10:06:23 +01001595
1596 watchdog_script = findfile("memory_watchdog.py")
1597 self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
1598 stdin=f, stderr=subprocess.DEVNULL)
1599 f.close()
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001600 self.started = True
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001601
1602 def stop(self):
Charles-François Natali55bce632012-03-24 10:06:23 +01001603 if self.started:
1604 self.mem_watchdog.terminate()
1605 self.mem_watchdog.wait()
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001606
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001607
1608def bigmemtest(size, memuse, dry_run=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001609 """Decorator for bigmem tests.
1610
1611 'minsize' is the minimum useful size for the test (in arbitrary,
1612 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001613 the test, or a good estimate of it.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001614
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001615 if 'dry_run' is False, it means the test doesn't support dummy runs
1616 when -M is not specified.
Thomas Wouters518b5ae2011-03-25 11:42:37 +01001617 """
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001618 def decorator(f):
1619 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001620 size = wrapper.size
1621 memuse = wrapper.memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001622 if not real_max_memuse:
1623 maxsize = 5147
1624 else:
1625 maxsize = size
1626
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001627 if ((real_max_memuse or not dry_run)
1628 and real_max_memuse < maxsize * memuse):
1629 raise unittest.SkipTest(
1630 "not enough memory: %.1fG minimum needed"
1631 % (size * memuse / (1024 ** 3)))
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001632
Charles-François Natali55bce632012-03-24 10:06:23 +01001633 if real_max_memuse and verbose:
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001634 print()
1635 print(" ... expected peak memory use: {peak:.1f}G"
1636 .format(peak=size * memuse / (1024 ** 3)))
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001637 watchdog = _MemoryWatchdog()
1638 watchdog.start()
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001639 else:
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001640 watchdog = None
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001641
1642 try:
1643 return f(self, maxsize)
1644 finally:
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001645 if watchdog:
1646 watchdog.stop()
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001647
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001648 wrapper.size = size
1649 wrapper.memuse = memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001650 return wrapper
1651 return decorator
1652
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001653def bigaddrspacetest(f):
1654 """Decorator for tests that fill the address space."""
1655 def wrapper(self):
1656 if max_memuse < MAX_Py_ssize_t:
Antoine Pitrou98c62bd2011-01-12 21:58:39 +00001657 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
Antoine Pitroue0d3f8a2011-01-12 21:50:44 +00001658 raise unittest.SkipTest(
1659 "not enough memory: try a 32-bit build instead")
1660 else:
1661 raise unittest.SkipTest(
1662 "not enough memory: %.1fG minimum needed"
1663 % (MAX_Py_ssize_t / (1024 ** 3)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001664 else:
1665 return f(self)
1666 return wrapper
1667
Thomas Wouters477c8d52006-05-27 19:21:47 +00001668#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +00001669# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001670
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001671class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001672 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001673 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001674 test(result)
1675 return result
1676
Benjamin Petersone549ead2009-03-28 21:42:05 +00001677def _id(obj):
1678 return obj
1679
1680def requires_resource(resource):
Antoine Pitroud20a5f62011-02-26 15:58:05 +00001681 if resource == 'gui' and not _is_gui_available():
Zachary Warececed6b2014-05-02 10:51:07 -05001682 return unittest.skip(_is_gui_available.reason)
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +00001683 if is_resource_enabled(resource):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001684 return _id
1685 else:
1686 return unittest.skip("resource {0!r} is not enabled".format(resource))
1687
1688def cpython_only(test):
1689 """
1690 Decorator for tests only applicable on CPython.
1691 """
1692 return impl_detail(cpython=True)(test)
1693
1694def impl_detail(msg=None, **guards):
1695 if check_impl_detail(**guards):
1696 return _id
1697 if msg is None:
1698 guardnames, default = _parse_guards(guards)
1699 if default:
1700 msg = "implementation detail not available on {0}"
1701 else:
1702 msg = "implementation detail specific to {0}"
1703 guardnames = sorted(guardnames.keys())
1704 msg = msg.format(' or '.join(guardnames))
1705 return unittest.skip(msg)
1706
1707def _parse_guards(guards):
1708 # Returns a tuple ({platform_name: run_me}, default_value)
1709 if not guards:
1710 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +00001711 is_true = list(guards.values())[0]
1712 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001713 return (guards, not is_true)
1714
1715# Use the following check to guard CPython's implementation-specific tests --
1716# or to run them only on the implementation(s) guarded by the arguments.
1717def check_impl_detail(**guards):
1718 """This function returns True or False depending on the host platform.
1719 Examples:
1720 if check_impl_detail(): # only on CPython (default)
1721 if check_impl_detail(jython=True): # only on Jython
1722 if check_impl_detail(cpython=False): # everywhere except on CPython
1723 """
1724 guards, default = _parse_guards(guards)
1725 return guards.get(platform.python_implementation().lower(), default)
1726
1727
Brett Cannon31f59292011-02-21 19:29:56 +00001728def no_tracing(func):
1729 """Decorator to temporarily turn off tracing for the duration of a test."""
1730 if not hasattr(sys, 'gettrace'):
1731 return func
1732 else:
1733 @functools.wraps(func)
1734 def wrapper(*args, **kwargs):
1735 original_trace = sys.gettrace()
1736 try:
1737 sys.settrace(None)
1738 return func(*args, **kwargs)
1739 finally:
1740 sys.settrace(original_trace)
1741 return wrapper
1742
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001743
Brett Cannon7a540732011-02-22 03:04:06 +00001744def refcount_test(test):
1745 """Decorator for tests which involve reference counting.
1746
1747 To start, the decorator does not run the test if is not run by CPython.
1748 After that, any trace function is unset during the test to prevent
1749 unexpected refcounts caused by the trace function.
1750
1751 """
1752 return no_tracing(cpython_only(test))
1753
1754
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001755def _filter_suite(suite, pred):
1756 """Recursively filter test cases in a suite based on a predicate."""
1757 newtests = []
1758 for test in suite._tests:
1759 if isinstance(test, unittest.TestSuite):
1760 _filter_suite(test, pred)
1761 newtests.append(test)
1762 else:
1763 if pred(test):
1764 newtests.append(test)
1765 suite._tests = newtests
1766
Guido van Rossumd8faa362007-04-27 19:54:29 +00001767def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001768 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001769 if verbose:
Antoine Pitrou216a3bc2011-07-23 22:33:39 +02001770 runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
1771 failfast=failfast)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001772 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001773 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001774
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001775 result = runner.run(suite)
1776 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001777 if len(result.errors) == 1 and not result.failures:
1778 err = result.errors[0][1]
1779 elif len(result.failures) == 1 and not result.errors:
1780 err = result.failures[0][1]
1781 else:
R. David Murray723357e2009-10-19 18:06:17 +00001782 err = "multiple errors occurred"
1783 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001784 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001785
Barry Warsawc10d6902001-09-20 06:30:41 +00001786
Walter Dörwald21d3a322003-05-01 17:45:56 +00001787def run_unittest(*classes):
1788 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001789 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001790 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001791 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001792 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001793 if cls in sys.modules:
1794 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1795 else:
1796 raise ValueError("str arguments must be keys in sys.modules")
1797 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001798 suite.addTest(cls)
1799 else:
1800 suite.addTest(unittest.makeSuite(cls))
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001801 def case_pred(test):
1802 if match_tests is None:
1803 return True
1804 for name in test.id().split("."):
1805 if fnmatch.fnmatchcase(name, match_tests):
1806 return True
1807 return False
1808 _filter_suite(suite, case_pred)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001809 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001810
Serhiy Storchaka9d0add02013-01-27 19:47:45 +02001811#=======================================================================
1812# Check for the presence of docstrings.
1813
Nick Coghlan561eb5c2013-10-26 22:20:43 +10001814# Rather than trying to enumerate all the cases where docstrings may be
1815# disabled, we just check for that directly
1816
1817def _check_docstrings():
1818 """Just used to check if docstrings are enabled"""
1819
Nick Coghlan624a74e2013-10-27 14:19:12 +10001820MISSING_C_DOCSTRINGS = (check_impl_detail() and
1821 sys.platform != 'win32' and
1822 not sysconfig.get_config_var('WITH_DOC_STRINGS'))
1823
1824HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and
1825 not MISSING_C_DOCSTRINGS)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +02001826
1827requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
1828 "test requires docstrings")
1829
Barry Warsawc10d6902001-09-20 06:30:41 +00001830
Tim Petersa0a62222001-09-09 06:12:01 +00001831#=======================================================================
1832# doctest driver.
1833
Stefan Krah1919b7e2012-03-21 18:25:23 +01001834def run_doctest(module, verbosity=None, optionflags=0):
Tim Peters17111f32001-10-03 04:08:26 +00001835 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001836
1837 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001838 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001839 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001840 """
1841
1842 import doctest
1843
1844 if verbosity is None:
1845 verbosity = verbose
1846 else:
1847 verbosity = None
1848
Stefan Krah1919b7e2012-03-21 18:25:23 +01001849 f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags)
Victor Stinnerbddc4d42011-06-29 15:52:46 +02001850 if f:
1851 raise TestFailed("%d of %d doctests failed" % (f, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001852 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001853 print('doctest (%s) ... %d tests with zero failures' %
1854 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001855 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001856
Antoine Pitrou060cee22009-11-13 16:29:04 +00001857
1858#=======================================================================
1859# Support for saving and restoring the imported modules.
1860
1861def modules_setup():
1862 return sys.modules.copy(),
1863
1864def modules_cleanup(oldmodules):
1865 # Encoders/decoders are registered permanently within the internal
1866 # codec cache. If we destroy the corresponding modules their
1867 # globals will be set to None which will trip up the cached functions.
1868 encodings = [(k, v) for k, v in sys.modules.items()
1869 if k.startswith('encodings.')]
1870 sys.modules.clear()
1871 sys.modules.update(encodings)
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001872 # XXX: This kind of problem can affect more than just encodings. In particular
Eric Smitha3e8f3d2011-01-11 10:24:34 +00001873 # extension modules (such as _ssl) don't cope with reloading properly.
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001874 # Really, test modules should be cleaning out the test specific modules they
1875 # know they added (ala test_runpy) rather than relying on this function (as
1876 # test_importhooks and test_pkg do currently).
1877 # Implicitly imported *real* modules should be left alone (see issue 10556).
Antoine Pitrou060cee22009-11-13 16:29:04 +00001878 sys.modules.update(oldmodules)
1879
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001880#=======================================================================
1881# Threading support to prevent reporting refleaks when running regrtest.py -R
1882
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001883# NOTE: we use thread._count() rather than threading.enumerate() (or the
1884# moral equivalent thereof) because a threading.Thread object is still alive
1885# until its __bootstrap() method has returned, even after it has been
1886# unregistered from the threading module.
1887# thread._count(), on the other hand, only gets decremented *after* the
1888# __bootstrap() method has returned, which gives us reliable reference counts
1889# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001890
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001891def threading_setup():
Victor Stinner45df8202010-04-28 22:31:17 +00001892 if _thread:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001893 return _thread._count(), threading._dangling.copy()
Victor Stinner45df8202010-04-28 22:31:17 +00001894 else:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001895 return 1, ()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001896
Antoine Pitrou707f2282011-07-15 22:29:44 +02001897def threading_cleanup(*original_values):
Victor Stinner45df8202010-04-28 22:31:17 +00001898 if not _thread:
1899 return
Antoine Pitrou05eafa82013-08-16 21:02:02 +02001900 _MAX_COUNT = 100
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001901 for count in range(_MAX_COUNT):
Antoine Pitrou707f2282011-07-15 22:29:44 +02001902 values = _thread._count(), threading._dangling
1903 if values == original_values:
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001904 break
Antoine Pitrou05eafa82013-08-16 21:02:02 +02001905 time.sleep(0.01)
Antoine Pitrou707f2282011-07-15 22:29:44 +02001906 gc_collect()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001907 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001908
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001909def reap_threads(func):
Victor Stinner45df8202010-04-28 22:31:17 +00001910 """Use this function when threads are being used. This will
1911 ensure that the threads are cleaned up even when the test fails.
1912 If threading is unavailable this function does nothing.
1913 """
1914 if not _thread:
1915 return func
1916
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001917 @functools.wraps(func)
1918 def decorator(*args):
1919 key = threading_setup()
1920 try:
1921 return func(*args)
1922 finally:
1923 threading_cleanup(*key)
1924 return decorator
1925
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001926def reap_children():
1927 """Use this function at the end of test_main() whenever sub-processes
1928 are started. This will help ensure that no extra children (zombies)
1929 stick around to hog resources and create problems when looking
1930 for refleaks.
1931 """
1932
1933 # Reap all our dead child processes so we don't leave zombies around.
1934 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001935 if hasattr(os, 'waitpid'):
1936 any_process = -1
1937 while True:
1938 try:
1939 # This will raise an exception on Windows. That's ok.
1940 pid, status = os.waitpid(any_process, os.WNOHANG)
1941 if pid == 0:
1942 break
1943 except:
1944 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001945
1946@contextlib.contextmanager
Serhiy Storchaka263dcd22015-04-01 13:01:14 +03001947def start_threads(threads, unlock=None):
1948 threads = list(threads)
1949 started = []
1950 try:
1951 try:
1952 for t in threads:
1953 t.start()
1954 started.append(t)
1955 except:
1956 if verbose:
1957 print("Can't start %d threads, only %d threads started" %
1958 (len(threads), len(started)))
1959 raise
1960 yield
1961 finally:
1962 try:
1963 if unlock:
1964 unlock()
1965 endtime = starttime = time.time()
1966 for timeout in range(1, 16):
1967 endtime += 60
1968 for t in started:
1969 t.join(max(endtime - time.time(), 0.01))
1970 started = [t for t in started if t.isAlive()]
1971 if not started:
1972 break
1973 if verbose:
1974 print('Unable to join %d threads during a period of '
1975 '%d minutes' % (len(started), timeout))
1976 finally:
1977 started = [t for t in started if t.isAlive()]
1978 if started:
1979 faulthandler.dump_traceback(sys.stdout)
1980 raise AssertionError('Unable to join %d threads' % len(started))
1981
1982@contextlib.contextmanager
Collin Winterf2bf2b32010-03-17 00:41:56 +00001983def swap_attr(obj, attr, new_val):
1984 """Temporary swap out an attribute with a new object.
1985
1986 Usage:
1987 with swap_attr(obj, "attr", 5):
1988 ...
1989
1990 This will set obj.attr to 5 for the duration of the with: block,
1991 restoring the old value at the end of the block. If `attr` doesn't
1992 exist on `obj`, it will be created and then deleted at the end of the
1993 block.
1994 """
1995 if hasattr(obj, attr):
1996 real_val = getattr(obj, attr)
1997 setattr(obj, attr, new_val)
1998 try:
1999 yield
2000 finally:
2001 setattr(obj, attr, real_val)
2002 else:
2003 setattr(obj, attr, new_val)
2004 try:
2005 yield
2006 finally:
2007 delattr(obj, attr)
2008
2009@contextlib.contextmanager
2010def swap_item(obj, item, new_val):
2011 """Temporary swap out an item with a new object.
2012
2013 Usage:
2014 with swap_item(obj, "item", 5):
2015 ...
2016
2017 This will set obj["item"] to 5 for the duration of the with: block,
2018 restoring the old value at the end of the block. If `item` doesn't
2019 exist on `obj`, it will be created and then deleted at the end of the
2020 block.
2021 """
2022 if item in obj:
2023 real_val = obj[item]
2024 obj[item] = new_val
2025 try:
2026 yield
2027 finally:
2028 obj[item] = real_val
2029 else:
2030 obj[item] = new_val
2031 try:
2032 yield
2033 finally:
2034 del obj[item]
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00002035
2036def strip_python_stderr(stderr):
2037 """Strip the stderr of a Python process from potential debug output
2038 emitted by the interpreter.
2039
2040 This will typically be run on the result of the communicate() method
2041 of a subprocess.Popen object.
2042 """
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01002043 stderr = re.sub(br"\[\d+ refs, \d+ blocks\]\r?\n?", b"", stderr).strip()
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00002044 return stderr
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00002045
2046def args_from_interpreter_flags():
2047 """Return a list of command-line arguments reproducing the current
Brett Cannonb880c152011-03-15 16:03:09 -04002048 settings in sys.flags and sys.warnoptions."""
Antoine Pitrouebdcd852012-05-18 18:33:07 +02002049 return subprocess._args_from_interpreter_flags()
Vinay Sajip129fd042010-12-10 08:19:38 +00002050
2051#============================================================
2052# Support for assertions about logging.
2053#============================================================
2054
2055class TestHandler(logging.handlers.BufferingHandler):
2056 def __init__(self, matcher):
2057 # BufferingHandler takes a "capacity" argument
2058 # so as to know when to flush. As we're overriding
2059 # shouldFlush anyway, we can set a capacity of zero.
2060 # You can call flush() manually to clear out the
2061 # buffer.
2062 logging.handlers.BufferingHandler.__init__(self, 0)
2063 self.matcher = matcher
2064
2065 def shouldFlush(self):
2066 return False
2067
2068 def emit(self, record):
2069 self.format(record)
2070 self.buffer.append(record.__dict__)
2071
2072 def matches(self, **kwargs):
2073 """
2074 Look for a saved dict whose keys/values match the supplied arguments.
2075 """
2076 result = False
2077 for d in self.buffer:
2078 if self.matcher.matches(d, **kwargs):
2079 result = True
2080 break
2081 return result
2082
2083class Matcher(object):
2084
2085 _partial_matches = ('msg', 'message')
2086
2087 def matches(self, d, **kwargs):
2088 """
2089 Try to match a single dict with the supplied arguments.
2090
2091 Keys whose values are strings and which are in self._partial_matches
2092 will be checked for partial (i.e. substring) matches. You can extend
2093 this scheme to (for example) do regular expression matching, etc.
2094 """
2095 result = True
2096 for k in kwargs:
2097 v = kwargs[k]
2098 dv = d.get(k)
2099 if not self.match_value(k, dv, v):
2100 result = False
2101 break
2102 return result
2103
2104 def match_value(self, k, dv, v):
2105 """
2106 Try to match a single stored value (dv) with a supplied value (v).
2107 """
2108 if type(v) != type(dv):
2109 result = False
2110 elif type(dv) is not str or k not in self._partial_matches:
2111 result = (v == dv)
2112 else:
2113 result = dv.find(v) >= 0
2114 return result
Brian Curtin3b4499c2010-12-28 14:31:47 +00002115
2116
2117_can_symlink = None
2118def can_symlink():
2119 global _can_symlink
2120 if _can_symlink is not None:
2121 return _can_symlink
Brett Cannonee877a02011-03-15 17:32:14 -04002122 symlink_path = TESTFN + "can_symlink"
Brian Curtin3b4499c2010-12-28 14:31:47 +00002123 try:
Brett Cannonee877a02011-03-15 17:32:14 -04002124 os.symlink(TESTFN, symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00002125 can = True
Brian Curtind25aef52011-06-13 15:16:04 -05002126 except (OSError, NotImplementedError, AttributeError):
Brian Curtin3b4499c2010-12-28 14:31:47 +00002127 can = False
Victor Stinner62ec61f2011-06-07 12:17:15 +02002128 else:
2129 os.remove(symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00002130 _can_symlink = can
2131 return can
2132
2133def skip_unless_symlink(test):
2134 """Skip decorator for tests that require functional symlink"""
2135 ok = can_symlink()
2136 msg = "Requires functional symlink implementation"
2137 return test if ok else unittest.skip(msg)(test)
Antoine Pitroue8706232011-03-15 21:05:36 +01002138
Antoine Pitrou424246f2012-05-12 19:02:01 +02002139_can_xattr = None
2140def can_xattr():
2141 global _can_xattr
2142 if _can_xattr is not None:
2143 return _can_xattr
2144 if not hasattr(os, "setxattr"):
2145 can = False
2146 else:
Hynek Schlawacke02ba102012-05-23 11:22:44 +02002147 tmp_fp, tmp_name = tempfile.mkstemp()
Antoine Pitrou424246f2012-05-12 19:02:01 +02002148 try:
2149 with open(TESTFN, "wb") as fp:
2150 try:
Hynek Schlawacke02ba102012-05-23 11:22:44 +02002151 # TESTFN & tempfile may use different file systems with
2152 # different capabilities
Larry Hastings9cf065c2012-06-22 16:30:09 -07002153 os.setxattr(tmp_fp, b"user.test", b"")
2154 os.setxattr(fp.fileno(), b"user.test", b"")
Antoine Pitrou424246f2012-05-12 19:02:01 +02002155 # Kernels < 2.6.39 don't respect setxattr flags.
2156 kernel_version = platform.release()
2157 m = re.match("2.6.(\d{1,2})", kernel_version)
2158 can = m is None or int(m.group(1)) >= 39
2159 except OSError:
2160 can = False
2161 finally:
2162 unlink(TESTFN)
Hynek Schlawacke02ba102012-05-23 11:22:44 +02002163 unlink(tmp_name)
Antoine Pitrou424246f2012-05-12 19:02:01 +02002164 _can_xattr = can
2165 return can
2166
2167def skip_unless_xattr(test):
2168 """Skip decorator for tests that require functional extended attributes"""
2169 ok = can_xattr()
2170 msg = "no non-broken extended attribute support"
2171 return test if ok else unittest.skip(msg)(test)
2172
Ezio Melotti25a40452013-03-05 20:26:17 +02002173
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002174def fs_is_case_insensitive(directory):
2175 """Detects if the file system for the specified directory is case-insensitive."""
Antoine Pitroue3207fe2015-03-08 00:15:05 +01002176 with tempfile.NamedTemporaryFile(dir=directory) as base:
2177 base_path = base.name
2178 case_path = base_path.upper()
2179 if case_path == base_path:
2180 case_path = base_path.lower()
2181 try:
2182 return os.path.samefile(base_path, case_path)
2183 except FileNotFoundError:
2184 return False
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002185
2186
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002187class SuppressCrashReport:
2188 """Try to prevent a crash report from popping up.
2189
2190 On Windows, don't display the Windows Error Reporting dialog. On UNIX,
2191 disable the creation of coredump file.
2192 """
2193 old_value = None
Steve Dowerc55a3162015-02-23 07:56:13 -08002194 old_modes = None
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002195
2196 def __enter__(self):
2197 """On Windows, disable Windows Error Reporting dialogs using
2198 SetErrorMode.
2199
2200 On UNIX, try to save the previous core file size limit, then set
2201 soft limit to 0.
2202 """
2203 if sys.platform.startswith('win'):
2204 # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
2205 # GetErrorMode is not available on Windows XP and Windows Server 2003,
2206 # but SetErrorMode returns the previous value, so we can use that
2207 import ctypes
2208 self._k32 = ctypes.windll.kernel32
2209 SEM_NOGPFAULTERRORBOX = 0x02
2210 self.old_value = self._k32.SetErrorMode(SEM_NOGPFAULTERRORBOX)
2211 self._k32.SetErrorMode(self.old_value | SEM_NOGPFAULTERRORBOX)
Steve Dowerc55a3162015-02-23 07:56:13 -08002212
2213 # Suppress assert dialogs in debug builds
2214 # (see http://bugs.python.org/issue23314)
2215 try:
2216 import msvcrt
2217 msvcrt.CrtSetReportMode
2218 except (AttributeError, ImportError):
2219 # no msvcrt or a release build
2220 pass
2221 else:
2222 self.old_modes = {}
2223 for report_type in [msvcrt.CRT_WARN,
2224 msvcrt.CRT_ERROR,
2225 msvcrt.CRT_ASSERT]:
2226 old_mode = msvcrt.CrtSetReportMode(report_type,
2227 msvcrt.CRTDBG_MODE_FILE)
2228 old_file = msvcrt.CrtSetReportFile(report_type,
2229 msvcrt.CRTDBG_FILE_STDERR)
2230 self.old_modes[report_type] = old_mode, old_file
2231
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002232 else:
2233 if resource is not None:
2234 try:
2235 self.old_value = resource.getrlimit(resource.RLIMIT_CORE)
2236 resource.setrlimit(resource.RLIMIT_CORE,
2237 (0, self.old_value[1]))
2238 except (ValueError, OSError):
2239 pass
2240 if sys.platform == 'darwin':
2241 # Check if the 'Crash Reporter' on OSX was configured
2242 # in 'Developer' mode and warn that it will get triggered
2243 # when it is.
2244 #
2245 # This assumes that this context manager is used in tests
2246 # that might trigger the next manager.
2247 value = subprocess.Popen(['/usr/bin/defaults', 'read',
2248 'com.apple.CrashReporter', 'DialogType'],
2249 stdout=subprocess.PIPE).communicate()[0]
2250 if value.strip() == b'developer':
2251 print("this test triggers the Crash Reporter, "
2252 "that is intentional", end='', flush=True)
2253
2254 return self
2255
2256 def __exit__(self, *ignore_exc):
2257 """Restore Windows ErrorMode or core file behavior to initial value."""
2258 if self.old_value is None:
2259 return
2260
2261 if sys.platform.startswith('win'):
2262 self._k32.SetErrorMode(self.old_value)
Steve Dowerc55a3162015-02-23 07:56:13 -08002263
2264 if self.old_modes:
2265 import msvcrt
2266 for report_type, (old_mode, old_file) in self.old_modes.items():
2267 msvcrt.CrtSetReportMode(report_type, old_mode)
2268 msvcrt.CrtSetReportFile(report_type, old_file)
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002269 else:
2270 if resource is not None:
2271 try:
2272 resource.setrlimit(resource.RLIMIT_CORE, self.old_value)
2273 except (ValueError, OSError):
2274 pass
Ezio Melotti25a40452013-03-05 20:26:17 +02002275
2276
Antoine Pitrou2c50a092011-03-15 21:02:59 +01002277def patch(test_instance, object_to_patch, attr_name, new_value):
2278 """Override 'object_to_patch'.'attr_name' with 'new_value'.
2279
2280 Also, add a cleanup procedure to 'test_instance' to restore
2281 'object_to_patch' value for 'attr_name'.
2282 The 'attr_name' should be a valid attribute for 'object_to_patch'.
2283
2284 """
2285 # check that 'attr_name' is a real attribute for 'object_to_patch'
2286 # will raise AttributeError if it does not exist
2287 getattr(object_to_patch, attr_name)
2288
2289 # keep a copy of the old value
2290 attr_is_local = False
2291 try:
2292 old_value = object_to_patch.__dict__[attr_name]
2293 except (AttributeError, KeyError):
2294 old_value = getattr(object_to_patch, attr_name, None)
2295 else:
2296 attr_is_local = True
2297
2298 # restore the value when the test is done
2299 def cleanup():
2300 if attr_is_local:
2301 setattr(object_to_patch, attr_name, old_value)
2302 else:
2303 delattr(object_to_patch, attr_name)
2304
2305 test_instance.addCleanup(cleanup)
2306
2307 # actually override the attribute
2308 setattr(object_to_patch, attr_name, new_value)
Victor Stinnered3b0bc2013-11-23 12:27:24 +01002309
2310
2311def run_in_subinterp(code):
2312 """
2313 Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
2314 module is enabled.
2315 """
2316 # Issue #10915, #15751: PyGILState_*() functions don't work with
2317 # sub-interpreters, the tracemalloc module uses these functions internally
2318 try:
2319 import tracemalloc
2320 except ImportError:
2321 pass
2322 else:
2323 if tracemalloc.is_tracing():
2324 raise unittest.SkipTest("run_in_subinterp() cannot be used "
2325 "if tracemalloc module is tracing "
2326 "memory allocations")
Serhiy Storchakaf28ba362014-02-07 10:10:55 +02002327 import _testcapi
Victor Stinnered3b0bc2013-11-23 12:27:24 +01002328 return _testcapi.run_in_subinterp(code)