support.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  1. # -*- coding: utf-8 -*-
  2. """Supporting definitions for the Python regression tests.
  3. Backported for python-future from Python 3.3 test/support.py.
  4. """
  5. from __future__ import (absolute_import, division,
  6. print_function, unicode_literals)
  7. from future import utils
  8. from future.builtins import str, range, open, int, map, list
  9. import contextlib
  10. import errno
  11. import functools
  12. import gc
  13. import socket
  14. import sys
  15. import os
  16. import platform
  17. import shutil
  18. import warnings
  19. import unittest
  20. # For Python 2.6 compatibility:
  21. if not hasattr(unittest, 'skip'):
  22. import unittest2 as unittest
  23. import importlib
  24. # import collections.abc # not present on Py2.7
  25. import re
  26. import subprocess
  27. import imp
  28. import time
  29. try:
  30. import sysconfig
  31. except ImportError:
  32. # sysconfig is not available on Python 2.6. Try using distutils.sysconfig instead:
  33. from distutils import sysconfig
  34. import fnmatch
  35. import logging.handlers
  36. import struct
  37. import tempfile
  38. try:
  39. if utils.PY3:
  40. import _thread, threading
  41. else:
  42. import thread as _thread, threading
  43. except ImportError:
  44. _thread = None
  45. threading = None
  46. try:
  47. import multiprocessing.process
  48. except ImportError:
  49. multiprocessing = None
  50. try:
  51. import zlib
  52. except ImportError:
  53. zlib = None
  54. try:
  55. import gzip
  56. except ImportError:
  57. gzip = None
  58. try:
  59. import bz2
  60. except ImportError:
  61. bz2 = None
  62. try:
  63. import lzma
  64. except ImportError:
  65. lzma = None
  66. __all__ = [
  67. "Error", "TestFailed", "ResourceDenied", "import_module", "verbose",
  68. "use_resources", "max_memuse", "record_original_stdout",
  69. "get_original_stdout", "unload", "unlink", "rmtree", "forget",
  70. "is_resource_enabled", "requires", "requires_freebsd_version",
  71. "requires_linux_version", "requires_mac_ver", "find_unused_port",
  72. "bind_port", "IPV6_ENABLED", "is_jython", "TESTFN", "HOST", "SAVEDCWD",
  73. "temp_cwd", "findfile", "create_empty_file", "sortdict",
  74. "check_syntax_error", "open_urlresource", "check_warnings", "CleanImport",
  75. "EnvironmentVarGuard", "TransientResource", "captured_stdout",
  76. "captured_stdin", "captured_stderr", "time_out", "socket_peer_reset",
  77. "ioerror_peer_reset", "run_with_locale", 'temp_umask',
  78. "transient_internet", "set_memlimit", "bigmemtest", "bigaddrspacetest",
  79. "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
  80. "threading_cleanup", "reap_children", "cpython_only", "check_impl_detail",
  81. "get_attribute", "swap_item", "swap_attr", "requires_IEEE_754",
  82. "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink",
  83. "skip_unless_xattr", "import_fresh_module", "requires_zlib",
  84. "PIPE_MAX_SIZE", "failfast", "anticipate_failure", "run_with_tz",
  85. "requires_gzip", "requires_bz2", "requires_lzma", "suppress_crash_popup",
  86. ]
  87. class Error(Exception):
  88. """Base class for regression test exceptions."""
  89. class TestFailed(Error):
  90. """Test failed."""
  91. class ResourceDenied(unittest.SkipTest):
  92. """Test skipped because it requested a disallowed resource.
  93. This is raised when a test calls requires() for a resource that
  94. has not be enabled. It is used to distinguish between expected
  95. and unexpected skips.
  96. """
  97. @contextlib.contextmanager
  98. def _ignore_deprecated_imports(ignore=True):
  99. """Context manager to suppress package and module deprecation
  100. warnings when importing them.
  101. If ignore is False, this context manager has no effect."""
  102. if ignore:
  103. with warnings.catch_warnings():
  104. warnings.filterwarnings("ignore", ".+ (module|package)",
  105. DeprecationWarning)
  106. yield
  107. else:
  108. yield
  109. def import_module(name, deprecated=False):
  110. """Import and return the module to be tested, raising SkipTest if
  111. it is not available.
  112. If deprecated is True, any module or package deprecation messages
  113. will be suppressed."""
  114. with _ignore_deprecated_imports(deprecated):
  115. try:
  116. return importlib.import_module(name)
  117. except ImportError as msg:
  118. raise unittest.SkipTest(str(msg))
  119. def _save_and_remove_module(name, orig_modules):
  120. """Helper function to save and remove a module from sys.modules
  121. Raise ImportError if the module can't be imported.
  122. """
  123. # try to import the module and raise an error if it can't be imported
  124. if name not in sys.modules:
  125. __import__(name)
  126. del sys.modules[name]
  127. for modname in list(sys.modules):
  128. if modname == name or modname.startswith(name + '.'):
  129. orig_modules[modname] = sys.modules[modname]
  130. del sys.modules[modname]
  131. def _save_and_block_module(name, orig_modules):
  132. """Helper function to save and block a module in sys.modules
  133. Return True if the module was in sys.modules, False otherwise.
  134. """
  135. saved = True
  136. try:
  137. orig_modules[name] = sys.modules[name]
  138. except KeyError:
  139. saved = False
  140. sys.modules[name] = None
  141. return saved
  142. def anticipate_failure(condition):
  143. """Decorator to mark a test that is known to be broken in some cases
  144. Any use of this decorator should have a comment identifying the
  145. associated tracker issue.
  146. """
  147. if condition:
  148. return unittest.expectedFailure
  149. return lambda f: f
  150. def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
  151. """Import and return a module, deliberately bypassing sys.modules.
  152. This function imports and returns a fresh copy of the named Python module
  153. by removing the named module from sys.modules before doing the import.
  154. Note that unlike reload, the original module is not affected by
  155. this operation.
  156. *fresh* is an iterable of additional module names that are also removed
  157. from the sys.modules cache before doing the import.
  158. *blocked* is an iterable of module names that are replaced with None
  159. in the module cache during the import to ensure that attempts to import
  160. them raise ImportError.
  161. The named module and any modules named in the *fresh* and *blocked*
  162. parameters are saved before starting the import and then reinserted into
  163. sys.modules when the fresh import is complete.
  164. Module and package deprecation messages are suppressed during this import
  165. if *deprecated* is True.
  166. This function will raise ImportError if the named module cannot be
  167. imported.
  168. If deprecated is True, any module or package deprecation messages
  169. will be suppressed.
  170. """
  171. # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
  172. # to make sure that this utility function is working as expected
  173. with _ignore_deprecated_imports(deprecated):
  174. # Keep track of modules saved for later restoration as well
  175. # as those which just need a blocking entry removed
  176. orig_modules = {}
  177. names_to_remove = []
  178. _save_and_remove_module(name, orig_modules)
  179. try:
  180. for fresh_name in fresh:
  181. _save_and_remove_module(fresh_name, orig_modules)
  182. for blocked_name in blocked:
  183. if not _save_and_block_module(blocked_name, orig_modules):
  184. names_to_remove.append(blocked_name)
  185. fresh_module = importlib.import_module(name)
  186. except ImportError:
  187. fresh_module = None
  188. finally:
  189. for orig_name, module in orig_modules.items():
  190. sys.modules[orig_name] = module
  191. for name_to_remove in names_to_remove:
  192. del sys.modules[name_to_remove]
  193. return fresh_module
  194. def get_attribute(obj, name):
  195. """Get an attribute, raising SkipTest if AttributeError is raised."""
  196. try:
  197. attribute = getattr(obj, name)
  198. except AttributeError:
  199. raise unittest.SkipTest("object %r has no attribute %r" % (obj, name))
  200. else:
  201. return attribute
  202. verbose = 1 # Flag set to 0 by regrtest.py
  203. use_resources = None # Flag set to [] by regrtest.py
  204. max_memuse = 0 # Disable bigmem tests (they will still be run with
  205. # small sizes, to make sure they work.)
  206. real_max_memuse = 0
  207. failfast = False
  208. match_tests = None
  209. # _original_stdout is meant to hold stdout at the time regrtest began.
  210. # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
  211. # The point is to have some flavor of stdout the user can actually see.
  212. _original_stdout = None
  213. def record_original_stdout(stdout):
  214. global _original_stdout
  215. _original_stdout = stdout
  216. def get_original_stdout():
  217. return _original_stdout or sys.stdout
  218. def unload(name):
  219. try:
  220. del sys.modules[name]
  221. except KeyError:
  222. pass
  223. if sys.platform.startswith("win"):
  224. def _waitfor(func, pathname, waitall=False):
  225. # Perform the operation
  226. func(pathname)
  227. # Now setup the wait loop
  228. if waitall:
  229. dirname = pathname
  230. else:
  231. dirname, name = os.path.split(pathname)
  232. dirname = dirname or '.'
  233. # Check for `pathname` to be removed from the filesystem.
  234. # The exponential backoff of the timeout amounts to a total
  235. # of ~1 second after which the deletion is probably an error
  236. # anyway.
  237. # Testing on a i7@4.3GHz shows that usually only 1 iteration is
  238. # required when contention occurs.
  239. timeout = 0.001
  240. while timeout < 1.0:
  241. # Note we are only testing for the existence of the file(s) in
  242. # the contents of the directory regardless of any security or
  243. # access rights. If we have made it this far, we have sufficient
  244. # permissions to do that much using Python's equivalent of the
  245. # Windows API FindFirstFile.
  246. # Other Windows APIs can fail or give incorrect results when
  247. # dealing with files that are pending deletion.
  248. L = os.listdir(dirname)
  249. if not (L if waitall else name in L):
  250. return
  251. # Increase the timeout and try again
  252. time.sleep(timeout)
  253. timeout *= 2
  254. warnings.warn('tests may fail, delete still pending for ' + pathname,
  255. RuntimeWarning, stacklevel=4)
  256. def _unlink(filename):
  257. _waitfor(os.unlink, filename)
  258. def _rmdir(dirname):
  259. _waitfor(os.rmdir, dirname)
  260. def _rmtree(path):
  261. def _rmtree_inner(path):
  262. for name in os.listdir(path):
  263. fullname = os.path.join(path, name)
  264. if os.path.isdir(fullname):
  265. _waitfor(_rmtree_inner, fullname, waitall=True)
  266. os.rmdir(fullname)
  267. else:
  268. os.unlink(fullname)
  269. _waitfor(_rmtree_inner, path, waitall=True)
  270. _waitfor(os.rmdir, path)
  271. else:
  272. _unlink = os.unlink
  273. _rmdir = os.rmdir
  274. _rmtree = shutil.rmtree
  275. def unlink(filename):
  276. try:
  277. _unlink(filename)
  278. except OSError as error:
  279. # The filename need not exist.
  280. if error.errno not in (errno.ENOENT, errno.ENOTDIR):
  281. raise
  282. def rmdir(dirname):
  283. try:
  284. _rmdir(dirname)
  285. except OSError as error:
  286. # The directory need not exist.
  287. if error.errno != errno.ENOENT:
  288. raise
  289. def rmtree(path):
  290. try:
  291. _rmtree(path)
  292. except OSError as error:
  293. if error.errno != errno.ENOENT:
  294. raise
  295. def make_legacy_pyc(source):
  296. """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
  297. The choice of .pyc or .pyo extension is done based on the __debug__ flag
  298. value.
  299. :param source: The file system path to the source file. The source file
  300. does not need to exist, however the PEP 3147 pyc file must exist.
  301. :return: The file system path to the legacy pyc file.
  302. """
  303. pyc_file = imp.cache_from_source(source)
  304. up_one = os.path.dirname(os.path.abspath(source))
  305. legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
  306. os.rename(pyc_file, legacy_pyc)
  307. return legacy_pyc
  308. def forget(modname):
  309. """'Forget' a module was ever imported.
  310. This removes the module from sys.modules and deletes any PEP 3147 or
  311. legacy .pyc and .pyo files.
  312. """
  313. unload(modname)
  314. for dirname in sys.path:
  315. source = os.path.join(dirname, modname + '.py')
  316. # It doesn't matter if they exist or not, unlink all possible
  317. # combinations of PEP 3147 and legacy pyc and pyo files.
  318. unlink(source + 'c')
  319. unlink(source + 'o')
  320. unlink(imp.cache_from_source(source, debug_override=True))
  321. unlink(imp.cache_from_source(source, debug_override=False))
  322. # On some platforms, should not run gui test even if it is allowed
  323. # in `use_resources'.
  324. if sys.platform.startswith('win'):
  325. import ctypes
  326. import ctypes.wintypes
  327. def _is_gui_available():
  328. UOI_FLAGS = 1
  329. WSF_VISIBLE = 0x0001
  330. class USEROBJECTFLAGS(ctypes.Structure):
  331. _fields_ = [("fInherit", ctypes.wintypes.BOOL),
  332. ("fReserved", ctypes.wintypes.BOOL),
  333. ("dwFlags", ctypes.wintypes.DWORD)]
  334. dll = ctypes.windll.user32
  335. h = dll.GetProcessWindowStation()
  336. if not h:
  337. raise ctypes.WinError()
  338. uof = USEROBJECTFLAGS()
  339. needed = ctypes.wintypes.DWORD()
  340. res = dll.GetUserObjectInformationW(h,
  341. UOI_FLAGS,
  342. ctypes.byref(uof),
  343. ctypes.sizeof(uof),
  344. ctypes.byref(needed))
  345. if not res:
  346. raise ctypes.WinError()
  347. return bool(uof.dwFlags & WSF_VISIBLE)
  348. else:
  349. def _is_gui_available():
  350. return True
  351. def is_resource_enabled(resource):
  352. """Test whether a resource is enabled. Known resources are set by
  353. regrtest.py."""
  354. return use_resources is not None and resource in use_resources
  355. def requires(resource, msg=None):
  356. """Raise ResourceDenied if the specified resource is not available.
  357. If the caller's module is __main__ then automatically return True. The
  358. possibility of False being returned occurs when regrtest.py is
  359. executing.
  360. """
  361. if resource == 'gui' and not _is_gui_available():
  362. raise unittest.SkipTest("Cannot use the 'gui' resource")
  363. # see if the caller's module is __main__ - if so, treat as if
  364. # the resource was set
  365. if sys._getframe(1).f_globals.get("__name__") == "__main__":
  366. return
  367. if not is_resource_enabled(resource):
  368. if msg is None:
  369. msg = "Use of the %r resource not enabled" % resource
  370. raise ResourceDenied(msg)
  371. def _requires_unix_version(sysname, min_version):
  372. """Decorator raising SkipTest if the OS is `sysname` and the version is less
  373. than `min_version`.
  374. For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
  375. the FreeBSD version is less than 7.2.
  376. """
  377. def decorator(func):
  378. @functools.wraps(func)
  379. def wrapper(*args, **kw):
  380. if platform.system() == sysname:
  381. version_txt = platform.release().split('-', 1)[0]
  382. try:
  383. version = tuple(map(int, version_txt.split('.')))
  384. except ValueError:
  385. pass
  386. else:
  387. if version < min_version:
  388. min_version_txt = '.'.join(map(str, min_version))
  389. raise unittest.SkipTest(
  390. "%s version %s or higher required, not %s"
  391. % (sysname, min_version_txt, version_txt))
  392. return func(*args, **kw)
  393. wrapper.min_version = min_version
  394. return wrapper
  395. return decorator
  396. def requires_freebsd_version(*min_version):
  397. """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
  398. less than `min_version`.
  399. For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
  400. version is less than 7.2.
  401. """
  402. return _requires_unix_version('FreeBSD', min_version)
  403. def requires_linux_version(*min_version):
  404. """Decorator raising SkipTest if the OS is Linux and the Linux version is
  405. less than `min_version`.
  406. For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
  407. version is less than 2.6.32.
  408. """
  409. return _requires_unix_version('Linux', min_version)
  410. def requires_mac_ver(*min_version):
  411. """Decorator raising SkipTest if the OS is Mac OS X and the OS X
  412. version if less than min_version.
  413. For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
  414. is lesser than 10.5.
  415. """
  416. def decorator(func):
  417. @functools.wraps(func)
  418. def wrapper(*args, **kw):
  419. if sys.platform == 'darwin':
  420. version_txt = platform.mac_ver()[0]
  421. try:
  422. version = tuple(map(int, version_txt.split('.')))
  423. except ValueError:
  424. pass
  425. else:
  426. if version < min_version:
  427. min_version_txt = '.'.join(map(str, min_version))
  428. raise unittest.SkipTest(
  429. "Mac OS X %s or higher required, not %s"
  430. % (min_version_txt, version_txt))
  431. return func(*args, **kw)
  432. wrapper.min_version = min_version
  433. return wrapper
  434. return decorator
  435. # Don't use "localhost", since resolving it uses the DNS under recent
  436. # Windows versions (see issue #18792).
  437. HOST = "127.0.0.1"
  438. HOSTv6 = "::1"
  439. def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
  440. """Returns an unused port that should be suitable for binding. This is
  441. achieved by creating a temporary socket with the same family and type as
  442. the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
  443. the specified host address (defaults to 0.0.0.0) with the port set to 0,
  444. eliciting an unused ephemeral port from the OS. The temporary socket is
  445. then closed and deleted, and the ephemeral port is returned.
  446. Either this method or bind_port() should be used for any tests where a
  447. server socket needs to be bound to a particular port for the duration of
  448. the test. Which one to use depends on whether the calling code is creating
  449. a python socket, or if an unused port needs to be provided in a constructor
  450. or passed to an external program (i.e. the -accept argument to openssl's
  451. s_server mode). Always prefer bind_port() over find_unused_port() where
  452. possible. Hard coded ports should *NEVER* be used. As soon as a server
  453. socket is bound to a hard coded port, the ability to run multiple instances
  454. of the test simultaneously on the same host is compromised, which makes the
  455. test a ticking time bomb in a buildbot environment. On Unix buildbots, this
  456. may simply manifest as a failed test, which can be recovered from without
  457. intervention in most cases, but on Windows, the entire python process can
  458. completely and utterly wedge, requiring someone to log in to the buildbot
  459. and manually kill the affected process.
  460. (This is easy to reproduce on Windows, unfortunately, and can be traced to
  461. the SO_REUSEADDR socket option having different semantics on Windows versus
  462. Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
  463. listen and then accept connections on identical host/ports. An EADDRINUSE
  464. socket.error will be raised at some point (depending on the platform and
  465. the order bind and listen were called on each socket).
  466. However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
  467. will ever be raised when attempting to bind two identical host/ports. When
  468. accept() is called on each socket, the second caller's process will steal
  469. the port from the first caller, leaving them both in an awkwardly wedged
  470. state where they'll no longer respond to any signals or graceful kills, and
  471. must be forcibly killed via OpenProcess()/TerminateProcess().
  472. The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
  473. instead of SO_REUSEADDR, which effectively affords the same semantics as
  474. SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
  475. Source world compared to Windows ones, this is a common mistake. A quick
  476. look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
  477. openssl.exe is called with the 's_server' option, for example. See
  478. http://bugs.python.org/issue2550 for more info. The following site also
  479. has a very thorough description about the implications of both REUSEADDR
  480. and EXCLUSIVEADDRUSE on Windows:
  481. http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
  482. XXX: although this approach is a vast improvement on previous attempts to
  483. elicit unused ports, it rests heavily on the assumption that the ephemeral
  484. port returned to us by the OS won't immediately be dished back out to some
  485. other process when we close and delete our temporary socket but before our
  486. calling code has a chance to bind the returned port. We can deal with this
  487. issue if/when we come across it.
  488. """
  489. tempsock = socket.socket(family, socktype)
  490. port = bind_port(tempsock)
  491. tempsock.close()
  492. del tempsock
  493. return port
  494. def bind_port(sock, host=HOST):
  495. """Bind the socket to a free port and return the port number. Relies on
  496. ephemeral ports in order to ensure we are using an unbound port. This is
  497. important as many tests may be running simultaneously, especially in a
  498. buildbot environment. This method raises an exception if the sock.family
  499. is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
  500. or SO_REUSEPORT set on it. Tests should *never* set these socket options
  501. for TCP/IP sockets. The only case for setting these options is testing
  502. multicasting via multiple UDP sockets.
  503. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
  504. on Windows), it will be set on the socket. This will prevent anyone else
  505. from bind()'ing to our host/port for the duration of the test.
  506. """
  507. if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
  508. if hasattr(socket, 'SO_REUSEADDR'):
  509. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
  510. raise TestFailed("tests should never set the SO_REUSEADDR " \
  511. "socket option on TCP/IP sockets!")
  512. if hasattr(socket, 'SO_REUSEPORT'):
  513. try:
  514. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
  515. raise TestFailed("tests should never set the SO_REUSEPORT " \
  516. "socket option on TCP/IP sockets!")
  517. except socket.error:
  518. # Python's socket module was compiled using modern headers
  519. # thus defining SO_REUSEPORT but this process is running
  520. # under an older kernel that does not support SO_REUSEPORT.
  521. pass
  522. if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
  523. sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  524. sock.bind((host, 0))
  525. port = sock.getsockname()[1]
  526. return port
  527. def _is_ipv6_enabled():
  528. """Check whether IPv6 is enabled on this host."""
  529. if socket.has_ipv6:
  530. sock = None
  531. try:
  532. sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  533. sock.bind(('::1', 0))
  534. return True
  535. except (socket.error, socket.gaierror):
  536. pass
  537. finally:
  538. if sock:
  539. sock.close()
  540. return False
  541. IPV6_ENABLED = _is_ipv6_enabled()
  542. # A constant likely larger than the underlying OS pipe buffer size, to
  543. # make writes blocking.
  544. # Windows limit seems to be around 512 B, and many Unix kernels have a
  545. # 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
  546. # (see issue #17835 for a discussion of this number).
  547. PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
  548. # A constant likely larger than the underlying OS socket buffer size, to make
  549. # writes blocking.
  550. # The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
  551. # on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
  552. # for a discussion of this number).
  553. SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1
  554. # # decorator for skipping tests on non-IEEE 754 platforms
  555. # requires_IEEE_754 = unittest.skipUnless(
  556. # float.__getformat__("double").startswith("IEEE"),
  557. # "test requires IEEE 754 doubles")
  558. requires_zlib = unittest.skipUnless(zlib, 'requires zlib')
  559. requires_bz2 = unittest.skipUnless(bz2, 'requires bz2')
  560. requires_lzma = unittest.skipUnless(lzma, 'requires lzma')
  561. is_jython = sys.platform.startswith('java')
  562. # Filename used for testing
  563. if os.name == 'java':
  564. # Jython disallows @ in module names
  565. TESTFN = '$test'
  566. else:
  567. TESTFN = '@test'
  568. # Disambiguate TESTFN for parallel testing, while letting it remain a valid
  569. # module name.
  570. TESTFN = "{0}_{1}_tmp".format(TESTFN, os.getpid())
  571. # # FS_NONASCII: non-ASCII character encodable by os.fsencode(),
  572. # # or None if there is no such character.
  573. # FS_NONASCII = None
  574. # for character in (
  575. # # First try printable and common characters to have a readable filename.
  576. # # For each character, the encoding list are just example of encodings able
  577. # # to encode the character (the list is not exhaustive).
  578. #
  579. # # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
  580. # '\u00E6',
  581. # # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
  582. # '\u0130',
  583. # # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
  584. # '\u0141',
  585. # # U+03C6 (Greek Small Letter Phi): cp1253
  586. # '\u03C6',
  587. # # U+041A (Cyrillic Capital Letter Ka): cp1251
  588. # '\u041A',
  589. # # U+05D0 (Hebrew Letter Alef): Encodable to cp424
  590. # '\u05D0',
  591. # # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
  592. # '\u060C',
  593. # # U+062A (Arabic Letter Teh): cp720
  594. # '\u062A',
  595. # # U+0E01 (Thai Character Ko Kai): cp874
  596. # '\u0E01',
  597. #
  598. # # Then try more "special" characters. "special" because they may be
  599. # # interpreted or displayed differently depending on the exact locale
  600. # # encoding and the font.
  601. #
  602. # # U+00A0 (No-Break Space)
  603. # '\u00A0',
  604. # # U+20AC (Euro Sign)
  605. # '\u20AC',
  606. # ):
  607. # try:
  608. # os.fsdecode(os.fsencode(character))
  609. # except UnicodeError:
  610. # pass
  611. # else:
  612. # FS_NONASCII = character
  613. # break
  614. #
  615. # # TESTFN_UNICODE is a non-ascii filename
  616. # TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
  617. # if sys.platform == 'darwin':
  618. # # In Mac OS X's VFS API file names are, by definition, canonically
  619. # # decomposed Unicode, encoded using UTF-8. See QA1173:
  620. # # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
  621. # import unicodedata
  622. # TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
  623. # TESTFN_ENCODING = sys.getfilesystemencoding()
  624. #
  625. # # TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
  626. # # encoded by the filesystem encoding (in strict mode). It can be None if we
  627. # # cannot generate such filename.
  628. # TESTFN_UNENCODABLE = None
  629. # if os.name in ('nt', 'ce'):
  630. # # skip win32s (0) or Windows 9x/ME (1)
  631. # if sys.getwindowsversion().platform >= 2:
  632. # # Different kinds of characters from various languages to minimize the
  633. # # probability that the whole name is encodable to MBCS (issue #9819)
  634. # TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
  635. # try:
  636. # TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
  637. # except UnicodeEncodeError:
  638. # pass
  639. # else:
  640. # print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
  641. # 'Unicode filename tests may not be effective'
  642. # % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
  643. # TESTFN_UNENCODABLE = None
  644. # # Mac OS X denies unencodable filenames (invalid utf-8)
  645. # elif sys.platform != 'darwin':
  646. # try:
  647. # # ascii and utf-8 cannot encode the byte 0xff
  648. # b'\xff'.decode(TESTFN_ENCODING)
  649. # except UnicodeDecodeError:
  650. # # 0xff will be encoded using the surrogate character u+DCFF
  651. # TESTFN_UNENCODABLE = TESTFN \
  652. # + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
  653. # else:
  654. # # File system encoding (eg. ISO-8859-* encodings) can encode
  655. # # the byte 0xff. Skip some unicode filename tests.
  656. # pass
  657. #
  658. # # TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be
  659. # # decoded from the filesystem encoding (in strict mode). It can be None if we
  660. # # cannot generate such filename (ex: the latin1 encoding can decode any byte
  661. # # sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks
  662. # # to the surrogateescape error handler (PEP 383), but not from the filesystem
  663. # # encoding in strict mode.
  664. # TESTFN_UNDECODABLE = None
  665. # for name in (
  666. # # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows
  667. # # accepts it to create a file or a directory, or don't accept to enter to
  668. # # such directory (when the bytes name is used). So test b'\xe7' first: it is
  669. # # not decodable from cp932.
  670. # b'\xe7w\xf0',
  671. # # undecodable from ASCII, UTF-8
  672. # b'\xff',
  673. # # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856
  674. # # and cp857
  675. # b'\xae\xd5'
  676. # # undecodable from UTF-8 (UNIX and Mac OS X)
  677. # b'\xed\xb2\x80', b'\xed\xb4\x80',
  678. # # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252,
  679. # # cp1253, cp1254, cp1255, cp1257, cp1258
  680. # b'\x81\x98',
  681. # ):
  682. # try:
  683. # name.decode(TESTFN_ENCODING)
  684. # except UnicodeDecodeError:
  685. # TESTFN_UNDECODABLE = os.fsencode(TESTFN) + name
  686. # break
  687. #
  688. # if FS_NONASCII:
  689. # TESTFN_NONASCII = TESTFN + '-' + FS_NONASCII
  690. # else:
  691. # TESTFN_NONASCII = None
  692. # Save the initial cwd
  693. SAVEDCWD = os.getcwd()
  694. @contextlib.contextmanager
  695. def temp_cwd(name='tempcwd', quiet=False, path=None):
  696. """
  697. Context manager that temporarily changes the CWD.
  698. An existing path may be provided as *path*, in which case this
  699. function makes no changes to the file system.
  700. Otherwise, the new CWD is created in the current directory and it's
  701. named *name*. If *quiet* is False (default) and it's not possible to
  702. create or change the CWD, an error is raised. If it's True, only a
  703. warning is raised and the original CWD is used.
  704. """
  705. saved_dir = os.getcwd()
  706. is_temporary = False
  707. if path is None:
  708. path = name
  709. try:
  710. os.mkdir(name)
  711. is_temporary = True
  712. except OSError:
  713. if not quiet:
  714. raise
  715. warnings.warn('tests may fail, unable to create temp CWD ' + name,
  716. RuntimeWarning, stacklevel=3)
  717. try:
  718. os.chdir(path)
  719. except OSError:
  720. if not quiet:
  721. raise
  722. warnings.warn('tests may fail, unable to change the CWD to ' + path,
  723. RuntimeWarning, stacklevel=3)
  724. try:
  725. yield os.getcwd()
  726. finally:
  727. os.chdir(saved_dir)
  728. if is_temporary:
  729. rmtree(name)
  730. if hasattr(os, "umask"):
  731. @contextlib.contextmanager
  732. def temp_umask(umask):
  733. """Context manager that temporarily sets the process umask."""
  734. oldmask = os.umask(umask)
  735. try:
  736. yield
  737. finally:
  738. os.umask(oldmask)
  739. def findfile(file, here=__file__, subdir=None):
  740. """Try to find a file on sys.path and the working directory. If it is not
  741. found the argument passed to the function is returned (this does not
  742. necessarily signal failure; could still be the legitimate path)."""
  743. if os.path.isabs(file):
  744. return file
  745. if subdir is not None:
  746. file = os.path.join(subdir, file)
  747. path = sys.path
  748. path = [os.path.dirname(here)] + path
  749. for dn in path:
  750. fn = os.path.join(dn, file)
  751. if os.path.exists(fn): return fn
  752. return file
  753. def create_empty_file(filename):
  754. """Create an empty file. If the file already exists, truncate it."""
  755. fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
  756. os.close(fd)
  757. def sortdict(dict):
  758. "Like repr(dict), but in sorted order."
  759. items = sorted(dict.items())
  760. reprpairs = ["%r: %r" % pair for pair in items]
  761. withcommas = ", ".join(reprpairs)
  762. return "{%s}" % withcommas
  763. def make_bad_fd():
  764. """
  765. Create an invalid file descriptor by opening and closing a file and return
  766. its fd.
  767. """
  768. file = open(TESTFN, "wb")
  769. try:
  770. return file.fileno()
  771. finally:
  772. file.close()
  773. unlink(TESTFN)
  774. def check_syntax_error(testcase, statement):
  775. testcase.assertRaises(SyntaxError, compile, statement,
  776. '<test string>', 'exec')
  777. def open_urlresource(url, *args, **kw):
  778. from future.backports.urllib import (request as urllib_request,
  779. parse as urllib_parse)
  780. check = kw.pop('check', None)
  781. filename = urllib_parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
  782. fn = os.path.join(os.path.dirname(__file__), "data", filename)
  783. def check_valid_file(fn):
  784. f = open(fn, *args, **kw)
  785. if check is None:
  786. return f
  787. elif check(f):
  788. f.seek(0)
  789. return f
  790. f.close()
  791. if os.path.exists(fn):
  792. f = check_valid_file(fn)
  793. if f is not None:
  794. return f
  795. unlink(fn)
  796. # Verify the requirement before downloading the file
  797. requires('urlfetch')
  798. print('\tfetching %s ...' % url, file=get_original_stdout())
  799. f = urllib_request.urlopen(url, timeout=15)
  800. try:
  801. with open(fn, "wb") as out:
  802. s = f.read()
  803. while s:
  804. out.write(s)
  805. s = f.read()
  806. finally:
  807. f.close()
  808. f = check_valid_file(fn)
  809. if f is not None:
  810. return f
  811. raise TestFailed('invalid resource %r' % fn)
  812. class WarningsRecorder(object):
  813. """Convenience wrapper for the warnings list returned on
  814. entry to the warnings.catch_warnings() context manager.
  815. """
  816. def __init__(self, warnings_list):
  817. self._warnings = warnings_list
  818. self._last = 0
  819. def __getattr__(self, attr):
  820. if len(self._warnings) > self._last:
  821. return getattr(self._warnings[-1], attr)
  822. elif attr in warnings.WarningMessage._WARNING_DETAILS:
  823. return None
  824. raise AttributeError("%r has no attribute %r" % (self, attr))
  825. @property
  826. def warnings(self):
  827. return self._warnings[self._last:]
  828. def reset(self):
  829. self._last = len(self._warnings)
  830. def _filterwarnings(filters, quiet=False):
  831. """Catch the warnings, then check if all the expected
  832. warnings have been raised and re-raise unexpected warnings.
  833. If 'quiet' is True, only re-raise the unexpected warnings.
  834. """
  835. # Clear the warning registry of the calling module
  836. # in order to re-raise the warnings.
  837. frame = sys._getframe(2)
  838. registry = frame.f_globals.get('__warningregistry__')
  839. if registry:
  840. if utils.PY3:
  841. registry.clear()
  842. else:
  843. # Py2-compatible:
  844. for i in range(len(registry)):
  845. registry.pop()
  846. with warnings.catch_warnings(record=True) as w:
  847. # Set filter "always" to record all warnings. Because
  848. # test_warnings swap the module, we need to look up in
  849. # the sys.modules dictionary.
  850. sys.modules['warnings'].simplefilter("always")
  851. yield WarningsRecorder(w)
  852. # Filter the recorded warnings
  853. reraise = list(w)
  854. missing = []
  855. for msg, cat in filters:
  856. seen = False
  857. for w in reraise[:]:
  858. warning = w.message
  859. # Filter out the matching messages
  860. if (re.match(msg, str(warning), re.I) and
  861. issubclass(warning.__class__, cat)):
  862. seen = True
  863. reraise.remove(w)
  864. if not seen and not quiet:
  865. # This filter caught nothing
  866. missing.append((msg, cat.__name__))
  867. if reraise:
  868. raise AssertionError("unhandled warning %s" % reraise[0])
  869. if missing:
  870. raise AssertionError("filter (%r, %s) did not catch any warning" %
  871. missing[0])
  872. @contextlib.contextmanager
  873. def check_warnings(*filters, **kwargs):
  874. """Context manager to silence warnings.
  875. Accept 2-tuples as positional arguments:
  876. ("message regexp", WarningCategory)
  877. Optional argument:
  878. - if 'quiet' is True, it does not fail if a filter catches nothing
  879. (default True without argument,
  880. default False if some filters are defined)
  881. Without argument, it defaults to:
  882. check_warnings(("", Warning), quiet=True)
  883. """
  884. quiet = kwargs.get('quiet')
  885. if not filters:
  886. filters = (("", Warning),)
  887. # Preserve backward compatibility
  888. if quiet is None:
  889. quiet = True
  890. return _filterwarnings(filters, quiet)
  891. class CleanImport(object):
  892. """Context manager to force import to return a new module reference.
  893. This is useful for testing module-level behaviours, such as
  894. the emission of a DeprecationWarning on import.
  895. Use like this:
  896. with CleanImport("foo"):
  897. importlib.import_module("foo") # new reference
  898. """
  899. def __init__(self, *module_names):
  900. self.original_modules = sys.modules.copy()
  901. for module_name in module_names:
  902. if module_name in sys.modules:
  903. module = sys.modules[module_name]
  904. # It is possible that module_name is just an alias for
  905. # another module (e.g. stub for modules renamed in 3.x).
  906. # In that case, we also need delete the real module to clear
  907. # the import cache.
  908. if module.__name__ != module_name:
  909. del sys.modules[module.__name__]
  910. del sys.modules[module_name]
  911. def __enter__(self):
  912. return self
  913. def __exit__(self, *ignore_exc):
  914. sys.modules.update(self.original_modules)
  915. ### Added for python-future:
  916. if utils.PY3:
  917. import collections.abc
  918. mybase = collections.abc.MutableMapping
  919. else:
  920. import UserDict
  921. mybase = UserDict.DictMixin
  922. ###
  923. class EnvironmentVarGuard(mybase):
  924. """Class to help protect the environment variable properly. Can be used as
  925. a context manager."""
  926. def __init__(self):
  927. self._environ = os.environ
  928. self._changed = {}
  929. def __getitem__(self, envvar):
  930. return self._environ[envvar]
  931. def __setitem__(self, envvar, value):
  932. # Remember the initial value on the first access
  933. if envvar not in self._changed:
  934. self._changed[envvar] = self._environ.get(envvar)
  935. self._environ[envvar] = value
  936. def __delitem__(self, envvar):
  937. # Remember the initial value on the first access
  938. if envvar not in self._changed:
  939. self._changed[envvar] = self._environ.get(envvar)
  940. if envvar in self._environ:
  941. del self._environ[envvar]
  942. def keys(self):
  943. return self._environ.keys()
  944. def __iter__(self):
  945. return iter(self._environ)
  946. def __len__(self):
  947. return len(self._environ)
  948. def set(self, envvar, value):
  949. self[envvar] = value
  950. def unset(self, envvar):
  951. del self[envvar]
  952. def __enter__(self):
  953. return self
  954. def __exit__(self, *ignore_exc):
  955. for (k, v) in self._changed.items():
  956. if v is None:
  957. if k in self._environ:
  958. del self._environ[k]
  959. else:
  960. self._environ[k] = v
  961. os.environ = self._environ
  962. class DirsOnSysPath(object):
  963. """Context manager to temporarily add directories to sys.path.
  964. This makes a copy of sys.path, appends any directories given
  965. as positional arguments, then reverts sys.path to the copied
  966. settings when the context ends.
  967. Note that *all* sys.path modifications in the body of the
  968. context manager, including replacement of the object,
  969. will be reverted at the end of the block.
  970. """
  971. def __init__(self, *paths):
  972. self.original_value = sys.path[:]
  973. self.original_object = sys.path
  974. sys.path.extend(paths)
  975. def __enter__(self):
  976. return self
  977. def __exit__(self, *ignore_exc):
  978. sys.path = self.original_object
  979. sys.path[:] = self.original_value
  980. class TransientResource(object):
  981. """Raise ResourceDenied if an exception is raised while the context manager
  982. is in effect that matches the specified exception and attributes."""
  983. def __init__(self, exc, **kwargs):
  984. self.exc = exc
  985. self.attrs = kwargs
  986. def __enter__(self):
  987. return self
  988. def __exit__(self, type_=None, value=None, traceback=None):
  989. """If type_ is a subclass of self.exc and value has attributes matching
  990. self.attrs, raise ResourceDenied. Otherwise let the exception
  991. propagate (if any)."""
  992. if type_ is not None and issubclass(self.exc, type_):
  993. for attr, attr_value in self.attrs.items():
  994. if not hasattr(value, attr):
  995. break
  996. if getattr(value, attr) != attr_value:
  997. break
  998. else:
  999. raise ResourceDenied("an optional resource is not available")
  1000. # Context managers that raise ResourceDenied when various issues
  1001. # with the Internet connection manifest themselves as exceptions.
  1002. # XXX deprecate these and use transient_internet() instead
  1003. time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
  1004. socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
  1005. ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
  1006. @contextlib.contextmanager
  1007. def transient_internet(resource_name, timeout=30.0, errnos=()):
  1008. """Return a context manager that raises ResourceDenied when various issues
  1009. with the Internet connection manifest themselves as exceptions."""
  1010. default_errnos = [
  1011. ('ECONNREFUSED', 111),
  1012. ('ECONNRESET', 104),
  1013. ('EHOSTUNREACH', 113),
  1014. ('ENETUNREACH', 101),
  1015. ('ETIMEDOUT', 110),
  1016. ]
  1017. default_gai_errnos = [
  1018. ('EAI_AGAIN', -3),
  1019. ('EAI_FAIL', -4),
  1020. ('EAI_NONAME', -2),
  1021. ('EAI_NODATA', -5),
  1022. # Encountered when trying to resolve IPv6-only hostnames
  1023. ('WSANO_DATA', 11004),
  1024. ]
  1025. denied = ResourceDenied("Resource %r is not available" % resource_name)
  1026. captured_errnos = errnos
  1027. gai_errnos = []
  1028. if not captured_errnos:
  1029. captured_errnos = [getattr(errno, name, num)
  1030. for (name, num) in default_errnos]
  1031. gai_errnos = [getattr(socket, name, num)
  1032. for (name, num) in default_gai_errnos]
  1033. def filter_error(err):
  1034. n = getattr(err, 'errno', None)
  1035. if (isinstance(err, socket.timeout) or
  1036. (isinstance(err, socket.gaierror) and n in gai_errnos) or
  1037. n in captured_errnos):
  1038. if not verbose:
  1039. sys.stderr.write(denied.args[0] + "\n")
  1040. # Was: raise denied from err
  1041. # For Python-Future:
  1042. exc = denied
  1043. exc.__cause__ = err
  1044. raise exc
  1045. old_timeout = socket.getdefaulttimeout()
  1046. try:
  1047. if timeout is not None:
  1048. socket.setdefaulttimeout(timeout)
  1049. yield
  1050. except IOError as err:
  1051. # urllib can wrap original socket errors multiple times (!), we must
  1052. # unwrap to get at the original error.
  1053. while True:
  1054. a = err.args
  1055. if len(a) >= 1 and isinstance(a[0], IOError):
  1056. err = a[0]
  1057. # The error can also be wrapped as args[1]:
  1058. # except socket.error as msg:
  1059. # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
  1060. elif len(a) >= 2 and isinstance(a[1], IOError):
  1061. err = a[1]
  1062. else:
  1063. break
  1064. filter_error(err)
  1065. raise
  1066. # XXX should we catch generic exceptions and look for their
  1067. # __cause__ or __context__?
  1068. finally:
  1069. socket.setdefaulttimeout(old_timeout)
  1070. @contextlib.contextmanager
  1071. def captured_output(stream_name):
  1072. """Return a context manager used by captured_stdout/stdin/stderr
  1073. that temporarily replaces the sys stream *stream_name* with a StringIO."""
  1074. import io
  1075. orig_stdout = getattr(sys, stream_name)
  1076. setattr(sys, stream_name, io.StringIO())
  1077. try:
  1078. yield getattr(sys, stream_name)
  1079. finally:
  1080. setattr(sys, stream_name, orig_stdout)
  1081. def captured_stdout():
  1082. """Capture the output of sys.stdout:
  1083. with captured_stdout() as s:
  1084. print("hello")
  1085. self.assertEqual(s.getvalue(), "hello")
  1086. """
  1087. return captured_output("stdout")
  1088. def captured_stderr():
  1089. return captured_output("stderr")
  1090. def captured_stdin():
  1091. return captured_output("stdin")
  1092. def gc_collect():
  1093. """Force as many objects as possible to be collected.
  1094. In non-CPython implementations of Python, this is needed because timely
  1095. deallocation is not guaranteed by the garbage collector. (Even in CPython
  1096. this can be the case in case of reference cycles.) This means that __del__
  1097. methods may be called later than expected and weakrefs may remain alive for
  1098. longer than expected. This function tries its best to force all garbage
  1099. objects to disappear.
  1100. """
  1101. gc.collect()
  1102. if is_jython:
  1103. time.sleep(0.1)
  1104. gc.collect()
  1105. gc.collect()
  1106. @contextlib.contextmanager
  1107. def disable_gc():
  1108. have_gc = gc.isenabled()
  1109. gc.disable()
  1110. try:
  1111. yield
  1112. finally:
  1113. if have_gc:
  1114. gc.enable()
  1115. def python_is_optimized():
  1116. """Find if Python was built with optimizations."""
  1117. # We don't have sysconfig on Py2.6:
  1118. import sysconfig
  1119. cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
  1120. final_opt = ""
  1121. for opt in cflags.split():
  1122. if opt.startswith('-O'):
  1123. final_opt = opt
  1124. return final_opt != '' and final_opt != '-O0'
  1125. _header = 'nP'
  1126. _align = '0n'
  1127. if hasattr(sys, "gettotalrefcount"):
  1128. _header = '2P' + _header
  1129. _align = '0P'
  1130. _vheader = _header + 'n'
  1131. def calcobjsize(fmt):
  1132. return struct.calcsize(_header + fmt + _align)
  1133. def calcvobjsize(fmt):
  1134. return struct.calcsize(_vheader + fmt + _align)
  1135. _TPFLAGS_HAVE_GC = 1<<14
  1136. _TPFLAGS_HEAPTYPE = 1<<9
  1137. def check_sizeof(test, o, size):
  1138. result = sys.getsizeof(o)
  1139. # add GC header size
  1140. if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
  1141. ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
  1142. size += _testcapi.SIZEOF_PYGC_HEAD
  1143. msg = 'wrong size for %s: got %d, expected %d' \
  1144. % (type(o), result, size)
  1145. test.assertEqual(result, size, msg)
  1146. #=======================================================================
  1147. # Decorator for running a function in a different locale, correctly resetting
  1148. # it afterwards.
  1149. def run_with_locale(catstr, *locales):
  1150. def decorator(func):
  1151. def inner(*args, **kwds):
  1152. try:
  1153. import locale
  1154. category = getattr(locale, catstr)
  1155. orig_locale = locale.setlocale(category)
  1156. except AttributeError:
  1157. # if the test author gives us an invalid category string
  1158. raise
  1159. except:
  1160. # cannot retrieve original locale, so do nothing
  1161. locale = orig_locale = None
  1162. else:
  1163. for loc in locales:
  1164. try:
  1165. locale.setlocale(category, loc)
  1166. break
  1167. except:
  1168. pass
  1169. # now run the function, resetting the locale on exceptions
  1170. try:
  1171. return func(*args, **kwds)
  1172. finally:
  1173. if locale and orig_locale:
  1174. locale.setlocale(category, orig_locale)
  1175. inner.__name__ = func.__name__
  1176. inner.__doc__ = func.__doc__
  1177. return inner
  1178. return decorator
  1179. #=======================================================================
  1180. # Decorator for running a function in a specific timezone, correctly
  1181. # resetting it afterwards.
  1182. def run_with_tz(tz):
  1183. def decorator(func):
  1184. def inner(*args, **kwds):
  1185. try:
  1186. tzset = time.tzset
  1187. except AttributeError:
  1188. raise unittest.SkipTest("tzset required")
  1189. if 'TZ' in os.environ:
  1190. orig_tz = os.environ['TZ']
  1191. else:
  1192. orig_tz = None
  1193. os.environ['TZ'] = tz
  1194. tzset()
  1195. # now run the function, resetting the tz on exceptions
  1196. try:
  1197. return func(*args, **kwds)
  1198. finally:
  1199. if orig_tz is None:
  1200. del os.environ['TZ']
  1201. else:
  1202. os.environ['TZ'] = orig_tz
  1203. time.tzset()
  1204. inner.__name__ = func.__name__
  1205. inner.__doc__ = func.__doc__
  1206. return inner
  1207. return decorator
  1208. #=======================================================================
  1209. # Big-memory-test support. Separate from 'resources' because memory use
  1210. # should be configurable.
  1211. # Some handy shorthands. Note that these are used for byte-limits as well
  1212. # as size-limits, in the various bigmem tests
  1213. _1M = 1024*1024
  1214. _1G = 1024 * _1M
  1215. _2G = 2 * _1G
  1216. _4G = 4 * _1G
  1217. MAX_Py_ssize_t = sys.maxsize
  1218. def set_memlimit(limit):
  1219. global max_memuse
  1220. global real_max_memuse
  1221. sizes = {
  1222. 'k': 1024,
  1223. 'm': _1M,
  1224. 'g': _1G,
  1225. 't': 1024*_1G,
  1226. }
  1227. m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
  1228. re.IGNORECASE | re.VERBOSE)
  1229. if m is None:
  1230. raise ValueError('Invalid memory limit %r' % (limit,))
  1231. memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
  1232. real_max_memuse = memlimit
  1233. if memlimit > MAX_Py_ssize_t:
  1234. memlimit = MAX_Py_ssize_t
  1235. if memlimit < _2G - 1:
  1236. raise ValueError('Memory limit %r too low to be useful' % (limit,))
  1237. max_memuse = memlimit
  1238. class _MemoryWatchdog(object):
  1239. """An object which periodically watches the process' memory consumption
  1240. and prints it out.
  1241. """
  1242. def __init__(self):
  1243. self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
  1244. self.started = False
  1245. def start(self):
  1246. try:
  1247. f = open(self.procfile, 'r')
  1248. except OSError as e:
  1249. warnings.warn('/proc not available for stats: {0}'.format(e),
  1250. RuntimeWarning)
  1251. sys.stderr.flush()
  1252. return
  1253. watchdog_script = findfile("memory_watchdog.py")
  1254. self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
  1255. stdin=f, stderr=subprocess.DEVNULL)
  1256. f.close()
  1257. self.started = True
  1258. def stop(self):
  1259. if self.started:
  1260. self.mem_watchdog.terminate()
  1261. self.mem_watchdog.wait()
  1262. def bigmemtest(size, memuse, dry_run=True):
  1263. """Decorator for bigmem tests.
  1264. 'minsize' is the minimum useful size for the test (in arbitrary,
  1265. test-interpreted units.) 'memuse' is the number of 'bytes per size' for
  1266. the test, or a good estimate of it.
  1267. if 'dry_run' is False, it means the test doesn't support dummy runs
  1268. when -M is not specified.
  1269. """
  1270. def decorator(f):
  1271. def wrapper(self):
  1272. size = wrapper.size
  1273. memuse = wrapper.memuse
  1274. if not real_max_memuse:
  1275. maxsize = 5147
  1276. else:
  1277. maxsize = size
  1278. if ((real_max_memuse or not dry_run)
  1279. and real_max_memuse < maxsize * memuse):
  1280. raise unittest.SkipTest(
  1281. "not enough memory: %.1fG minimum needed"
  1282. % (size * memuse / (1024 ** 3)))
  1283. if real_max_memuse and verbose:
  1284. print()
  1285. print(" ... expected peak memory use: {peak:.1f}G"
  1286. .format(peak=size * memuse / (1024 ** 3)))
  1287. watchdog = _MemoryWatchdog()
  1288. watchdog.start()
  1289. else:
  1290. watchdog = None
  1291. try:
  1292. return f(self, maxsize)
  1293. finally:
  1294. if watchdog:
  1295. watchdog.stop()
  1296. wrapper.size = size
  1297. wrapper.memuse = memuse
  1298. return wrapper
  1299. return decorator
  1300. def bigaddrspacetest(f):
  1301. """Decorator for tests that fill the address space."""
  1302. def wrapper(self):
  1303. if max_memuse < MAX_Py_ssize_t:
  1304. if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
  1305. raise unittest.SkipTest(
  1306. "not enough memory: try a 32-bit build instead")
  1307. else:
  1308. raise unittest.SkipTest(
  1309. "not enough memory: %.1fG minimum needed"
  1310. % (MAX_Py_ssize_t / (1024 ** 3)))
  1311. else:
  1312. return f(self)
  1313. return wrapper
  1314. #=======================================================================
  1315. # unittest integration.
  1316. class BasicTestRunner(object):
  1317. def run(self, test):
  1318. result = unittest.TestResult()
  1319. test(result)
  1320. return result
  1321. def _id(obj):
  1322. return obj
  1323. def requires_resource(resource):
  1324. if resource == 'gui' and not _is_gui_available():
  1325. return unittest.skip("resource 'gui' is not available")
  1326. if is_resource_enabled(resource):
  1327. return _id
  1328. else:
  1329. return unittest.skip("resource {0!r} is not enabled".format(resource))
  1330. def cpython_only(test):
  1331. """
  1332. Decorator for tests only applicable on CPython.
  1333. """
  1334. return impl_detail(cpython=True)(test)
  1335. def impl_detail(msg=None, **guards):
  1336. if check_impl_detail(**guards):
  1337. return _id
  1338. if msg is None:
  1339. guardnames, default = _parse_guards(guards)
  1340. if default:
  1341. msg = "implementation detail not available on {0}"
  1342. else:
  1343. msg = "implementation detail specific to {0}"
  1344. guardnames = sorted(guardnames.keys())
  1345. msg = msg.format(' or '.join(guardnames))
  1346. return unittest.skip(msg)
  1347. def _parse_guards(guards):
  1348. # Returns a tuple ({platform_name: run_me}, default_value)
  1349. if not guards:
  1350. return ({'cpython': True}, False)
  1351. is_true = list(guards.values())[0]
  1352. assert list(guards.values()) == [is_true] * len(guards) # all True or all False
  1353. return (guards, not is_true)
  1354. # Use the following check to guard CPython's implementation-specific tests --
  1355. # or to run them only on the implementation(s) guarded by the arguments.
  1356. def check_impl_detail(**guards):
  1357. """This function returns True or False depending on the host platform.
  1358. Examples:
  1359. if check_impl_detail(): # only on CPython (default)
  1360. if check_impl_detail(jython=True): # only on Jython
  1361. if check_impl_detail(cpython=False): # everywhere except on CPython
  1362. """
  1363. guards, default = _parse_guards(guards)
  1364. return guards.get(platform.python_implementation().lower(), default)
  1365. def no_tracing(func):
  1366. """Decorator to temporarily turn off tracing for the duration of a test."""
  1367. if not hasattr(sys, 'gettrace'):
  1368. return func
  1369. else:
  1370. @functools.wraps(func)
  1371. def wrapper(*args, **kwargs):
  1372. original_trace = sys.gettrace()
  1373. try:
  1374. sys.settrace(None)
  1375. return func(*args, **kwargs)
  1376. finally:
  1377. sys.settrace(original_trace)
  1378. return wrapper
  1379. def refcount_test(test):
  1380. """Decorator for tests which involve reference counting.
  1381. To start, the decorator does not run the test if is not run by CPython.
  1382. After that, any trace function is unset during the test to prevent
  1383. unexpected refcounts caused by the trace function.
  1384. """
  1385. return no_tracing(cpython_only(test))
  1386. def _filter_suite(suite, pred):
  1387. """Recursively filter test cases in a suite based on a predicate."""
  1388. newtests = []
  1389. for test in suite._tests:
  1390. if isinstance(test, unittest.TestSuite):
  1391. _filter_suite(test, pred)
  1392. newtests.append(test)
  1393. else:
  1394. if pred(test):
  1395. newtests.append(test)
  1396. suite._tests = newtests
  1397. def _run_suite(suite):
  1398. """Run tests from a unittest.TestSuite-derived class."""
  1399. if verbose:
  1400. runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
  1401. failfast=failfast)
  1402. else:
  1403. runner = BasicTestRunner()
  1404. result = runner.run(suite)
  1405. if not result.wasSuccessful():
  1406. if len(result.errors) == 1 and not result.failures:
  1407. err = result.errors[0][1]
  1408. elif len(result.failures) == 1 and not result.errors:
  1409. err = result.failures[0][1]
  1410. else:
  1411. err = "multiple errors occurred"
  1412. if not verbose: err += "; run in verbose mode for details"
  1413. raise TestFailed(err)
  1414. def run_unittest(*classes):
  1415. """Run tests from unittest.TestCase-derived classes."""
  1416. valid_types = (unittest.TestSuite, unittest.TestCase)
  1417. suite = unittest.TestSuite()
  1418. for cls in classes:
  1419. if isinstance(cls, str):
  1420. if cls in sys.modules:
  1421. suite.addTest(unittest.findTestCases(sys.modules[cls]))
  1422. else:
  1423. raise ValueError("str arguments must be keys in sys.modules")
  1424. elif isinstance(cls, valid_types):
  1425. suite.addTest(cls)
  1426. else:
  1427. suite.addTest(unittest.makeSuite(cls))
  1428. def case_pred(test):
  1429. if match_tests is None:
  1430. return True
  1431. for name in test.id().split("."):
  1432. if fnmatch.fnmatchcase(name, match_tests):
  1433. return True
  1434. return False
  1435. _filter_suite(suite, case_pred)
  1436. _run_suite(suite)
  1437. # We don't have sysconfig on Py2.6:
  1438. # #=======================================================================
  1439. # # Check for the presence of docstrings.
  1440. #
  1441. # HAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or
  1442. # sys.platform == 'win32' or
  1443. # sysconfig.get_config_var('WITH_DOC_STRINGS'))
  1444. #
  1445. # requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
  1446. # "test requires docstrings")
  1447. #
  1448. #
  1449. # #=======================================================================
  1450. # doctest driver.
  1451. def run_doctest(module, verbosity=None, optionflags=0):
  1452. """Run doctest on the given module. Return (#failures, #tests).
  1453. If optional argument verbosity is not specified (or is None), pass
  1454. support's belief about verbosity on to doctest. Else doctest's
  1455. usual behavior is used (it searches sys.argv for -v).
  1456. """
  1457. import doctest
  1458. if verbosity is None:
  1459. verbosity = verbose
  1460. else:
  1461. verbosity = None
  1462. f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags)
  1463. if f:
  1464. raise TestFailed("%d of %d doctests failed" % (f, t))
  1465. if verbose:
  1466. print('doctest (%s) ... %d tests with zero failures' %
  1467. (module.__name__, t))
  1468. return f, t
  1469. #=======================================================================
  1470. # Support for saving and restoring the imported modules.
  1471. def modules_setup():
  1472. return sys.modules.copy(),
  1473. def modules_cleanup(oldmodules):
  1474. # Encoders/decoders are registered permanently within the internal
  1475. # codec cache. If we destroy the corresponding modules their
  1476. # globals will be set to None which will trip up the cached functions.
  1477. encodings = [(k, v) for k, v in sys.modules.items()
  1478. if k.startswith('encodings.')]
  1479. # Was:
  1480. # sys.modules.clear()
  1481. # Py2-compatible:
  1482. for i in range(len(sys.modules)):
  1483. sys.modules.pop()
  1484. sys.modules.update(encodings)
  1485. # XXX: This kind of problem can affect more than just encodings. In particular
  1486. # extension modules (such as _ssl) don't cope with reloading properly.
  1487. # Really, test modules should be cleaning out the test specific modules they
  1488. # know they added (ala test_runpy) rather than relying on this function (as
  1489. # test_importhooks and test_pkg do currently).
  1490. # Implicitly imported *real* modules should be left alone (see issue 10556).
  1491. sys.modules.update(oldmodules)
  1492. #=======================================================================
  1493. # Backported versions of threading_setup() and threading_cleanup() which don't refer
  1494. # to threading._dangling (not available on Py2.7).
  1495. # Threading support to prevent reporting refleaks when running regrtest.py -R
  1496. # NOTE: we use thread._count() rather than threading.enumerate() (or the
  1497. # moral equivalent thereof) because a threading.Thread object is still alive
  1498. # until its __bootstrap() method has returned, even after it has been
  1499. # unregistered from the threading module.
  1500. # thread._count(), on the other hand, only gets decremented *after* the
  1501. # __bootstrap() method has returned, which gives us reliable reference counts
  1502. # at the end of a test run.
  1503. def threading_setup():
  1504. if _thread:
  1505. return _thread._count(),
  1506. else:
  1507. return 1,
  1508. def threading_cleanup(nb_threads):
  1509. if not _thread:
  1510. return
  1511. _MAX_COUNT = 10
  1512. for count in range(_MAX_COUNT):
  1513. n = _thread._count()
  1514. if n == nb_threads:
  1515. break
  1516. time.sleep(0.1)
  1517. # XXX print a warning in case of failure?
  1518. def reap_threads(func):
  1519. """Use this function when threads are being used. This will
  1520. ensure that the threads are cleaned up even when the test fails.
  1521. If threading is unavailable this function does nothing.
  1522. """
  1523. if not _thread:
  1524. return func
  1525. @functools.wraps(func)
  1526. def decorator(*args):
  1527. key = threading_setup()
  1528. try:
  1529. return func(*args)
  1530. finally:
  1531. threading_cleanup(*key)
  1532. return decorator
  1533. def reap_children():
  1534. """Use this function at the end of test_main() whenever sub-processes
  1535. are started. This will help ensure that no extra children (zombies)
  1536. stick around to hog resources and create problems when looking
  1537. for refleaks.
  1538. """
  1539. # Reap all our dead child processes so we don't leave zombies around.
  1540. # These hog resources and might be causing some of the buildbots to die.
  1541. if hasattr(os, 'waitpid'):
  1542. any_process = -1
  1543. while True:
  1544. try:
  1545. # This will raise an exception on Windows. That's ok.
  1546. pid, status = os.waitpid(any_process, os.WNOHANG)
  1547. if pid == 0:
  1548. break
  1549. except:
  1550. break
  1551. @contextlib.contextmanager
  1552. def swap_attr(obj, attr, new_val):
  1553. """Temporary swap out an attribute with a new object.
  1554. Usage:
  1555. with swap_attr(obj, "attr", 5):
  1556. ...
  1557. This will set obj.attr to 5 for the duration of the with: block,
  1558. restoring the old value at the end of the block. If `attr` doesn't
  1559. exist on `obj`, it will be created and then deleted at the end of the
  1560. block.
  1561. """
  1562. if hasattr(obj, attr):
  1563. real_val = getattr(obj, attr)
  1564. setattr(obj, attr, new_val)
  1565. try:
  1566. yield
  1567. finally:
  1568. setattr(obj, attr, real_val)
  1569. else:
  1570. setattr(obj, attr, new_val)
  1571. try:
  1572. yield
  1573. finally:
  1574. delattr(obj, attr)
  1575. @contextlib.contextmanager
  1576. def swap_item(obj, item, new_val):
  1577. """Temporary swap out an item with a new object.
  1578. Usage:
  1579. with swap_item(obj, "item", 5):
  1580. ...
  1581. This will set obj["item"] to 5 for the duration of the with: block,
  1582. restoring the old value at the end of the block. If `item` doesn't
  1583. exist on `obj`, it will be created and then deleted at the end of the
  1584. block.
  1585. """
  1586. if item in obj:
  1587. real_val = obj[item]
  1588. obj[item] = new_val
  1589. try:
  1590. yield
  1591. finally:
  1592. obj[item] = real_val
  1593. else:
  1594. obj[item] = new_val
  1595. try:
  1596. yield
  1597. finally:
  1598. del obj[item]
  1599. def strip_python_stderr(stderr):
  1600. """Strip the stderr of a Python process from potential debug output
  1601. emitted by the interpreter.
  1602. This will typically be run on the result of the communicate() method
  1603. of a subprocess.Popen object.
  1604. """
  1605. stderr = re.sub(br"\[\d+ refs\]\r?\n?", b"", stderr).strip()
  1606. return stderr
  1607. def args_from_interpreter_flags():
  1608. """Return a list of command-line arguments reproducing the current
  1609. settings in sys.flags and sys.warnoptions."""
  1610. return subprocess._args_from_interpreter_flags()
  1611. #============================================================
  1612. # Support for assertions about logging.
  1613. #============================================================
  1614. class TestHandler(logging.handlers.BufferingHandler):
  1615. def __init__(self, matcher):
  1616. # BufferingHandler takes a "capacity" argument
  1617. # so as to know when to flush. As we're overriding
  1618. # shouldFlush anyway, we can set a capacity of zero.
  1619. # You can call flush() manually to clear out the
  1620. # buffer.
  1621. logging.handlers.BufferingHandler.__init__(self, 0)
  1622. self.matcher = matcher
  1623. def shouldFlush(self):
  1624. return False
  1625. def emit(self, record):
  1626. self.format(record)
  1627. self.buffer.append(record.__dict__)
  1628. def matches(self, **kwargs):
  1629. """
  1630. Look for a saved dict whose keys/values match the supplied arguments.
  1631. """
  1632. result = False
  1633. for d in self.buffer:
  1634. if self.matcher.matches(d, **kwargs):
  1635. result = True
  1636. break
  1637. return result
  1638. class Matcher(object):
  1639. _partial_matches = ('msg', 'message')
  1640. def matches(self, d, **kwargs):
  1641. """
  1642. Try to match a single dict with the supplied arguments.
  1643. Keys whose values are strings and which are in self._partial_matches
  1644. will be checked for partial (i.e. substring) matches. You can extend
  1645. this scheme to (for example) do regular expression matching, etc.
  1646. """
  1647. result = True
  1648. for k in kwargs:
  1649. v = kwargs[k]
  1650. dv = d.get(k)
  1651. if not self.match_value(k, dv, v):
  1652. result = False
  1653. break
  1654. return result
  1655. def match_value(self, k, dv, v):
  1656. """
  1657. Try to match a single stored value (dv) with a supplied value (v).
  1658. """
  1659. if type(v) != type(dv):
  1660. result = False
  1661. elif type(dv) is not str or k not in self._partial_matches:
  1662. result = (v == dv)
  1663. else:
  1664. result = dv.find(v) >= 0
  1665. return result
  1666. _can_symlink = None
  1667. def can_symlink():
  1668. global _can_symlink
  1669. if _can_symlink is not None:
  1670. return _can_symlink
  1671. symlink_path = TESTFN + "can_symlink"
  1672. try:
  1673. os.symlink(TESTFN, symlink_path)
  1674. can = True
  1675. except (OSError, NotImplementedError, AttributeError):
  1676. can = False
  1677. else:
  1678. os.remove(symlink_path)
  1679. _can_symlink = can
  1680. return can
  1681. def skip_unless_symlink(test):
  1682. """Skip decorator for tests that require functional symlink"""
  1683. ok = can_symlink()
  1684. msg = "Requires functional symlink implementation"
  1685. return test if ok else unittest.skip(msg)(test)
  1686. _can_xattr = None
  1687. def can_xattr():
  1688. global _can_xattr
  1689. if _can_xattr is not None:
  1690. return _can_xattr
  1691. if not hasattr(os, "setxattr"):
  1692. can = False
  1693. else:
  1694. tmp_fp, tmp_name = tempfile.mkstemp()
  1695. try:
  1696. with open(TESTFN, "wb") as fp:
  1697. try:
  1698. # TESTFN & tempfile may use different file systems with
  1699. # different capabilities
  1700. os.setxattr(tmp_fp, b"user.test", b"")
  1701. os.setxattr(fp.fileno(), b"user.test", b"")
  1702. # Kernels < 2.6.39 don't respect setxattr flags.
  1703. kernel_version = platform.release()
  1704. m = re.match("2.6.(\d{1,2})", kernel_version)
  1705. can = m is None or int(m.group(1)) >= 39
  1706. except OSError:
  1707. can = False
  1708. finally:
  1709. unlink(TESTFN)
  1710. unlink(tmp_name)
  1711. _can_xattr = can
  1712. return can
  1713. def skip_unless_xattr(test):
  1714. """Skip decorator for tests that require functional extended attributes"""
  1715. ok = can_xattr()
  1716. msg = "no non-broken extended attribute support"
  1717. return test if ok else unittest.skip(msg)(test)
  1718. if sys.platform.startswith('win'):
  1719. @contextlib.contextmanager
  1720. def suppress_crash_popup():
  1721. """Disable Windows Error Reporting dialogs using SetErrorMode."""
  1722. # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621%28v=vs.85%29.aspx
  1723. # GetErrorMode is not available on Windows XP and Windows Server 2003,
  1724. # but SetErrorMode returns the previous value, so we can use that
  1725. import ctypes
  1726. k32 = ctypes.windll.kernel32
  1727. SEM_NOGPFAULTERRORBOX = 0x02
  1728. old_error_mode = k32.SetErrorMode(SEM_NOGPFAULTERRORBOX)
  1729. k32.SetErrorMode(old_error_mode | SEM_NOGPFAULTERRORBOX)
  1730. try:
  1731. yield
  1732. finally:
  1733. k32.SetErrorMode(old_error_mode)
  1734. else:
  1735. # this is a no-op for other platforms
  1736. @contextlib.contextmanager
  1737. def suppress_crash_popup():
  1738. yield
  1739. def patch(test_instance, object_to_patch, attr_name, new_value):
  1740. """Override 'object_to_patch'.'attr_name' with 'new_value'.
  1741. Also, add a cleanup procedure to 'test_instance' to restore
  1742. 'object_to_patch' value for 'attr_name'.
  1743. The 'attr_name' should be a valid attribute for 'object_to_patch'.
  1744. """
  1745. # check that 'attr_name' is a real attribute for 'object_to_patch'
  1746. # will raise AttributeError if it does not exist
  1747. getattr(object_to_patch, attr_name)
  1748. # keep a copy of the old value
  1749. attr_is_local = False
  1750. try:
  1751. old_value = object_to_patch.__dict__[attr_name]
  1752. except (AttributeError, KeyError):
  1753. old_value = getattr(object_to_patch, attr_name, None)
  1754. else:
  1755. attr_is_local = True
  1756. # restore the value when the test is done
  1757. def cleanup():
  1758. if attr_is_local:
  1759. setattr(object_to_patch, attr_name, old_value)
  1760. else:
  1761. delattr(object_to_patch, attr_name)
  1762. test_instance.addCleanup(cleanup)
  1763. # actually override the attribute
  1764. setattr(object_to_patch, attr_name, new_value)