blob: 253f319c1363f669688bdfb2974be479025ca72d [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
Victor Stinner47ae7632014-07-21 21:40:19 +02009import fnmatch
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000010import functools
Benjamin Peterson8cc7d882009-06-01 23:14:51 +000011import gc
R. David Murraya21e4ca2009-03-31 23:16:50 +000012import importlib
Brett Cannon9529fbf2013-06-15 17:11:25 -040013import importlib.util
Vinay Sajip129fd042010-12-10 08:19:38 +000014import logging.handlers
Victor Stinner47ae7632014-07-21 21:40:19 +020015import os
16import platform
17import re
18import shutil
19import socket
20import stat
Antoine Pitrou75e78b62011-10-04 11:51:23 +020021import struct
Victor Stinner47ae7632014-07-21 21:40:19 +020022import subprocess
23import sys
24import sysconfig
Hynek Schlawacke02ba102012-05-23 11:22:44 +020025import tempfile
Victor Stinner47ae7632014-07-21 21:40:19 +020026import time
27import unittest
Berker Peksag8b63d3a2014-10-25 05:42:30 +030028import urllib.error
Victor Stinner47ae7632014-07-21 21:40:19 +020029import warnings
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000030
Victor Stinner45df8202010-04-28 22:31:17 +000031try:
Antoine Pitrou707f2282011-07-15 22:29:44 +020032 import _thread, threading
Brett Cannon260fbe82013-07-04 18:16:15 -040033except ImportError:
Victor Stinner45df8202010-04-28 22:31:17 +000034 _thread = None
Antoine Pitrou707f2282011-07-15 22:29:44 +020035 threading = None
36try:
37 import multiprocessing.process
Brett Cannon260fbe82013-07-04 18:16:15 -040038except ImportError:
Antoine Pitrou707f2282011-07-15 22:29:44 +020039 multiprocessing = None
40
Antoine Pitrou75e78b62011-10-04 11:51:23 +020041try:
Ezio Melotticad648c2011-05-19 21:25:10 +030042 import zlib
Brett Cannon260fbe82013-07-04 18:16:15 -040043except ImportError:
Ezio Melotticad648c2011-05-19 21:25:10 +030044 zlib = None
45
Martin v. Löwisf6b16a42012-05-01 07:58:44 +020046try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +030047 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040048except ImportError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +030049 gzip = None
50
51try:
Martin v. Löwisf6b16a42012-05-01 07:58:44 +020052 import bz2
Brett Cannon260fbe82013-07-04 18:16:15 -040053except ImportError:
Martin v. Löwisf6b16a42012-05-01 07:58:44 +020054 bz2 = None
55
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +020056try:
57 import lzma
Brett Cannon260fbe82013-07-04 18:16:15 -040058except ImportError:
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +020059 lzma = None
60
Antoine Pitroub0478b32013-09-06 20:50:00 +020061try:
62 import resource
63except ImportError:
64 resource = None
65
Barry Warsaw28a691b2010-04-17 00:19:56 +000066__all__ = [
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010067 # globals
68 "PIPE_MAX_SIZE", "verbose", "max_memuse", "use_resources", "failfast",
69 # exceptions
70 "Error", "TestFailed", "ResourceDenied",
71 # imports
72 "import_module", "import_fresh_module", "CleanImport",
73 # modules
74 "unload", "forget",
75 # io
76 "record_original_stdout", "get_original_stdout", "captured_stdout",
77 "captured_stdin", "captured_stderr",
78 # filesystem
79 "TESTFN", "SAVEDCWD", "unlink", "rmtree", "temp_cwd", "findfile",
Brett Cannonfe77f4e2013-11-22 16:14:10 -050080 "create_empty_file", "can_symlink", "fs_is_case_insensitive",
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010081 # unittest
Charles-François Natali87b3c922011-10-03 19:40:37 +020082 "is_resource_enabled", "requires", "requires_freebsd_version",
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010083 "requires_linux_version", "requires_mac_ver", "check_syntax_error",
84 "TransientResource", "time_out", "socket_peer_reset", "ioerror_peer_reset",
85 "transient_internet", "BasicTestRunner", "run_unittest", "run_doctest",
86 "skip_unless_symlink", "requires_gzip", "requires_bz2", "requires_lzma",
87 "bigmemtest", "bigaddrspacetest", "cpython_only", "get_attribute",
88 "requires_IEEE_754", "skip_unless_xattr", "requires_zlib",
Zachary Waref012ba42014-07-23 12:00:29 -050089 "anticipate_failure", "load_package_tests",
Giampaolo Rodola'1bfa7ed2013-11-12 23:08:27 +010090 # sys
91 "is_jython", "check_impl_detail",
92 # network
93 "HOST", "IPV6_ENABLED", "find_unused_port", "bind_port", "open_urlresource",
94 # processes
95 'temp_umask', "reap_children",
96 # logging
97 "TestHandler",
98 # threads
99 "threading_setup", "threading_cleanup",
100 # miscellaneous
101 "check_warnings", "EnvironmentVarGuard", "run_with_locale", "swap_item",
102 "swap_attr", "Matcher", "set_memlimit", "SuppressCrashReport", "sortdict",
103 "run_with_tz",
Antoine Pitrou4d7979b2010-09-07 21:22:56 +0000104 ]
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000105
Fred Drake1790dd42000-07-24 06:55:00 +0000106class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +0000107 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +0000108
109class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +0000110 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +0000111
Benjamin Petersone549ead2009-03-28 21:42:05 +0000112class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +0000113 """Test skipped because it requested a disallowed resource.
114
115 This is raised when a test calls requires() for a resource that
116 has not be enabled. It is used to distinguish between expected
117 and unexpected skips.
118 """
119
Nick Coghlanfce769e2009-04-11 14:30:59 +0000120@contextlib.contextmanager
121def _ignore_deprecated_imports(ignore=True):
122 """Context manager to suppress package and module deprecation
123 warnings when importing them.
124
Brett Cannond1877262012-11-17 20:46:26 -0500125 If ignore is False, this context manager has no effect.
126 """
Nick Coghlanfce769e2009-04-11 14:30:59 +0000127 if ignore:
128 with warnings.catch_warnings():
129 warnings.filterwarnings("ignore", ".+ (module|package)",
130 DeprecationWarning)
131 yield
132 else:
133 yield
134
135
Brett Cannond1877262012-11-17 20:46:26 -0500136def import_module(name, deprecated=False, *, required_on=()):
R. David Murraya21e4ca2009-03-31 23:16:50 +0000137 """Import and return the module to be tested, raising SkipTest if
138 it is not available.
139
140 If deprecated is True, any module or package deprecation messages
Brett Cannond1877262012-11-17 20:46:26 -0500141 will be suppressed. If a module is required on a platform but optional for
142 others, set required_on to an iterable of platform prefixes which will be
143 compared against sys.platform.
144 """
Nick Coghlanfce769e2009-04-11 14:30:59 +0000145 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +0000146 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +0000147 return importlib.import_module(name)
Brett Cannon260fbe82013-07-04 18:16:15 -0400148 except ImportError as msg:
Brett Cannond1877262012-11-17 20:46:26 -0500149 if sys.platform.startswith(tuple(required_on)):
150 raise
R. David Murraya21e4ca2009-03-31 23:16:50 +0000151 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +0000152
153
Nick Coghlan47384702009-04-22 16:13:36 +0000154def _save_and_remove_module(name, orig_modules):
155 """Helper function to save and remove a module from sys.modules
156
Eli Benderskyba5517d2013-08-11 15:38:08 -0700157 Raise ImportError if the module can't be imported.
158 """
Ezio Melottifec3ad12011-05-14 06:02:25 +0300159 # try to import the module and raise an error if it can't be imported
160 if name not in sys.modules:
Ezio Melotti199e0852011-05-09 06:41:55 +0300161 __import__(name)
Nick Coghlan47384702009-04-22 16:13:36 +0000162 del sys.modules[name]
Ezio Melottifec3ad12011-05-14 06:02:25 +0300163 for modname in list(sys.modules):
164 if modname == name or modname.startswith(name + '.'):
165 orig_modules[modname] = sys.modules[modname]
166 del sys.modules[modname]
Nick Coghlan47384702009-04-22 16:13:36 +0000167
168def _save_and_block_module(name, orig_modules):
169 """Helper function to save and block a module in sys.modules
170
Eli Benderskyba5517d2013-08-11 15:38:08 -0700171 Return True if the module was in sys.modules, False otherwise.
172 """
Nick Coghlan47384702009-04-22 16:13:36 +0000173 saved = True
174 try:
175 orig_modules[name] = sys.modules[name]
176 except KeyError:
177 saved = False
Alexander Belopolsky903396e2010-07-13 14:50:16 +0000178 sys.modules[name] = None
Nick Coghlan47384702009-04-22 16:13:36 +0000179 return saved
180
181
Nick Coghlan2496f332011-09-19 20:26:31 +1000182def anticipate_failure(condition):
183 """Decorator to mark a test that is known to be broken in some cases
184
185 Any use of this decorator should have a comment identifying the
186 associated tracker issue.
187 """
188 if condition:
189 return unittest.expectedFailure
190 return lambda f: f
191
Zachary Waref012ba42014-07-23 12:00:29 -0500192def load_package_tests(pkg_dir, loader, standard_tests, pattern):
193 """Generic load_tests implementation for simple test packages.
194
195 Most packages can implement load_tests using this function as follows:
196
197 def load_tests(*args):
198 return load_package_tests(os.path.dirname(__file__), *args)
199 """
200 if pattern is None:
201 pattern = "test*"
202 top_dir = os.path.dirname( # Lib
203 os.path.dirname( # test
204 os.path.dirname(__file__))) # support
205 package_tests = loader.discover(start_dir=pkg_dir,
206 top_level_dir=top_dir,
207 pattern=pattern)
208 standard_tests.addTests(package_tests)
209 return standard_tests
210
Nick Coghlan2496f332011-09-19 20:26:31 +1000211
Nick Coghlan47384702009-04-22 16:13:36 +0000212def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Eli Benderskyba5517d2013-08-11 15:38:08 -0700213 """Import and return a module, deliberately bypassing sys.modules.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000214
Eli Benderskyba5517d2013-08-11 15:38:08 -0700215 This function imports and returns a fresh copy of the named Python module
216 by removing the named module from sys.modules before doing the import.
217 Note that unlike reload, the original module is not affected by
218 this operation.
Nick Coghlan47384702009-04-22 16:13:36 +0000219
Eli Benderskyba5517d2013-08-11 15:38:08 -0700220 *fresh* is an iterable of additional module names that are also removed
221 from the sys.modules cache before doing the import.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000222
Eli Benderskyba5517d2013-08-11 15:38:08 -0700223 *blocked* is an iterable of module names that are replaced with None
224 in the module cache during the import to ensure that attempts to import
225 them raise ImportError.
226
227 The named module and any modules named in the *fresh* and *blocked*
228 parameters are saved before starting the import and then reinserted into
229 sys.modules when the fresh import is complete.
230
231 Module and package deprecation messages are suppressed during this import
232 if *deprecated* is True.
233
234 This function will raise ImportError if the named module cannot be
235 imported.
236 """
Ezio Melotti6b60fb92011-05-14 06:47:51 +0300237 # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
238 # to make sure that this utility function is working as expected
Nick Coghlanfce769e2009-04-11 14:30:59 +0000239 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000240 # Keep track of modules saved for later restoration as well
241 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000242 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000243 names_to_remove = []
244 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000245 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000246 for fresh_name in fresh:
247 _save_and_remove_module(fresh_name, orig_modules)
248 for blocked_name in blocked:
249 if not _save_and_block_module(blocked_name, orig_modules):
250 names_to_remove.append(blocked_name)
251 fresh_module = importlib.import_module(name)
Brett Cannon260fbe82013-07-04 18:16:15 -0400252 except ImportError:
Ezio Melotti199e0852011-05-09 06:41:55 +0300253 fresh_module = None
Nick Coghlanfce769e2009-04-11 14:30:59 +0000254 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000255 for orig_name, module in orig_modules.items():
256 sys.modules[orig_name] = module
257 for name_to_remove in names_to_remove:
258 del sys.modules[name_to_remove]
259 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000260
Benjamin Peterson699adb92008-05-08 22:27:58 +0000261
R. David Murraya21e4ca2009-03-31 23:16:50 +0000262def get_attribute(obj, name):
263 """Get an attribute, raising SkipTest if AttributeError is raised."""
264 try:
265 attribute = getattr(obj, name)
266 except AttributeError:
Éric Araujo4300f692011-10-05 01:50:22 +0200267 raise unittest.SkipTest("object %r has no attribute %r" % (obj, name))
R. David Murraya21e4ca2009-03-31 23:16:50 +0000268 else:
269 return attribute
270
Barry Warsawc0fb6052001-08-20 22:29:23 +0000271verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000272use_resources = None # Flag set to [] by regrtest.py
273max_memuse = 0 # Disable bigmem tests (they will still be run with
274 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000275real_max_memuse = 0
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200276failfast = False
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200277match_tests = None
Guido van Rossum531661c1996-12-20 02:58:22 +0000278
Tim Peters8dee8092001-09-25 20:05:11 +0000279# _original_stdout is meant to hold stdout at the time regrtest began.
280# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
281# The point is to have some flavor of stdout the user can actually see.
282_original_stdout = None
283def record_original_stdout(stdout):
284 global _original_stdout
285 _original_stdout = stdout
286
287def get_original_stdout():
288 return _original_stdout or sys.stdout
289
Guido van Rossum3bead091992-01-27 17:00:37 +0000290def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000291 try:
292 del sys.modules[name]
293 except KeyError:
294 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000295
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500296if sys.platform.startswith("win"):
297 def _waitfor(func, pathname, waitall=False):
Ezio Melottib5bc3532013-08-17 16:11:40 +0300298 # Perform the operation
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500299 func(pathname)
300 # Now setup the wait loop
301 if waitall:
302 dirname = pathname
303 else:
304 dirname, name = os.path.split(pathname)
305 dirname = dirname or '.'
306 # Check for `pathname` to be removed from the filesystem.
307 # The exponential backoff of the timeout amounts to a total
308 # of ~1 second after which the deletion is probably an error
309 # anyway.
310 # Testing on a i7@4.3GHz shows that usually only 1 iteration is
311 # required when contention occurs.
312 timeout = 0.001
313 while timeout < 1.0:
Ezio Melottib5bc3532013-08-17 16:11:40 +0300314 # Note we are only testing for the existence of the file(s) in
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500315 # the contents of the directory regardless of any security or
316 # access rights. If we have made it this far, we have sufficient
317 # permissions to do that much using Python's equivalent of the
318 # Windows API FindFirstFile.
319 # Other Windows APIs can fail or give incorrect results when
320 # dealing with files that are pending deletion.
321 L = os.listdir(dirname)
322 if not (L if waitall else name in L):
323 return
324 # Increase the timeout and try again
325 time.sleep(timeout)
326 timeout *= 2
327 warnings.warn('tests may fail, delete still pending for ' + pathname,
328 RuntimeWarning, stacklevel=4)
329
330 def _unlink(filename):
331 _waitfor(os.unlink, filename)
332
333 def _rmdir(dirname):
334 _waitfor(os.rmdir, dirname)
335
336 def _rmtree(path):
337 def _rmtree_inner(path):
338 for name in os.listdir(path):
339 fullname = os.path.join(path, name)
Victor Stinner67f87062014-07-21 19:18:12 +0200340 try:
341 mode = os.lstat(fullname).st_mode
342 except OSError as exc:
343 print("support.rmtree(): os.lstat(%r) failed with %s" % (fullname, exc),
344 file=sys.__stderr__)
345 mode = 0
346 if stat.S_ISDIR(mode):
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500347 _waitfor(_rmtree_inner, fullname, waitall=True)
348 os.rmdir(fullname)
349 else:
350 os.unlink(fullname)
351 _waitfor(_rmtree_inner, path, waitall=True)
352 _waitfor(os.rmdir, path)
353else:
354 _unlink = os.unlink
355 _rmdir = os.rmdir
356 _rmtree = shutil.rmtree
357
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000358def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000359 try:
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500360 _unlink(filename)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100361 except (FileNotFoundError, NotADirectoryError):
362 pass
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000363
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500364def rmdir(dirname):
365 try:
366 _rmdir(dirname)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100367 except FileNotFoundError:
368 pass
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500369
Christian Heimes23daade02008-02-25 12:39:23 +0000370def rmtree(path):
371 try:
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500372 _rmtree(path)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100373 except FileNotFoundError:
374 pass
Christian Heimes23daade02008-02-25 12:39:23 +0000375
Barry Warsaw28a691b2010-04-17 00:19:56 +0000376def make_legacy_pyc(source):
377 """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
378
379 The choice of .pyc or .pyo extension is done based on the __debug__ flag
380 value.
381
382 :param source: The file system path to the source file. The source file
383 does not need to exist, however the PEP 3147 pyc file must exist.
384 :return: The file system path to the legacy pyc file.
385 """
Brett Cannon9529fbf2013-06-15 17:11:25 -0400386 pyc_file = importlib.util.cache_from_source(source)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000387 up_one = os.path.dirname(os.path.abspath(source))
388 legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
389 os.rename(pyc_file, legacy_pyc)
390 return legacy_pyc
391
Guido van Rossum3bead091992-01-27 17:00:37 +0000392def forget(modname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000393 """'Forget' a module was ever imported.
394
395 This removes the module from sys.modules and deletes any PEP 3147 or
396 legacy .pyc and .pyo files.
397 """
Fred Drake004d5e62000-10-23 17:22:08 +0000398 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000399 for dirname in sys.path:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000400 source = os.path.join(dirname, modname + '.py')
401 # It doesn't matter if they exist or not, unlink all possible
402 # combinations of PEP 3147 and legacy pyc and pyo files.
403 unlink(source + 'c')
404 unlink(source + 'o')
Brett Cannon9529fbf2013-06-15 17:11:25 -0400405 unlink(importlib.util.cache_from_source(source, debug_override=True))
406 unlink(importlib.util.cache_from_source(source, debug_override=False))
Guido van Rossum3bead091992-01-27 17:00:37 +0000407
Zachary Warececed6b2014-05-02 10:51:07 -0500408# Check whether a gui is actually available
409def _is_gui_available():
410 if hasattr(_is_gui_available, 'result'):
411 return _is_gui_available.result
412 reason = None
413 if sys.platform.startswith('win'):
414 # if Python is running as a service (such as the buildbot service),
415 # gui interaction may be disallowed
416 import ctypes
417 import ctypes.wintypes
Antoine Pitroud20a5f62011-02-26 15:58:05 +0000418 UOI_FLAGS = 1
419 WSF_VISIBLE = 0x0001
420 class USEROBJECTFLAGS(ctypes.Structure):
421 _fields_ = [("fInherit", ctypes.wintypes.BOOL),
422 ("fReserved", ctypes.wintypes.BOOL),
423 ("dwFlags", ctypes.wintypes.DWORD)]
424 dll = ctypes.windll.user32
425 h = dll.GetProcessWindowStation()
426 if not h:
427 raise ctypes.WinError()
428 uof = USEROBJECTFLAGS()
429 needed = ctypes.wintypes.DWORD()
430 res = dll.GetUserObjectInformationW(h,
431 UOI_FLAGS,
432 ctypes.byref(uof),
433 ctypes.sizeof(uof),
434 ctypes.byref(needed))
435 if not res:
436 raise ctypes.WinError()
Zachary Warececed6b2014-05-02 10:51:07 -0500437 if not bool(uof.dwFlags & WSF_VISIBLE):
438 reason = "gui not available (WSF_VISIBLE flag not set)"
439 elif sys.platform == 'darwin':
440 # The Aqua Tk implementations on OS X can abort the process if
441 # being called in an environment where a window server connection
442 # cannot be made, for instance when invoked by a buildbot or ssh
443 # process not running under the same user id as the current console
444 # user. To avoid that, raise an exception if the window manager
445 # connection is not available.
446 from ctypes import cdll, c_int, pointer, Structure
447 from ctypes.util import find_library
448
449 app_services = cdll.LoadLibrary(find_library("ApplicationServices"))
450
451 if app_services.CGMainDisplayID() == 0:
452 reason = "gui tests cannot run without OS X window manager"
453 else:
454 class ProcessSerialNumber(Structure):
455 _fields_ = [("highLongOfPSN", c_int),
456 ("lowLongOfPSN", c_int)]
457 psn = ProcessSerialNumber()
458 psn_p = pointer(psn)
459 if ( (app_services.GetCurrentProcess(psn_p) < 0) or
460 (app_services.SetFrontProcess(psn_p) < 0) ):
461 reason = "cannot run without OS X gui process"
462
463 # check on every platform whether tkinter can actually do anything
Ned Deily91f01e12014-11-01 19:29:22 -0700464 if not reason:
Zachary Warececed6b2014-05-02 10:51:07 -0500465 try:
466 from tkinter import Tk
467 root = Tk()
Ned Deily91f01e12014-11-01 19:29:22 -0700468 root.update()
Zachary Warececed6b2014-05-02 10:51:07 -0500469 root.destroy()
470 except Exception as e:
471 err_string = str(e)
472 if len(err_string) > 50:
473 err_string = err_string[:50] + ' [...]'
474 reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__,
475 err_string)
476
477 _is_gui_available.reason = reason
478 _is_gui_available.result = not reason
479
480 return _is_gui_available.result
Antoine Pitroud20a5f62011-02-26 15:58:05 +0000481
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000482def is_resource_enabled(resource):
Zachary Ware66f29282014-06-02 16:01:29 -0500483 """Test whether a resource is enabled.
484
485 Known resources are set by regrtest.py. If not running under regrtest.py,
486 all resources are assumed enabled unless use_resources has been set.
487 """
488 return use_resources is None or resource in use_resources
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000489
Barry Warsawc0fb6052001-08-20 22:29:23 +0000490def requires(resource, msg=None):
Zachary Ware66f29282014-06-02 16:01:29 -0500491 """Raise ResourceDenied if the specified resource is not available."""
Antoine Pitroud20a5f62011-02-26 15:58:05 +0000492 if resource == 'gui' and not _is_gui_available():
Zachary Warececed6b2014-05-02 10:51:07 -0500493 raise ResourceDenied(_is_gui_available.reason)
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000494 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000495 if msg is None:
Éric Araujoaf5bacf2011-07-15 17:50:15 +0200496 msg = "Use of the %r resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000497 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000498
Charles-François Natali87b3c922011-10-03 19:40:37 +0200499def _requires_unix_version(sysname, min_version):
500 """Decorator raising SkipTest if the OS is `sysname` and the version is less
501 than `min_version`.
Charles-François Natali239bb962011-06-03 12:55:15 +0200502
Charles-François Natali87b3c922011-10-03 19:40:37 +0200503 For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
504 the FreeBSD version is less than 7.2.
Charles-François Natali239bb962011-06-03 12:55:15 +0200505 """
506 def decorator(func):
507 @functools.wraps(func)
508 def wrapper(*args, **kw):
Charles-François Natali87b3c922011-10-03 19:40:37 +0200509 if platform.system() == sysname:
Charles-François Natali239bb962011-06-03 12:55:15 +0200510 version_txt = platform.release().split('-', 1)[0]
511 try:
512 version = tuple(map(int, version_txt.split('.')))
513 except ValueError:
514 pass
515 else:
516 if version < min_version:
517 min_version_txt = '.'.join(map(str, min_version))
518 raise unittest.SkipTest(
Charles-François Natali87b3c922011-10-03 19:40:37 +0200519 "%s version %s or higher required, not %s"
520 % (sysname, min_version_txt, version_txt))
Victor Stinner3b44a402013-08-28 12:26:28 +0200521 return func(*args, **kw)
522 wrapper.min_version = min_version
Charles-François Natali239bb962011-06-03 12:55:15 +0200523 return wrapper
524 return decorator
Victor Stinnerfea0f4d2011-05-24 00:24:19 +0200525
Charles-François Natali87b3c922011-10-03 19:40:37 +0200526def requires_freebsd_version(*min_version):
527 """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
528 less than `min_version`.
529
530 For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
531 version is less than 7.2.
532 """
533 return _requires_unix_version('FreeBSD', min_version)
534
535def requires_linux_version(*min_version):
536 """Decorator raising SkipTest if the OS is Linux and the Linux version is
537 less than `min_version`.
538
539 For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
540 version is less than 2.6.32.
541 """
542 return _requires_unix_version('Linux', min_version)
543
Victor Stinnerfce92332011-06-01 12:28:04 +0200544def requires_mac_ver(*min_version):
Victor Stinner88701e22011-06-01 13:13:04 +0200545 """Decorator raising SkipTest if the OS is Mac OS X and the OS X
546 version if less than min_version.
Victor Stinnerfce92332011-06-01 12:28:04 +0200547
Victor Stinner88701e22011-06-01 13:13:04 +0200548 For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
549 is lesser than 10.5.
Victor Stinnerfce92332011-06-01 12:28:04 +0200550 """
Victor Stinner88701e22011-06-01 13:13:04 +0200551 def decorator(func):
552 @functools.wraps(func)
553 def wrapper(*args, **kw):
554 if sys.platform == 'darwin':
555 version_txt = platform.mac_ver()[0]
556 try:
557 version = tuple(map(int, version_txt.split('.')))
558 except ValueError:
559 pass
560 else:
561 if version < min_version:
562 min_version_txt = '.'.join(map(str, min_version))
563 raise unittest.SkipTest(
564 "Mac OS X %s or higher required, not %s"
565 % (min_version_txt, version_txt))
566 return func(*args, **kw)
567 wrapper.min_version = min_version
568 return wrapper
569 return decorator
570
Victor Stinnerfce92332011-06-01 12:28:04 +0200571
Antoine Pitrouf6fbf562013-08-22 00:39:46 +0200572# Don't use "localhost", since resolving it uses the DNS under recent
573# Windows versions (see issue #18792).
574HOST = "127.0.0.1"
575HOSTv6 = "::1"
576
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000577
Christian Heimes5e696852008-04-09 08:37:03 +0000578def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
579 """Returns an unused port that should be suitable for binding. This is
580 achieved by creating a temporary socket with the same family and type as
581 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
582 the specified host address (defaults to 0.0.0.0) with the port set to 0,
583 eliciting an unused ephemeral port from the OS. The temporary socket is
584 then closed and deleted, and the ephemeral port is returned.
585
586 Either this method or bind_port() should be used for any tests where a
587 server socket needs to be bound to a particular port for the duration of
588 the test. Which one to use depends on whether the calling code is creating
589 a python socket, or if an unused port needs to be provided in a constructor
590 or passed to an external program (i.e. the -accept argument to openssl's
591 s_server mode). Always prefer bind_port() over find_unused_port() where
592 possible. Hard coded ports should *NEVER* be used. As soon as a server
593 socket is bound to a hard coded port, the ability to run multiple instances
594 of the test simultaneously on the same host is compromised, which makes the
595 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
596 may simply manifest as a failed test, which can be recovered from without
597 intervention in most cases, but on Windows, the entire python process can
598 completely and utterly wedge, requiring someone to log in to the buildbot
599 and manually kill the affected process.
600
601 (This is easy to reproduce on Windows, unfortunately, and can be traced to
602 the SO_REUSEADDR socket option having different semantics on Windows versus
603 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
604 listen and then accept connections on identical host/ports. An EADDRINUSE
Andrew Svetlov0832af62012-12-18 23:10:48 +0200605 OSError will be raised at some point (depending on the platform and
Christian Heimes5e696852008-04-09 08:37:03 +0000606 the order bind and listen were called on each socket).
607
608 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
609 will ever be raised when attempting to bind two identical host/ports. When
610 accept() is called on each socket, the second caller's process will steal
611 the port from the first caller, leaving them both in an awkwardly wedged
612 state where they'll no longer respond to any signals or graceful kills, and
613 must be forcibly killed via OpenProcess()/TerminateProcess().
614
615 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
616 instead of SO_REUSEADDR, which effectively affords the same semantics as
617 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
618 Source world compared to Windows ones, this is a common mistake. A quick
619 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
620 openssl.exe is called with the 's_server' option, for example. See
621 http://bugs.python.org/issue2550 for more info. The following site also
622 has a very thorough description about the implications of both REUSEADDR
623 and EXCLUSIVEADDRUSE on Windows:
624 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
625
626 XXX: although this approach is a vast improvement on previous attempts to
627 elicit unused ports, it rests heavily on the assumption that the ephemeral
628 port returned to us by the OS won't immediately be dished back out to some
629 other process when we close and delete our temporary socket but before our
630 calling code has a chance to bind the returned port. We can deal with this
631 issue if/when we come across it.
632 """
633
634 tempsock = socket.socket(family, socktype)
635 port = bind_port(tempsock)
636 tempsock.close()
637 del tempsock
638 return port
639
640def bind_port(sock, host=HOST):
641 """Bind the socket to a free port and return the port number. Relies on
642 ephemeral ports in order to ensure we are using an unbound port. This is
643 important as many tests may be running simultaneously, especially in a
644 buildbot environment. This method raises an exception if the sock.family
645 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
646 or SO_REUSEPORT set on it. Tests should *never* set these socket options
647 for TCP/IP sockets. The only case for setting these options is testing
648 multicasting via multiple UDP sockets.
649
650 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
651 on Windows), it will be set on the socket. This will prevent anyone else
652 from bind()'ing to our host/port for the duration of the test.
653 """
654
655 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
656 if hasattr(socket, 'SO_REUSEADDR'):
657 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
658 raise TestFailed("tests should never set the SO_REUSEADDR " \
659 "socket option on TCP/IP sockets!")
660 if hasattr(socket, 'SO_REUSEPORT'):
Gregory P. Smith162307f2013-11-17 22:19:32 +0000661 try:
662 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
663 raise TestFailed("tests should never set the SO_REUSEPORT " \
664 "socket option on TCP/IP sockets!")
665 except OSError:
666 # Python's socket module was compiled using modern headers
667 # thus defining SO_REUSEPORT but this process is running
668 # under an older kernel that does not support SO_REUSEPORT.
669 pass
Christian Heimes5e696852008-04-09 08:37:03 +0000670 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
671 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
672
673 sock.bind((host, 0))
674 port = sock.getsockname()[1]
675 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200677def _is_ipv6_enabled():
678 """Check whether IPv6 is enabled on this host."""
679 if socket.has_ipv6:
Ross Lagerwall121d59f2012-07-07 18:40:32 +0200680 sock = None
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200681 try:
682 sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
Charles-François Natalifcfb3242013-08-31 14:40:49 +0200683 sock.bind((HOSTv6, 0))
Ross Lagerwall121d59f2012-07-07 18:40:32 +0200684 return True
Andrew Svetlov0832af62012-12-18 23:10:48 +0200685 except OSError:
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200686 pass
Ross Lagerwall121d59f2012-07-07 18:40:32 +0200687 finally:
688 if sock:
689 sock.close()
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +0200690 return False
691
692IPV6_ENABLED = _is_ipv6_enabled()
693
Benjamin Peterson2615e9e2014-11-25 15:16:55 -0600694def system_must_validate_cert(f):
695 """Skip the test on TLS certificate validation failures."""
696 @functools.wraps(f)
697 def dec(*args, **kwargs):
698 try:
699 f(*args, **kwargs)
700 except IOError as e:
701 if e.reason == "CERTIFICATE_VERIFY_FAILED":
702 raise unittest.SkipTest("system does not contain "
703 "necessary certificates")
704 raise
705 return dec
Charles-François Natali2d517212011-05-29 16:36:44 +0200706
Antoine Pitroue1a16742013-04-24 23:31:38 +0200707# A constant likely larger than the underlying OS pipe buffer size, to
708# make writes blocking.
709# Windows limit seems to be around 512 B, and many Unix kernels have a
710# 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
711# (see issue #17835 for a discussion of this number).
Charles-François Natali5fd26422013-08-29 19:01:40 +0200712PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
Charles-François Natali2d517212011-05-29 16:36:44 +0200713
Charles-François Natali5fd26422013-08-29 19:01:40 +0200714# A constant likely larger than the underlying OS socket buffer size, to make
715# writes blocking.
716# The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
717# on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
718# for a discussion of this number).
719SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1
Charles-François Natali2d517212011-05-29 16:36:44 +0200720
Eric Smithf24a0d92010-12-04 13:32:18 +0000721# decorator for skipping tests on non-IEEE 754 platforms
722requires_IEEE_754 = unittest.skipUnless(
723 float.__getformat__("double").startswith("IEEE"),
724 "test requires IEEE 754 doubles")
725
Ezio Melotticad648c2011-05-19 21:25:10 +0300726requires_zlib = unittest.skipUnless(zlib, 'requires zlib')
727
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300728requires_gzip = unittest.skipUnless(gzip, 'requires gzip')
729
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200730requires_bz2 = unittest.skipUnless(bz2, 'requires bz2')
731
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200732requires_lzma = unittest.skipUnless(lzma, 'requires lzma')
733
Finn Bock57bc5fa2002-11-01 18:02:03 +0000734is_jython = sys.platform.startswith('java')
735
Barry Warsaw559f6682001-03-23 18:04:02 +0000736# Filename used for testing
737if os.name == 'java':
738 # Jython disallows @ in module names
739 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000740else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000741 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000742
Antoine Pitrou88909542009-06-29 13:54:42 +0000743# Disambiguate TESTFN for parallel testing, while letting it remain a valid
744# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000745TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000746
Victor Stinner8b219b22012-11-06 23:23:43 +0100747# FS_NONASCII: non-ASCII character encodable by os.fsencode(),
748# or None if there is no such character.
749FS_NONASCII = None
750for character in (
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100751 # First try printable and common characters to have a readable filename.
752 # For each character, the encoding list are just example of encodings able
753 # to encode the character (the list is not exhaustive).
754
755 # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
Victor Stinner8b219b22012-11-06 23:23:43 +0100756 '\u00E6',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100757 # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
758 '\u0130',
759 # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
Victor Stinner8b219b22012-11-06 23:23:43 +0100760 '\u0141',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100761 # U+03C6 (Greek Small Letter Phi): cp1253
762 '\u03C6',
763 # U+041A (Cyrillic Capital Letter Ka): cp1251
Victor Stinner8b219b22012-11-06 23:23:43 +0100764 '\u041A',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100765 # U+05D0 (Hebrew Letter Alef): Encodable to cp424
Victor Stinner8b219b22012-11-06 23:23:43 +0100766 '\u05D0',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100767 # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
768 '\u060C',
769 # U+062A (Arabic Letter Teh): cp720
770 '\u062A',
771 # U+0E01 (Thai Character Ko Kai): cp874
Victor Stinner8b219b22012-11-06 23:23:43 +0100772 '\u0E01',
Victor Stinnerab8b6bd2012-11-06 23:43:21 +0100773
774 # Then try more "special" characters. "special" because they may be
775 # interpreted or displayed differently depending on the exact locale
776 # encoding and the font.
777
778 # U+00A0 (No-Break Space)
779 '\u00A0',
780 # U+20AC (Euro Sign)
781 '\u20AC',
Victor Stinner8b219b22012-11-06 23:23:43 +0100782):
783 try:
784 os.fsdecode(os.fsencode(character))
785 except UnicodeError:
786 pass
787 else:
788 FS_NONASCII = character
789 break
Michael Foord2d9c2d52010-05-04 22:29:10 +0000790
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000791# TESTFN_UNICODE is a non-ascii filename
792TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
Victor Stinner74a833f2010-08-18 21:06:23 +0000793if sys.platform == 'darwin':
794 # In Mac OS X's VFS API file names are, by definition, canonically
795 # decomposed Unicode, encoded using UTF-8. See QA1173:
796 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
797 import unicodedata
798 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
Antoine Pitrou88909542009-06-29 13:54:42 +0000799TESTFN_ENCODING = sys.getfilesystemencoding()
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000800
Victor Stinner09c449c2010-08-13 22:23:24 +0000801# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000802# encoded by the filesystem encoding (in strict mode). It can be None if we
803# cannot generate such filename.
Victor Stinnera0241c82010-08-15 19:28:21 +0000804TESTFN_UNENCODABLE = None
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000805if os.name in ('nt', 'ce'):
Victor Stinnera0241c82010-08-15 19:28:21 +0000806 # skip win32s (0) or Windows 9x/ME (1)
807 if sys.getwindowsversion().platform >= 2:
Victor Stinner8ce7df62010-09-10 11:19:59 +0000808 # Different kinds of characters from various languages to minimize the
809 # probability that the whole name is encodable to MBCS (issue #9819)
810 TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000811 try:
Victor Stinner09c449c2010-08-13 22:23:24 +0000812 TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000813 except UnicodeEncodeError:
814 pass
815 else:
816 print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
817 'Unicode filename tests may not be effective'
Victor Stinner09c449c2010-08-13 22:23:24 +0000818 % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
819 TESTFN_UNENCODABLE = None
Victor Stinnera0241c82010-08-15 19:28:21 +0000820# Mac OS X denies unencodable filenames (invalid utf-8)
Victor Stinner03c9e1d2010-08-14 17:35:20 +0000821elif sys.platform != 'darwin':
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000822 try:
823 # ascii and utf-8 cannot encode the byte 0xff
824 b'\xff'.decode(TESTFN_ENCODING)
825 except UnicodeDecodeError:
826 # 0xff will be encoded using the surrogate character u+DCFF
Victor Stinner09c449c2010-08-13 22:23:24 +0000827 TESTFN_UNENCODABLE = TESTFN \
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000828 + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
829 else:
830 # File system encoding (eg. ISO-8859-* encodings) can encode
831 # the byte 0xff. Skip some unicode filename tests.
Victor Stinnera0241c82010-08-15 19:28:21 +0000832 pass
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000833
Victor Stinner292c8352012-10-30 02:17:38 +0100834# TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be
835# decoded from the filesystem encoding (in strict mode). It can be None if we
Victor Stinnerff3d5152012-11-10 12:07:39 +0100836# cannot generate such filename (ex: the latin1 encoding can decode any byte
837# sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks
838# to the surrogateescape error handler (PEP 383), but not from the filesystem
839# encoding in strict mode.
Victor Stinner292c8352012-10-30 02:17:38 +0100840TESTFN_UNDECODABLE = None
Victor Stinnerff3d5152012-11-10 12:07:39 +0100841for name in (
842 # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows
843 # accepts it to create a file or a directory, or don't accept to enter to
844 # such directory (when the bytes name is used). So test b'\xe7' first: it is
845 # not decodable from cp932.
846 b'\xe7w\xf0',
847 # undecodable from ASCII, UTF-8
848 b'\xff',
849 # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856
850 # and cp857
851 b'\xae\xd5'
852 # undecodable from UTF-8 (UNIX and Mac OS X)
853 b'\xed\xb2\x80', b'\xed\xb4\x80',
Victor Stinnerfe907e12012-12-04 11:55:04 +0100854 # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252,
855 # cp1253, cp1254, cp1255, cp1257, cp1258
856 b'\x81\x98',
Victor Stinnerff3d5152012-11-10 12:07:39 +0100857):
Victor Stinner292c8352012-10-30 02:17:38 +0100858 try:
Victor Stinnerff3d5152012-11-10 12:07:39 +0100859 name.decode(TESTFN_ENCODING)
Victor Stinnera0c811e2012-10-31 22:16:38 +0100860 except UnicodeDecodeError:
Victor Stinnerff3d5152012-11-10 12:07:39 +0100861 TESTFN_UNDECODABLE = os.fsencode(TESTFN) + name
Victor Stinner292c8352012-10-30 02:17:38 +0100862 break
863
Victor Stinner8b219b22012-11-06 23:23:43 +0100864if FS_NONASCII:
Victor Stinner90a9d512012-11-06 23:40:22 +0100865 TESTFN_NONASCII = TESTFN + '-' + FS_NONASCII
Victor Stinner8b219b22012-11-06 23:23:43 +0100866else:
867 TESTFN_NONASCII = None
868
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000869# Save the initial cwd
870SAVEDCWD = os.getcwd()
871
872@contextlib.contextmanager
Nick Coghlan55175962013-07-28 22:11:50 +1000873def temp_dir(path=None, quiet=False):
874 """Return a context manager that creates a temporary directory.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000875
Nick Coghlan55175962013-07-28 22:11:50 +1000876 Arguments:
Nick Coghland26c18a2010-08-17 13:06:11 +0000877
Nick Coghlan55175962013-07-28 22:11:50 +1000878 path: the directory to create temporarily. If omitted or None,
879 defaults to creating a temporary directory using tempfile.mkdtemp.
880
881 quiet: if False (the default), the context manager raises an exception
882 on error. Otherwise, if the path is specified and cannot be
883 created, only a warning is issued.
884
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000885 """
Nick Coghlan55175962013-07-28 22:11:50 +1000886 dir_created = False
Nick Coghland26c18a2010-08-17 13:06:11 +0000887 if path is None:
Nick Coghlan55175962013-07-28 22:11:50 +1000888 path = tempfile.mkdtemp()
889 dir_created = True
890 path = os.path.realpath(path)
891 else:
Nick Coghland26c18a2010-08-17 13:06:11 +0000892 try:
Nick Coghlan55175962013-07-28 22:11:50 +1000893 os.mkdir(path)
894 dir_created = True
Nick Coghland26c18a2010-08-17 13:06:11 +0000895 except OSError:
896 if not quiet:
897 raise
Nick Coghlan55175962013-07-28 22:11:50 +1000898 warnings.warn('tests may fail, unable to create temp dir: ' + path,
Nick Coghland26c18a2010-08-17 13:06:11 +0000899 RuntimeWarning, stacklevel=3)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000900 try:
Nick Coghlan55175962013-07-28 22:11:50 +1000901 yield path
902 finally:
903 if dir_created:
904 shutil.rmtree(path)
905
906@contextlib.contextmanager
907def change_cwd(path, quiet=False):
908 """Return a context manager that changes the current working directory.
909
910 Arguments:
911
912 path: the directory to use as the temporary current working directory.
913
914 quiet: if False (the default), the context manager raises an exception
915 on error. Otherwise, it issues only a warning and keeps the current
916 working directory the same.
917
918 """
919 saved_dir = os.getcwd()
920 try:
Nick Coghland26c18a2010-08-17 13:06:11 +0000921 os.chdir(path)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000922 except OSError:
923 if not quiet:
924 raise
Nick Coghlan55175962013-07-28 22:11:50 +1000925 warnings.warn('tests may fail, unable to change CWD to: ' + path,
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000926 RuntimeWarning, stacklevel=3)
927 try:
928 yield os.getcwd()
929 finally:
930 os.chdir(saved_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000931
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000932
Nick Coghlan55175962013-07-28 22:11:50 +1000933@contextlib.contextmanager
934def temp_cwd(name='tempcwd', quiet=False):
935 """
936 Context manager that temporarily creates and changes the CWD.
937
938 The function temporarily changes the current working directory
939 after creating a temporary directory in the current directory with
940 name *name*. If *name* is None, the temporary directory is
941 created using tempfile.mkdtemp.
942
943 If *quiet* is False (default) and it is not possible to
944 create or change the CWD, an error is raised. If *quiet* is True,
945 only a warning is raised and the original CWD is used.
946
947 """
948 with temp_dir(path=name, quiet=quiet) as temp_path:
949 with change_cwd(temp_path, quiet=quiet) as cwd_dir:
950 yield cwd_dir
951
Eli Bendersky6c519992011-07-23 08:48:53 +0300952if hasattr(os, "umask"):
953 @contextlib.contextmanager
954 def temp_umask(umask):
955 """Context manager that temporarily sets the process umask."""
956 oldmask = os.umask(umask)
957 try:
958 yield
959 finally:
960 os.umask(oldmask)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000961
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000962# TEST_HOME_DIR refers to the top level directory of the "test" package
Nick Coghlanfb15aa12013-07-28 20:56:19 +1000963# that contains Python's regression test suite
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000964TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__))
965TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000966
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000967# TEST_DATA_DIR is used as a target download location for remote resources
968TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data")
969
970def findfile(filename, subdir=None):
Nick Coghlanfb15aa12013-07-28 20:56:19 +1000971 """Try to find a file on sys.path or in the test directory. If it is not
Brett Cannonf1cfb622003-05-04 21:15:27 +0000972 found the argument passed to the function is returned (this does not
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000973 necessarily signal failure; could still be the legitimate path).
974
975 Setting *subdir* indicates a relative path to use to find the file
976 rather than looking directly in the path directories.
977 """
978 if os.path.isabs(filename):
979 return filename
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000980 if subdir is not None:
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000981 filename = os.path.join(subdir, filename)
982 path = [TEST_HOME_DIR] + sys.path
Fred Drake004d5e62000-10-23 17:22:08 +0000983 for dn in path:
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000984 fn = os.path.join(dn, filename)
Fred Drake004d5e62000-10-23 17:22:08 +0000985 if os.path.exists(fn): return fn
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000986 return filename
Marc-André Lemburg36619082001-01-17 19:11:13 +0000987
Victor Stinnerbf816222011-06-30 23:25:47 +0200988def create_empty_file(filename):
989 """Create an empty file. If the file already exists, truncate it."""
990 fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
991 os.close(fd)
992
Tim Peters2f228e72001-05-13 00:19:31 +0000993def sortdict(dict):
994 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000995 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000996 reprpairs = ["%r: %r" % pair for pair in items]
997 withcommas = ", ".join(reprpairs)
998 return "{%s}" % withcommas
999
Benjamin Peterson7522c742009-01-19 21:00:09 +00001000def make_bad_fd():
1001 """
1002 Create an invalid file descriptor by opening and closing a file and return
1003 its fd.
1004 """
1005 file = open(TESTFN, "wb")
1006 try:
1007 return file.fileno()
1008 finally:
1009 file.close()
1010 unlink(TESTFN)
1011
Thomas Wouters89f507f2006-12-13 04:49:30 +00001012def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001013 testcase.assertRaises(SyntaxError, compile, statement,
1014 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001015
Martin v. Löwis234a34a2007-08-30 20:58:02 +00001016def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001017 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001018
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001019 check = kw.pop('check', None)
1020
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001021 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +00001022
Nick Coghlan0494c2a2013-09-08 11:40:34 +10001023 fn = os.path.join(TEST_DATA_DIR, filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001024
1025 def check_valid_file(fn):
1026 f = open(fn, *args, **kw)
1027 if check is None:
1028 return f
1029 elif check(f):
1030 f.seek(0)
1031 return f
1032 f.close()
1033
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001034 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001035 f = check_valid_file(fn)
1036 if f is not None:
1037 return f
1038 unlink(fn)
1039
1040 # Verify the requirement before downloading the file
1041 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +00001042
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001043 print('\tfetching %s ...' % url, file=get_original_stdout())
Georg Brandl72a7f7c2014-11-06 15:33:30 +01001044 opener = urllib.request.build_opener()
1045 if gzip:
1046 opener.addheaders.append(('Accept-Encoding', 'gzip'))
1047 f = opener.open(url, timeout=15)
1048 if gzip and f.headers.get('Content-Encoding') == 'gzip':
1049 f = gzip.GzipFile(fileobj=f)
Antoine Pitroufd0680b2009-11-01 22:13:48 +00001050 try:
1051 with open(fn, "wb") as out:
1052 s = f.read()
1053 while s:
1054 out.write(s)
1055 s = f.read()
1056 finally:
1057 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001058
1059 f = check_valid_file(fn)
1060 if f is not None:
1061 return f
Éric Araujoaf5bacf2011-07-15 17:50:15 +02001062 raise TestFailed('invalid resource %r' % fn)
Florent Xiclunaf089fd62010-03-19 14:25:03 +00001063
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001064
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001065class WarningsRecorder(object):
1066 """Convenience wrapper for the warnings list returned on
1067 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001069 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001070 self._warnings = warnings_list
1071 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001072
1073 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001074 if len(self._warnings) > self._last:
1075 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001076 elif attr in warnings.WarningMessage._WARNING_DETAILS:
1077 return None
1078 raise AttributeError("%r has no attribute %r" % (self, attr))
1079
Florent Xiclunab14930c2010-03-13 15:26:44 +00001080 @property
1081 def warnings(self):
1082 return self._warnings[self._last:]
1083
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001084 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001085 self._last = len(self._warnings)
1086
1087
1088def _filterwarnings(filters, quiet=False):
1089 """Catch the warnings, then check if all the expected
1090 warnings have been raised and re-raise unexpected warnings.
1091 If 'quiet' is True, only re-raise the unexpected warnings.
1092 """
1093 # Clear the warning registry of the calling module
1094 # in order to re-raise the warnings.
1095 frame = sys._getframe(2)
1096 registry = frame.f_globals.get('__warningregistry__')
1097 if registry:
1098 registry.clear()
1099 with warnings.catch_warnings(record=True) as w:
1100 # Set filter "always" to record all warnings. Because
1101 # test_warnings swap the module, we need to look up in
1102 # the sys.modules dictionary.
1103 sys.modules['warnings'].simplefilter("always")
1104 yield WarningsRecorder(w)
1105 # Filter the recorded warnings
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001106 reraise = list(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001107 missing = []
1108 for msg, cat in filters:
1109 seen = False
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001110 for w in reraise[:]:
1111 warning = w.message
Florent Xiclunab14930c2010-03-13 15:26:44 +00001112 # Filter out the matching messages
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001113 if (re.match(msg, str(warning), re.I) and
1114 issubclass(warning.__class__, cat)):
Florent Xiclunab14930c2010-03-13 15:26:44 +00001115 seen = True
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001116 reraise.remove(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001117 if not seen and not quiet:
1118 # This filter caught nothing
1119 missing.append((msg, cat.__name__))
1120 if reraise:
Antoine Pitrou31e08a42010-10-29 11:54:03 +00001121 raise AssertionError("unhandled warning %s" % reraise[0])
Florent Xiclunab14930c2010-03-13 15:26:44 +00001122 if missing:
1123 raise AssertionError("filter (%r, %s) did not catch any warning" %
1124 missing[0])
1125
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001126
1127@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +00001128def check_warnings(*filters, **kwargs):
1129 """Context manager to silence warnings.
1130
1131 Accept 2-tuples as positional arguments:
1132 ("message regexp", WarningCategory)
1133
1134 Optional argument:
1135 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506be2010-03-18 20:00:57 +00001136 (default True without argument,
1137 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001138
1139 Without argument, it defaults to:
Florent Xicluna53b506be2010-03-18 20:00:57 +00001140 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +00001141 """
Florent Xicluna53b506be2010-03-18 20:00:57 +00001142 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +00001143 if not filters:
1144 filters = (("", Warning),)
Florent Xicluna53b506be2010-03-18 20:00:57 +00001145 # Preserve backward compatibility
1146 if quiet is None:
1147 quiet = True
1148 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001150
1151class CleanImport(object):
1152 """Context manager to force import to return a new module reference.
1153
1154 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +00001155 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001156
1157 Use like this:
1158
1159 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +00001160 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001161 """
1162
1163 def __init__(self, *module_names):
1164 self.original_modules = sys.modules.copy()
1165 for module_name in module_names:
1166 if module_name in sys.modules:
1167 module = sys.modules[module_name]
1168 # It is possible that module_name is just an alias for
1169 # another module (e.g. stub for modules renamed in 3.x).
1170 # In that case, we also need delete the real module to clear
1171 # the import cache.
1172 if module.__name__ != module_name:
1173 del sys.modules[module.__name__]
1174 del sys.modules[module_name]
1175
1176 def __enter__(self):
1177 return self
1178
1179 def __exit__(self, *ignore_exc):
1180 sys.modules.update(self.original_modules)
1181
1182
Raymond Hettinger57d1a882011-02-23 00:46:28 +00001183class EnvironmentVarGuard(collections.abc.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001184
1185 """Class to help protect the environment variable properly. Can be used as
1186 a context manager."""
1187
1188 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +00001189 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +00001190 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001191
Walter Dörwald155374d2009-05-01 19:58:58 +00001192 def __getitem__(self, envvar):
1193 return self._environ[envvar]
1194
1195 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +00001196 # Remember the initial value on the first access
1197 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +00001198 self._changed[envvar] = self._environ.get(envvar)
1199 self._environ[envvar] = value
1200
1201 def __delitem__(self, envvar):
1202 # Remember the initial value on the first access
1203 if envvar not in self._changed:
1204 self._changed[envvar] = self._environ.get(envvar)
1205 if envvar in self._environ:
1206 del self._environ[envvar]
1207
1208 def keys(self):
1209 return self._environ.keys()
1210
1211 def __iter__(self):
1212 return iter(self._environ)
1213
1214 def __len__(self):
1215 return len(self._environ)
1216
1217 def set(self, envvar, value):
1218 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001219
1220 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +00001221 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001222
1223 def __enter__(self):
1224 return self
1225
1226 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +00001227 for (k, v) in self._changed.items():
1228 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +00001229 if k in self._environ:
1230 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +00001231 else:
Walter Dörwald155374d2009-05-01 19:58:58 +00001232 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +00001233 os.environ = self._environ
1234
1235
1236class DirsOnSysPath(object):
1237 """Context manager to temporarily add directories to sys.path.
1238
1239 This makes a copy of sys.path, appends any directories given
1240 as positional arguments, then reverts sys.path to the copied
1241 settings when the context ends.
1242
1243 Note that *all* sys.path modifications in the body of the
1244 context manager, including replacement of the object,
1245 will be reverted at the end of the block.
1246 """
1247
1248 def __init__(self, *paths):
1249 self.original_value = sys.path[:]
1250 self.original_object = sys.path
1251 sys.path.extend(paths)
1252
1253 def __enter__(self):
1254 return self
1255
1256 def __exit__(self, *ignore_exc):
1257 sys.path = self.original_object
1258 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +00001259
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001260
Guido van Rossumd8faa362007-04-27 19:54:29 +00001261class TransientResource(object):
1262
1263 """Raise ResourceDenied if an exception is raised while the context manager
1264 is in effect that matches the specified exception and attributes."""
1265
1266 def __init__(self, exc, **kwargs):
1267 self.exc = exc
1268 self.attrs = kwargs
1269
1270 def __enter__(self):
1271 return self
1272
1273 def __exit__(self, type_=None, value=None, traceback=None):
1274 """If type_ is a subclass of self.exc and value has attributes matching
1275 self.attrs, raise ResourceDenied. Otherwise let the exception
1276 propagate (if any)."""
1277 if type_ is not None and issubclass(self.exc, type_):
1278 for attr, attr_value in self.attrs.items():
1279 if not hasattr(value, attr):
1280 break
1281 if getattr(value, attr) != attr_value:
1282 break
1283 else:
1284 raise ResourceDenied("an optional resource is not available")
1285
Raymond Hettinger686057b2009-06-04 00:11:54 +00001286# Context managers that raise ResourceDenied when various issues
1287# with the Internet connection manifest themselves as exceptions.
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001288# XXX deprecate these and use transient_internet() instead
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001289time_out = TransientResource(OSError, errno=errno.ETIMEDOUT)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001290socket_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001291ioerror_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001292
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001293
Thomas Woutersed03b412007-08-28 21:37:11 +00001294@contextlib.contextmanager
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001295def transient_internet(resource_name, *, timeout=30.0, errnos=()):
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001296 """Return a context manager that raises ResourceDenied when various issues
1297 with the Internet connection manifest themselves as exceptions."""
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001298 default_errnos = [
1299 ('ECONNREFUSED', 111),
1300 ('ECONNRESET', 104),
Antoine Pitrou5d938cb2011-01-08 10:28:11 +00001301 ('EHOSTUNREACH', 113),
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001302 ('ENETUNREACH', 101),
1303 ('ETIMEDOUT', 110),
1304 ]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001305 default_gai_errnos = [
Antoine Pitrou4875c462011-07-09 02:31:24 +02001306 ('EAI_AGAIN', -3),
Charles-François Natali13859bf2011-12-10 13:16:44 +01001307 ('EAI_FAIL', -4),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001308 ('EAI_NONAME', -2),
1309 ('EAI_NODATA', -5),
Antoine Pitrou390ea0f2011-04-29 00:44:33 +02001310 # Encountered when trying to resolve IPv6-only hostnames
1311 ('WSANO_DATA', 11004),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001312 ]
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001313
Éric Araujoaf5bacf2011-07-15 17:50:15 +02001314 denied = ResourceDenied("Resource %r is not available" % resource_name)
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001315 captured_errnos = errnos
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001316 gai_errnos = []
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001317 if not captured_errnos:
1318 captured_errnos = [getattr(errno, name, num)
1319 for (name, num) in default_errnos]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001320 gai_errnos = [getattr(socket, name, num)
1321 for (name, num) in default_gai_errnos]
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001322
1323 def filter_error(err):
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001324 n = getattr(err, 'errno', None)
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001325 if (isinstance(err, socket.timeout) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001326 (isinstance(err, socket.gaierror) and n in gai_errnos) or
Berker Peksag8b63d3a2014-10-25 05:42:30 +03001327 (isinstance(err, urllib.error.URLError) and
1328 "ConnectionRefusedError" in err.reason) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001329 n in captured_errnos):
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001330 if not verbose:
1331 sys.stderr.write(denied.args[0] + "\n")
1332 raise denied from err
1333
1334 old_timeout = socket.getdefaulttimeout()
1335 try:
1336 if timeout is not None:
1337 socket.setdefaulttimeout(timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001338 yield
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001339 except OSError as err:
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001340 # urllib can wrap original socket errors multiple times (!), we must
1341 # unwrap to get at the original error.
1342 while True:
1343 a = err.args
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001344 if len(a) >= 1 and isinstance(a[0], OSError):
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001345 err = a[0]
1346 # The error can also be wrapped as args[1]:
1347 # except socket.error as msg:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001348 # raise OSError('socket error', msg).with_traceback(sys.exc_info()[2])
1349 elif len(a) >= 2 and isinstance(a[1], OSError):
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001350 err = a[1]
1351 else:
1352 break
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001353 filter_error(err)
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001354 raise
1355 # XXX should we catch generic exceptions and look for their
1356 # __cause__ or __context__?
1357 finally:
1358 socket.setdefaulttimeout(old_timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001359
1360
1361@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001362def captured_output(stream_name):
Ezio Melotti07352b02011-05-14 14:51:18 +03001363 """Return a context manager used by captured_stdout/stdin/stderr
Ezio Melottifc778fd2011-05-14 08:22:47 +03001364 that temporarily replaces the sys stream *stream_name* with a StringIO."""
Thomas Woutersed03b412007-08-28 21:37:11 +00001365 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001366 orig_stdout = getattr(sys, stream_name)
1367 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001368 try:
1369 yield getattr(sys, stream_name)
1370 finally:
1371 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001372
1373def captured_stdout():
Ezio Melottifc778fd2011-05-14 08:22:47 +03001374 """Capture the output of sys.stdout:
1375
R David Murray5a33f812013-07-11 12:28:40 -04001376 with captured_stdout() as stdout:
Ezio Melottifc778fd2011-05-14 08:22:47 +03001377 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -04001378 self.assertEqual(stdout.getvalue(), "hello\n")
Ezio Melottifc778fd2011-05-14 08:22:47 +03001379 """
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001380 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +00001381
Nick Coghlan6b22f3f2010-12-12 15:24:21 +00001382def captured_stderr():
R David Murray5a33f812013-07-11 12:28:40 -04001383 """Capture the output of sys.stderr:
1384
1385 with captured_stderr() as stderr:
1386 print("hello", file=sys.stderr)
1387 self.assertEqual(stderr.getvalue(), "hello\n")
1388 """
Nick Coghlan6b22f3f2010-12-12 15:24:21 +00001389 return captured_output("stderr")
1390
Nick Coghlan6ead5522009-10-18 13:19:33 +00001391def captured_stdin():
R David Murray5a33f812013-07-11 12:28:40 -04001392 """Capture the input to sys.stdin:
1393
1394 with captured_stdin() as stdin:
1395 stdin.write('hello\n')
1396 stdin.seek(0)
1397 # call test code that consumes from sys.stdin
1398 captured = input()
1399 self.assertEqual(captured, "hello")
1400 """
Nick Coghlan6ead5522009-10-18 13:19:33 +00001401 return captured_output("stdin")
1402
Ezio Melotti07352b02011-05-14 14:51:18 +03001403
Benjamin Petersone549ead2009-03-28 21:42:05 +00001404def gc_collect():
1405 """Force as many objects as possible to be collected.
1406
1407 In non-CPython implementations of Python, this is needed because timely
1408 deallocation is not guaranteed by the garbage collector. (Even in CPython
1409 this can be the case in case of reference cycles.) This means that __del__
1410 methods may be called later than expected and weakrefs may remain alive for
1411 longer than expected. This function tries its best to force all garbage
1412 objects to disappear.
1413 """
Benjamin Petersone549ead2009-03-28 21:42:05 +00001414 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +00001415 if is_jython:
1416 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00001417 gc.collect()
1418 gc.collect()
1419
Benjamin Peterson31f4beb2011-07-14 12:48:01 -05001420@contextlib.contextmanager
1421def disable_gc():
1422 have_gc = gc.isenabled()
1423 gc.disable()
1424 try:
1425 yield
1426 finally:
1427 if have_gc:
1428 gc.enable()
1429
Thomas Woutersed03b412007-08-28 21:37:11 +00001430
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001431def python_is_optimized():
1432 """Find if Python was built with optimizations."""
Antoine Pitrou64474542010-10-31 11:34:47 +00001433 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001434 final_opt = ""
1435 for opt in cflags.split():
1436 if opt.startswith('-O'):
1437 final_opt = opt
Eli Bendersky6c519992011-07-23 08:48:53 +03001438 return final_opt != '' and final_opt != '-O0'
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001439
1440
Martin v. Löwis2b168442012-07-29 16:38:45 +02001441_header = 'nP'
1442_align = '0n'
Martin v. Löwis33f79972012-07-29 16:33:05 +02001443if hasattr(sys, "gettotalrefcount"):
1444 _header = '2P' + _header
Martin v. Löwis2b168442012-07-29 16:38:45 +02001445 _align = '0P'
1446_vheader = _header + 'n'
Martin v. Löwis33f79972012-07-29 16:33:05 +02001447
1448def calcobjsize(fmt):
Martin v. Löwis2b168442012-07-29 16:38:45 +02001449 return struct.calcsize(_header + fmt + _align)
Martin v. Löwis33f79972012-07-29 16:33:05 +02001450
1451def calcvobjsize(fmt):
Martin v. Löwis2b168442012-07-29 16:38:45 +02001452 return struct.calcsize(_vheader + fmt + _align)
Martin v. Löwis33f79972012-07-29 16:33:05 +02001453
1454
1455_TPFLAGS_HAVE_GC = 1<<14
1456_TPFLAGS_HEAPTYPE = 1<<9
1457
1458def check_sizeof(test, o, size):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001459 import _testcapi
Martin v. Löwis33f79972012-07-29 16:33:05 +02001460 result = sys.getsizeof(o)
1461 # add GC header size
1462 if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
1463 ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
1464 size += _testcapi.SIZEOF_PYGC_HEAD
1465 msg = 'wrong size for %s: got %d, expected %d' \
1466 % (type(o), result, size)
1467 test.assertEqual(result, size, msg)
1468
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001469#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001470# Decorator for running a function in a different locale, correctly resetting
1471# it afterwards.
1472
1473def run_with_locale(catstr, *locales):
1474 def decorator(func):
1475 def inner(*args, **kwds):
1476 try:
1477 import locale
1478 category = getattr(locale, catstr)
1479 orig_locale = locale.setlocale(category)
1480 except AttributeError:
1481 # if the test author gives us an invalid category string
1482 raise
1483 except:
1484 # cannot retrieve original locale, so do nothing
1485 locale = orig_locale = None
1486 else:
1487 for loc in locales:
1488 try:
1489 locale.setlocale(category, loc)
1490 break
1491 except:
1492 pass
1493
1494 # now run the function, resetting the locale on exceptions
1495 try:
1496 return func(*args, **kwds)
1497 finally:
1498 if locale and orig_locale:
1499 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +00001500 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +00001501 inner.__doc__ = func.__doc__
1502 return inner
1503 return decorator
1504
1505#=======================================================================
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001506# Decorator for running a function in a specific timezone, correctly
1507# resetting it afterwards.
1508
1509def run_with_tz(tz):
1510 def decorator(func):
1511 def inner(*args, **kwds):
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001512 try:
1513 tzset = time.tzset
1514 except AttributeError:
1515 raise unittest.SkipTest("tzset required")
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001516 if 'TZ' in os.environ:
1517 orig_tz = os.environ['TZ']
1518 else:
1519 orig_tz = None
1520 os.environ['TZ'] = tz
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001521 tzset()
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001522
1523 # now run the function, resetting the tz on exceptions
1524 try:
1525 return func(*args, **kwds)
1526 finally:
Benjamin Petersonb29614e2012-10-09 11:16:03 -04001527 if orig_tz is None:
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001528 del os.environ['TZ']
1529 else:
1530 os.environ['TZ'] = orig_tz
1531 time.tzset()
1532
1533 inner.__name__ = func.__name__
1534 inner.__doc__ = func.__doc__
1535 return inner
1536 return decorator
1537
1538#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +00001539# Big-memory-test support. Separate from 'resources' because memory use
1540# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001541
1542# Some handy shorthands. Note that these are used for byte-limits as well
1543# as size-limits, in the various bigmem tests
1544_1M = 1024*1024
1545_1G = 1024 * _1M
1546_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001547_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +00001548
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001549MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001550
Thomas Wouters477c8d52006-05-27 19:21:47 +00001551def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001552 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001553 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001554 sizes = {
1555 'k': 1024,
1556 'm': _1M,
1557 'g': _1G,
1558 't': 1024*_1G,
1559 }
1560 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
1561 re.IGNORECASE | re.VERBOSE)
1562 if m is None:
1563 raise ValueError('Invalid memory limit %r' % (limit,))
1564 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001565 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001566 if memlimit > MAX_Py_ssize_t:
1567 memlimit = MAX_Py_ssize_t
1568 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001569 raise ValueError('Memory limit %r too low to be useful' % (limit,))
1570 max_memuse = memlimit
1571
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001572class _MemoryWatchdog:
1573 """An object which periodically watches the process' memory consumption
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001574 and prints it out.
1575 """
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001576
1577 def __init__(self):
1578 self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
1579 self.started = False
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001580
1581 def start(self):
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001582 try:
Charles-François Natali55bce632012-03-24 10:06:23 +01001583 f = open(self.procfile, 'r')
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001584 except OSError as e:
1585 warnings.warn('/proc not available for stats: {}'.format(e),
1586 RuntimeWarning)
1587 sys.stderr.flush()
1588 return
Charles-François Natali55bce632012-03-24 10:06:23 +01001589
1590 watchdog_script = findfile("memory_watchdog.py")
1591 self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
1592 stdin=f, stderr=subprocess.DEVNULL)
1593 f.close()
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001594 self.started = True
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001595
1596 def stop(self):
Charles-François Natali55bce632012-03-24 10:06:23 +01001597 if self.started:
1598 self.mem_watchdog.terminate()
1599 self.mem_watchdog.wait()
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001600
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001601
1602def bigmemtest(size, memuse, dry_run=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001603 """Decorator for bigmem tests.
1604
1605 'minsize' is the minimum useful size for the test (in arbitrary,
1606 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001607 the test, or a good estimate of it.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001608
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001609 if 'dry_run' is False, it means the test doesn't support dummy runs
1610 when -M is not specified.
Thomas Wouters518b5ae2011-03-25 11:42:37 +01001611 """
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001612 def decorator(f):
1613 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001614 size = wrapper.size
1615 memuse = wrapper.memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001616 if not real_max_memuse:
1617 maxsize = 5147
1618 else:
1619 maxsize = size
1620
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001621 if ((real_max_memuse or not dry_run)
1622 and real_max_memuse < maxsize * memuse):
1623 raise unittest.SkipTest(
1624 "not enough memory: %.1fG minimum needed"
1625 % (size * memuse / (1024 ** 3)))
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001626
Charles-François Natali55bce632012-03-24 10:06:23 +01001627 if real_max_memuse and verbose:
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001628 print()
1629 print(" ... expected peak memory use: {peak:.1f}G"
1630 .format(peak=size * memuse / (1024 ** 3)))
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001631 watchdog = _MemoryWatchdog()
1632 watchdog.start()
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001633 else:
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001634 watchdog = None
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001635
1636 try:
1637 return f(self, maxsize)
1638 finally:
Antoine Pitrou75e78b62011-10-04 11:51:23 +02001639 if watchdog:
1640 watchdog.stop()
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001641
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001642 wrapper.size = size
1643 wrapper.memuse = memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001644 return wrapper
1645 return decorator
1646
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001647def bigaddrspacetest(f):
1648 """Decorator for tests that fill the address space."""
1649 def wrapper(self):
1650 if max_memuse < MAX_Py_ssize_t:
Antoine Pitrou98c62bd2011-01-12 21:58:39 +00001651 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
Antoine Pitroue0d3f8a2011-01-12 21:50:44 +00001652 raise unittest.SkipTest(
1653 "not enough memory: try a 32-bit build instead")
1654 else:
1655 raise unittest.SkipTest(
1656 "not enough memory: %.1fG minimum needed"
1657 % (MAX_Py_ssize_t / (1024 ** 3)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001658 else:
1659 return f(self)
1660 return wrapper
1661
Thomas Wouters477c8d52006-05-27 19:21:47 +00001662#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +00001663# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001664
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001665class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001666 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001667 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001668 test(result)
1669 return result
1670
Benjamin Petersone549ead2009-03-28 21:42:05 +00001671def _id(obj):
1672 return obj
1673
1674def requires_resource(resource):
Antoine Pitroud20a5f62011-02-26 15:58:05 +00001675 if resource == 'gui' and not _is_gui_available():
Zachary Warececed6b2014-05-02 10:51:07 -05001676 return unittest.skip(_is_gui_available.reason)
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +00001677 if is_resource_enabled(resource):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001678 return _id
1679 else:
1680 return unittest.skip("resource {0!r} is not enabled".format(resource))
1681
1682def cpython_only(test):
1683 """
1684 Decorator for tests only applicable on CPython.
1685 """
1686 return impl_detail(cpython=True)(test)
1687
1688def impl_detail(msg=None, **guards):
1689 if check_impl_detail(**guards):
1690 return _id
1691 if msg is None:
1692 guardnames, default = _parse_guards(guards)
1693 if default:
1694 msg = "implementation detail not available on {0}"
1695 else:
1696 msg = "implementation detail specific to {0}"
1697 guardnames = sorted(guardnames.keys())
1698 msg = msg.format(' or '.join(guardnames))
1699 return unittest.skip(msg)
1700
1701def _parse_guards(guards):
1702 # Returns a tuple ({platform_name: run_me}, default_value)
1703 if not guards:
1704 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +00001705 is_true = list(guards.values())[0]
1706 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001707 return (guards, not is_true)
1708
1709# Use the following check to guard CPython's implementation-specific tests --
1710# or to run them only on the implementation(s) guarded by the arguments.
1711def check_impl_detail(**guards):
1712 """This function returns True or False depending on the host platform.
1713 Examples:
1714 if check_impl_detail(): # only on CPython (default)
1715 if check_impl_detail(jython=True): # only on Jython
1716 if check_impl_detail(cpython=False): # everywhere except on CPython
1717 """
1718 guards, default = _parse_guards(guards)
1719 return guards.get(platform.python_implementation().lower(), default)
1720
1721
Brett Cannon31f59292011-02-21 19:29:56 +00001722def no_tracing(func):
1723 """Decorator to temporarily turn off tracing for the duration of a test."""
1724 if not hasattr(sys, 'gettrace'):
1725 return func
1726 else:
1727 @functools.wraps(func)
1728 def wrapper(*args, **kwargs):
1729 original_trace = sys.gettrace()
1730 try:
1731 sys.settrace(None)
1732 return func(*args, **kwargs)
1733 finally:
1734 sys.settrace(original_trace)
1735 return wrapper
1736
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001737
Brett Cannon7a540732011-02-22 03:04:06 +00001738def refcount_test(test):
1739 """Decorator for tests which involve reference counting.
1740
1741 To start, the decorator does not run the test if is not run by CPython.
1742 After that, any trace function is unset during the test to prevent
1743 unexpected refcounts caused by the trace function.
1744
1745 """
1746 return no_tracing(cpython_only(test))
1747
1748
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001749def _filter_suite(suite, pred):
1750 """Recursively filter test cases in a suite based on a predicate."""
1751 newtests = []
1752 for test in suite._tests:
1753 if isinstance(test, unittest.TestSuite):
1754 _filter_suite(test, pred)
1755 newtests.append(test)
1756 else:
1757 if pred(test):
1758 newtests.append(test)
1759 suite._tests = newtests
1760
Guido van Rossumd8faa362007-04-27 19:54:29 +00001761def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001762 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001763 if verbose:
Antoine Pitrou216a3bc2011-07-23 22:33:39 +02001764 runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
1765 failfast=failfast)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001766 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001767 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001768
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001769 result = runner.run(suite)
1770 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001771 if len(result.errors) == 1 and not result.failures:
1772 err = result.errors[0][1]
1773 elif len(result.failures) == 1 and not result.errors:
1774 err = result.failures[0][1]
1775 else:
R. David Murray723357e2009-10-19 18:06:17 +00001776 err = "multiple errors occurred"
1777 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001778 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001779
Barry Warsawc10d6902001-09-20 06:30:41 +00001780
Walter Dörwald21d3a322003-05-01 17:45:56 +00001781def run_unittest(*classes):
1782 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001783 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001784 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001785 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001786 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001787 if cls in sys.modules:
1788 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1789 else:
1790 raise ValueError("str arguments must be keys in sys.modules")
1791 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001792 suite.addTest(cls)
1793 else:
1794 suite.addTest(unittest.makeSuite(cls))
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001795 def case_pred(test):
1796 if match_tests is None:
1797 return True
1798 for name in test.id().split("."):
1799 if fnmatch.fnmatchcase(name, match_tests):
1800 return True
1801 return False
1802 _filter_suite(suite, case_pred)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001803 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001804
Serhiy Storchaka9d0add02013-01-27 19:47:45 +02001805#=======================================================================
1806# Check for the presence of docstrings.
1807
Nick Coghlan561eb5c2013-10-26 22:20:43 +10001808# Rather than trying to enumerate all the cases where docstrings may be
1809# disabled, we just check for that directly
1810
1811def _check_docstrings():
1812 """Just used to check if docstrings are enabled"""
1813
Nick Coghlan624a74e2013-10-27 14:19:12 +10001814MISSING_C_DOCSTRINGS = (check_impl_detail() and
1815 sys.platform != 'win32' and
1816 not sysconfig.get_config_var('WITH_DOC_STRINGS'))
1817
1818HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and
1819 not MISSING_C_DOCSTRINGS)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +02001820
1821requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
1822 "test requires docstrings")
1823
Barry Warsawc10d6902001-09-20 06:30:41 +00001824
Tim Petersa0a62222001-09-09 06:12:01 +00001825#=======================================================================
1826# doctest driver.
1827
Stefan Krah1919b7e2012-03-21 18:25:23 +01001828def run_doctest(module, verbosity=None, optionflags=0):
Tim Peters17111f32001-10-03 04:08:26 +00001829 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001830
1831 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001832 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001833 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001834 """
1835
1836 import doctest
1837
1838 if verbosity is None:
1839 verbosity = verbose
1840 else:
1841 verbosity = None
1842
Stefan Krah1919b7e2012-03-21 18:25:23 +01001843 f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags)
Victor Stinnerbddc4d42011-06-29 15:52:46 +02001844 if f:
1845 raise TestFailed("%d of %d doctests failed" % (f, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001846 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001847 print('doctest (%s) ... %d tests with zero failures' %
1848 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001849 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001850
Antoine Pitrou060cee22009-11-13 16:29:04 +00001851
1852#=======================================================================
1853# Support for saving and restoring the imported modules.
1854
1855def modules_setup():
1856 return sys.modules.copy(),
1857
1858def modules_cleanup(oldmodules):
1859 # Encoders/decoders are registered permanently within the internal
1860 # codec cache. If we destroy the corresponding modules their
1861 # globals will be set to None which will trip up the cached functions.
1862 encodings = [(k, v) for k, v in sys.modules.items()
1863 if k.startswith('encodings.')]
1864 sys.modules.clear()
1865 sys.modules.update(encodings)
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001866 # XXX: This kind of problem can affect more than just encodings. In particular
Eric Smitha3e8f3d2011-01-11 10:24:34 +00001867 # extension modules (such as _ssl) don't cope with reloading properly.
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001868 # Really, test modules should be cleaning out the test specific modules they
1869 # know they added (ala test_runpy) rather than relying on this function (as
1870 # test_importhooks and test_pkg do currently).
1871 # Implicitly imported *real* modules should be left alone (see issue 10556).
Antoine Pitrou060cee22009-11-13 16:29:04 +00001872 sys.modules.update(oldmodules)
1873
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001874#=======================================================================
1875# Threading support to prevent reporting refleaks when running regrtest.py -R
1876
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001877# NOTE: we use thread._count() rather than threading.enumerate() (or the
1878# moral equivalent thereof) because a threading.Thread object is still alive
1879# until its __bootstrap() method has returned, even after it has been
1880# unregistered from the threading module.
1881# thread._count(), on the other hand, only gets decremented *after* the
1882# __bootstrap() method has returned, which gives us reliable reference counts
1883# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001884
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001885def threading_setup():
Victor Stinner45df8202010-04-28 22:31:17 +00001886 if _thread:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001887 return _thread._count(), threading._dangling.copy()
Victor Stinner45df8202010-04-28 22:31:17 +00001888 else:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001889 return 1, ()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001890
Antoine Pitrou707f2282011-07-15 22:29:44 +02001891def threading_cleanup(*original_values):
Victor Stinner45df8202010-04-28 22:31:17 +00001892 if not _thread:
1893 return
Antoine Pitrou05eafa82013-08-16 21:02:02 +02001894 _MAX_COUNT = 100
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001895 for count in range(_MAX_COUNT):
Antoine Pitrou707f2282011-07-15 22:29:44 +02001896 values = _thread._count(), threading._dangling
1897 if values == original_values:
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001898 break
Antoine Pitrou05eafa82013-08-16 21:02:02 +02001899 time.sleep(0.01)
Antoine Pitrou707f2282011-07-15 22:29:44 +02001900 gc_collect()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001901 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001902
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001903def reap_threads(func):
Victor Stinner45df8202010-04-28 22:31:17 +00001904 """Use this function when threads are being used. This will
1905 ensure that the threads are cleaned up even when the test fails.
1906 If threading is unavailable this function does nothing.
1907 """
1908 if not _thread:
1909 return func
1910
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001911 @functools.wraps(func)
1912 def decorator(*args):
1913 key = threading_setup()
1914 try:
1915 return func(*args)
1916 finally:
1917 threading_cleanup(*key)
1918 return decorator
1919
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001920def reap_children():
1921 """Use this function at the end of test_main() whenever sub-processes
1922 are started. This will help ensure that no extra children (zombies)
1923 stick around to hog resources and create problems when looking
1924 for refleaks.
1925 """
1926
1927 # Reap all our dead child processes so we don't leave zombies around.
1928 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001929 if hasattr(os, 'waitpid'):
1930 any_process = -1
1931 while True:
1932 try:
1933 # This will raise an exception on Windows. That's ok.
1934 pid, status = os.waitpid(any_process, os.WNOHANG)
1935 if pid == 0:
1936 break
1937 except:
1938 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001939
1940@contextlib.contextmanager
1941def swap_attr(obj, attr, new_val):
1942 """Temporary swap out an attribute with a new object.
1943
1944 Usage:
1945 with swap_attr(obj, "attr", 5):
1946 ...
1947
1948 This will set obj.attr to 5 for the duration of the with: block,
1949 restoring the old value at the end of the block. If `attr` doesn't
1950 exist on `obj`, it will be created and then deleted at the end of the
1951 block.
1952 """
1953 if hasattr(obj, attr):
1954 real_val = getattr(obj, attr)
1955 setattr(obj, attr, new_val)
1956 try:
1957 yield
1958 finally:
1959 setattr(obj, attr, real_val)
1960 else:
1961 setattr(obj, attr, new_val)
1962 try:
1963 yield
1964 finally:
1965 delattr(obj, attr)
1966
1967@contextlib.contextmanager
1968def swap_item(obj, item, new_val):
1969 """Temporary swap out an item with a new object.
1970
1971 Usage:
1972 with swap_item(obj, "item", 5):
1973 ...
1974
1975 This will set obj["item"] to 5 for the duration of the with: block,
1976 restoring the old value at the end of the block. If `item` doesn't
1977 exist on `obj`, it will be created and then deleted at the end of the
1978 block.
1979 """
1980 if item in obj:
1981 real_val = obj[item]
1982 obj[item] = new_val
1983 try:
1984 yield
1985 finally:
1986 obj[item] = real_val
1987 else:
1988 obj[item] = new_val
1989 try:
1990 yield
1991 finally:
1992 del obj[item]
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00001993
1994def strip_python_stderr(stderr):
1995 """Strip the stderr of a Python process from potential debug output
1996 emitted by the interpreter.
1997
1998 This will typically be run on the result of the communicate() method
1999 of a subprocess.Popen object.
2000 """
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01002001 stderr = re.sub(br"\[\d+ refs, \d+ blocks\]\r?\n?", b"", stderr).strip()
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00002002 return stderr
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00002003
2004def args_from_interpreter_flags():
2005 """Return a list of command-line arguments reproducing the current
Brett Cannonb880c152011-03-15 16:03:09 -04002006 settings in sys.flags and sys.warnoptions."""
Antoine Pitrouebdcd852012-05-18 18:33:07 +02002007 return subprocess._args_from_interpreter_flags()
Vinay Sajip129fd042010-12-10 08:19:38 +00002008
2009#============================================================
2010# Support for assertions about logging.
2011#============================================================
2012
2013class TestHandler(logging.handlers.BufferingHandler):
2014 def __init__(self, matcher):
2015 # BufferingHandler takes a "capacity" argument
2016 # so as to know when to flush. As we're overriding
2017 # shouldFlush anyway, we can set a capacity of zero.
2018 # You can call flush() manually to clear out the
2019 # buffer.
2020 logging.handlers.BufferingHandler.__init__(self, 0)
2021 self.matcher = matcher
2022
2023 def shouldFlush(self):
2024 return False
2025
2026 def emit(self, record):
2027 self.format(record)
2028 self.buffer.append(record.__dict__)
2029
2030 def matches(self, **kwargs):
2031 """
2032 Look for a saved dict whose keys/values match the supplied arguments.
2033 """
2034 result = False
2035 for d in self.buffer:
2036 if self.matcher.matches(d, **kwargs):
2037 result = True
2038 break
2039 return result
2040
2041class Matcher(object):
2042
2043 _partial_matches = ('msg', 'message')
2044
2045 def matches(self, d, **kwargs):
2046 """
2047 Try to match a single dict with the supplied arguments.
2048
2049 Keys whose values are strings and which are in self._partial_matches
2050 will be checked for partial (i.e. substring) matches. You can extend
2051 this scheme to (for example) do regular expression matching, etc.
2052 """
2053 result = True
2054 for k in kwargs:
2055 v = kwargs[k]
2056 dv = d.get(k)
2057 if not self.match_value(k, dv, v):
2058 result = False
2059 break
2060 return result
2061
2062 def match_value(self, k, dv, v):
2063 """
2064 Try to match a single stored value (dv) with a supplied value (v).
2065 """
2066 if type(v) != type(dv):
2067 result = False
2068 elif type(dv) is not str or k not in self._partial_matches:
2069 result = (v == dv)
2070 else:
2071 result = dv.find(v) >= 0
2072 return result
Brian Curtin3b4499c2010-12-28 14:31:47 +00002073
2074
2075_can_symlink = None
2076def can_symlink():
2077 global _can_symlink
2078 if _can_symlink is not None:
2079 return _can_symlink
Brett Cannonee877a02011-03-15 17:32:14 -04002080 symlink_path = TESTFN + "can_symlink"
Brian Curtin3b4499c2010-12-28 14:31:47 +00002081 try:
Brett Cannonee877a02011-03-15 17:32:14 -04002082 os.symlink(TESTFN, symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00002083 can = True
Brian Curtind25aef52011-06-13 15:16:04 -05002084 except (OSError, NotImplementedError, AttributeError):
Brian Curtin3b4499c2010-12-28 14:31:47 +00002085 can = False
Victor Stinner62ec61f2011-06-07 12:17:15 +02002086 else:
2087 os.remove(symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00002088 _can_symlink = can
2089 return can
2090
2091def skip_unless_symlink(test):
2092 """Skip decorator for tests that require functional symlink"""
2093 ok = can_symlink()
2094 msg = "Requires functional symlink implementation"
2095 return test if ok else unittest.skip(msg)(test)
Antoine Pitroue8706232011-03-15 21:05:36 +01002096
Antoine Pitrou424246f2012-05-12 19:02:01 +02002097_can_xattr = None
2098def can_xattr():
2099 global _can_xattr
2100 if _can_xattr is not None:
2101 return _can_xattr
2102 if not hasattr(os, "setxattr"):
2103 can = False
2104 else:
Hynek Schlawacke02ba102012-05-23 11:22:44 +02002105 tmp_fp, tmp_name = tempfile.mkstemp()
Antoine Pitrou424246f2012-05-12 19:02:01 +02002106 try:
2107 with open(TESTFN, "wb") as fp:
2108 try:
Hynek Schlawacke02ba102012-05-23 11:22:44 +02002109 # TESTFN & tempfile may use different file systems with
2110 # different capabilities
Larry Hastings9cf065c2012-06-22 16:30:09 -07002111 os.setxattr(tmp_fp, b"user.test", b"")
2112 os.setxattr(fp.fileno(), b"user.test", b"")
Antoine Pitrou424246f2012-05-12 19:02:01 +02002113 # Kernels < 2.6.39 don't respect setxattr flags.
2114 kernel_version = platform.release()
2115 m = re.match("2.6.(\d{1,2})", kernel_version)
2116 can = m is None or int(m.group(1)) >= 39
2117 except OSError:
2118 can = False
2119 finally:
2120 unlink(TESTFN)
Hynek Schlawacke02ba102012-05-23 11:22:44 +02002121 unlink(tmp_name)
Antoine Pitrou424246f2012-05-12 19:02:01 +02002122 _can_xattr = can
2123 return can
2124
2125def skip_unless_xattr(test):
2126 """Skip decorator for tests that require functional extended attributes"""
2127 ok = can_xattr()
2128 msg = "no non-broken extended attribute support"
2129 return test if ok else unittest.skip(msg)(test)
2130
Ezio Melotti25a40452013-03-05 20:26:17 +02002131
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002132def fs_is_case_insensitive(directory):
2133 """Detects if the file system for the specified directory is case-insensitive."""
2134 base_fp, base_path = tempfile.mkstemp(dir=directory)
2135 case_path = base_path.upper()
2136 if case_path == base_path:
2137 case_path = base_path.lower()
2138 try:
2139 return os.path.samefile(base_path, case_path)
2140 except FileNotFoundError:
2141 return False
2142 finally:
2143 os.unlink(base_path)
2144
2145
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002146class SuppressCrashReport:
2147 """Try to prevent a crash report from popping up.
2148
2149 On Windows, don't display the Windows Error Reporting dialog. On UNIX,
2150 disable the creation of coredump file.
2151 """
2152 old_value = None
2153
2154 def __enter__(self):
2155 """On Windows, disable Windows Error Reporting dialogs using
2156 SetErrorMode.
2157
2158 On UNIX, try to save the previous core file size limit, then set
2159 soft limit to 0.
2160 """
2161 if sys.platform.startswith('win'):
2162 # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
2163 # GetErrorMode is not available on Windows XP and Windows Server 2003,
2164 # but SetErrorMode returns the previous value, so we can use that
2165 import ctypes
2166 self._k32 = ctypes.windll.kernel32
2167 SEM_NOGPFAULTERRORBOX = 0x02
2168 self.old_value = self._k32.SetErrorMode(SEM_NOGPFAULTERRORBOX)
2169 self._k32.SetErrorMode(self.old_value | SEM_NOGPFAULTERRORBOX)
2170 else:
2171 if resource is not None:
2172 try:
2173 self.old_value = resource.getrlimit(resource.RLIMIT_CORE)
2174 resource.setrlimit(resource.RLIMIT_CORE,
2175 (0, self.old_value[1]))
2176 except (ValueError, OSError):
2177 pass
2178 if sys.platform == 'darwin':
2179 # Check if the 'Crash Reporter' on OSX was configured
2180 # in 'Developer' mode and warn that it will get triggered
2181 # when it is.
2182 #
2183 # This assumes that this context manager is used in tests
2184 # that might trigger the next manager.
2185 value = subprocess.Popen(['/usr/bin/defaults', 'read',
2186 'com.apple.CrashReporter', 'DialogType'],
2187 stdout=subprocess.PIPE).communicate()[0]
2188 if value.strip() == b'developer':
2189 print("this test triggers the Crash Reporter, "
2190 "that is intentional", end='', flush=True)
2191
2192 return self
2193
2194 def __exit__(self, *ignore_exc):
2195 """Restore Windows ErrorMode or core file behavior to initial value."""
2196 if self.old_value is None:
2197 return
2198
2199 if sys.platform.startswith('win'):
2200 self._k32.SetErrorMode(self.old_value)
2201 else:
2202 if resource is not None:
2203 try:
2204 resource.setrlimit(resource.RLIMIT_CORE, self.old_value)
2205 except (ValueError, OSError):
2206 pass
Ezio Melotti25a40452013-03-05 20:26:17 +02002207
2208
Antoine Pitrou2c50a092011-03-15 21:02:59 +01002209def patch(test_instance, object_to_patch, attr_name, new_value):
2210 """Override 'object_to_patch'.'attr_name' with 'new_value'.
2211
2212 Also, add a cleanup procedure to 'test_instance' to restore
2213 'object_to_patch' value for 'attr_name'.
2214 The 'attr_name' should be a valid attribute for 'object_to_patch'.
2215
2216 """
2217 # check that 'attr_name' is a real attribute for 'object_to_patch'
2218 # will raise AttributeError if it does not exist
2219 getattr(object_to_patch, attr_name)
2220
2221 # keep a copy of the old value
2222 attr_is_local = False
2223 try:
2224 old_value = object_to_patch.__dict__[attr_name]
2225 except (AttributeError, KeyError):
2226 old_value = getattr(object_to_patch, attr_name, None)
2227 else:
2228 attr_is_local = True
2229
2230 # restore the value when the test is done
2231 def cleanup():
2232 if attr_is_local:
2233 setattr(object_to_patch, attr_name, old_value)
2234 else:
2235 delattr(object_to_patch, attr_name)
2236
2237 test_instance.addCleanup(cleanup)
2238
2239 # actually override the attribute
2240 setattr(object_to_patch, attr_name, new_value)
Victor Stinnered3b0bc2013-11-23 12:27:24 +01002241
2242
2243def run_in_subinterp(code):
2244 """
2245 Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
2246 module is enabled.
2247 """
2248 # Issue #10915, #15751: PyGILState_*() functions don't work with
2249 # sub-interpreters, the tracemalloc module uses these functions internally
2250 try:
2251 import tracemalloc
2252 except ImportError:
2253 pass
2254 else:
2255 if tracemalloc.is_tracing():
2256 raise unittest.SkipTest("run_in_subinterp() cannot be used "
2257 "if tracemalloc module is tracing "
2258 "memory allocations")
Serhiy Storchakaf28ba362014-02-07 10:10:55 +02002259 import _testcapi
Victor Stinnered3b0bc2013-11-23 12:27:24 +01002260 return _testcapi.run_in_subinterp(code)