__init__.py 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  1. """Supporting definitions for the Python regression tests."""
  2. if __name__ != 'test.support':
  3. raise ImportError('support must be imported from the test package')
  4. import collections.abc
  5. import contextlib
  6. import datetime
  7. import errno
  8. import faulthandler
  9. import fnmatch
  10. import functools
  11. import gc
  12. import importlib
  13. import importlib.util
  14. import io
  15. import logging.handlers
  16. import nntplib
  17. import os
  18. import platform
  19. import re
  20. import shutil
  21. import socket
  22. import stat
  23. import struct
  24. import subprocess
  25. import sys
  26. import sysconfig
  27. import tempfile
  28. import _thread
  29. import threading
  30. import time
  31. import types
  32. import unittest
  33. import urllib.error
  34. import warnings
  35. from .testresult import get_test_runner
  36. try:
  37. import multiprocessing.process
  38. except ImportError:
  39. multiprocessing = None
  40. try:
  41. import zlib
  42. except ImportError:
  43. zlib = None
  44. try:
  45. import gzip
  46. except ImportError:
  47. gzip = None
  48. try:
  49. import bz2
  50. except ImportError:
  51. bz2 = None
  52. try:
  53. import lzma
  54. except ImportError:
  55. lzma = None
  56. try:
  57. import resource
  58. except ImportError:
  59. resource = None
  60. __all__ = [
  61. # globals
  62. "PIPE_MAX_SIZE", "verbose", "max_memuse", "use_resources", "failfast",
  63. # exceptions
  64. "Error", "TestFailed", "TestDidNotRun", "ResourceDenied",
  65. # imports
  66. "import_module", "import_fresh_module", "CleanImport",
  67. # modules
  68. "unload", "forget",
  69. # io
  70. "record_original_stdout", "get_original_stdout", "captured_stdout",
  71. "captured_stdin", "captured_stderr",
  72. # filesystem
  73. "TESTFN", "SAVEDCWD", "unlink", "rmtree", "temp_cwd", "findfile",
  74. "create_empty_file", "can_symlink", "fs_is_case_insensitive",
  75. # unittest
  76. "is_resource_enabled", "requires", "requires_freebsd_version",
  77. "requires_linux_version", "requires_mac_ver", "check_syntax_error",
  78. "TransientResource", "time_out", "socket_peer_reset", "ioerror_peer_reset",
  79. "transient_internet", "BasicTestRunner", "run_unittest", "run_doctest",
  80. "skip_unless_symlink", "requires_gzip", "requires_bz2", "requires_lzma",
  81. "bigmemtest", "bigaddrspacetest", "cpython_only", "get_attribute",
  82. "requires_IEEE_754", "skip_unless_xattr", "requires_zlib",
  83. "anticipate_failure", "load_package_tests", "detect_api_mismatch",
  84. "check__all__", "skip_unless_bind_unix_socket",
  85. # sys
  86. "is_jython", "is_android", "check_impl_detail", "unix_shell",
  87. "setswitchinterval",
  88. # network
  89. "HOST", "IPV6_ENABLED", "find_unused_port", "bind_port", "open_urlresource",
  90. "bind_unix_socket",
  91. # processes
  92. 'temp_umask', "reap_children",
  93. # logging
  94. "TestHandler",
  95. # threads
  96. "threading_setup", "threading_cleanup", "reap_threads", "start_threads",
  97. # miscellaneous
  98. "check_warnings", "check_no_resource_warning", "EnvironmentVarGuard",
  99. "run_with_locale", "swap_item",
  100. "swap_attr", "Matcher", "set_memlimit", "SuppressCrashReport", "sortdict",
  101. "run_with_tz", "PGO", "missing_compiler_executable", "fd_count",
  102. "ALWAYS_EQ", "LARGEST", "SMALLEST"
  103. ]
  104. class Error(Exception):
  105. """Base class for regression test exceptions."""
  106. class TestFailed(Error):
  107. """Test failed."""
  108. class TestDidNotRun(Error):
  109. """Test did not run any subtests."""
  110. class ResourceDenied(unittest.SkipTest):
  111. """Test skipped because it requested a disallowed resource.
  112. This is raised when a test calls requires() for a resource that
  113. has not be enabled. It is used to distinguish between expected
  114. and unexpected skips.
  115. """
  116. @contextlib.contextmanager
  117. def _ignore_deprecated_imports(ignore=True):
  118. """Context manager to suppress package and module deprecation
  119. warnings when importing them.
  120. If ignore is False, this context manager has no effect.
  121. """
  122. if ignore:
  123. with warnings.catch_warnings():
  124. warnings.filterwarnings("ignore", ".+ (module|package)",
  125. DeprecationWarning)
  126. yield
  127. else:
  128. yield
  129. def import_module(name, deprecated=False, *, required_on=()):
  130. """Import and return the module to be tested, raising SkipTest if
  131. it is not available.
  132. If deprecated is True, any module or package deprecation messages
  133. will be suppressed. If a module is required on a platform but optional for
  134. others, set required_on to an iterable of platform prefixes which will be
  135. compared against sys.platform.
  136. """
  137. with _ignore_deprecated_imports(deprecated):
  138. try:
  139. return importlib.import_module(name)
  140. except ImportError as msg:
  141. if sys.platform.startswith(tuple(required_on)):
  142. raise
  143. raise unittest.SkipTest(str(msg))
  144. def _save_and_remove_module(name, orig_modules):
  145. """Helper function to save and remove a module from sys.modules
  146. Raise ImportError if the module can't be imported.
  147. """
  148. # try to import the module and raise an error if it can't be imported
  149. if name not in sys.modules:
  150. __import__(name)
  151. del sys.modules[name]
  152. for modname in list(sys.modules):
  153. if modname == name or modname.startswith(name + '.'):
  154. orig_modules[modname] = sys.modules[modname]
  155. del sys.modules[modname]
  156. def _save_and_block_module(name, orig_modules):
  157. """Helper function to save and block a module in sys.modules
  158. Return True if the module was in sys.modules, False otherwise.
  159. """
  160. saved = True
  161. try:
  162. orig_modules[name] = sys.modules[name]
  163. except KeyError:
  164. saved = False
  165. sys.modules[name] = None
  166. return saved
  167. def anticipate_failure(condition):
  168. """Decorator to mark a test that is known to be broken in some cases
  169. Any use of this decorator should have a comment identifying the
  170. associated tracker issue.
  171. """
  172. if condition:
  173. return unittest.expectedFailure
  174. return lambda f: f
  175. def load_package_tests(pkg_dir, loader, standard_tests, pattern):
  176. """Generic load_tests implementation for simple test packages.
  177. Most packages can implement load_tests using this function as follows:
  178. def load_tests(*args):
  179. return load_package_tests(os.path.dirname(__file__), *args)
  180. """
  181. if pattern is None:
  182. pattern = "test*"
  183. top_dir = os.path.dirname( # Lib
  184. os.path.dirname( # test
  185. os.path.dirname(__file__))) # support
  186. package_tests = loader.discover(start_dir=pkg_dir,
  187. top_level_dir=top_dir,
  188. pattern=pattern)
  189. standard_tests.addTests(package_tests)
  190. return standard_tests
  191. def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
  192. """Import and return a module, deliberately bypassing sys.modules.
  193. This function imports and returns a fresh copy of the named Python module
  194. by removing the named module from sys.modules before doing the import.
  195. Note that unlike reload, the original module is not affected by
  196. this operation.
  197. *fresh* is an iterable of additional module names that are also removed
  198. from the sys.modules cache before doing the import.
  199. *blocked* is an iterable of module names that are replaced with None
  200. in the module cache during the import to ensure that attempts to import
  201. them raise ImportError.
  202. The named module and any modules named in the *fresh* and *blocked*
  203. parameters are saved before starting the import and then reinserted into
  204. sys.modules when the fresh import is complete.
  205. Module and package deprecation messages are suppressed during this import
  206. if *deprecated* is True.
  207. This function will raise ImportError if the named module cannot be
  208. imported.
  209. """
  210. # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
  211. # to make sure that this utility function is working as expected
  212. with _ignore_deprecated_imports(deprecated):
  213. # Keep track of modules saved for later restoration as well
  214. # as those which just need a blocking entry removed
  215. orig_modules = {}
  216. names_to_remove = []
  217. _save_and_remove_module(name, orig_modules)
  218. try:
  219. for fresh_name in fresh:
  220. _save_and_remove_module(fresh_name, orig_modules)
  221. for blocked_name in blocked:
  222. if not _save_and_block_module(blocked_name, orig_modules):
  223. names_to_remove.append(blocked_name)
  224. fresh_module = importlib.import_module(name)
  225. except ImportError:
  226. fresh_module = None
  227. finally:
  228. for orig_name, module in orig_modules.items():
  229. sys.modules[orig_name] = module
  230. for name_to_remove in names_to_remove:
  231. del sys.modules[name_to_remove]
  232. return fresh_module
  233. def get_attribute(obj, name):
  234. """Get an attribute, raising SkipTest if AttributeError is raised."""
  235. try:
  236. attribute = getattr(obj, name)
  237. except AttributeError:
  238. raise unittest.SkipTest("object %r has no attribute %r" % (obj, name))
  239. else:
  240. return attribute
  241. verbose = 1 # Flag set to 0 by regrtest.py
  242. use_resources = None # Flag set to [] by regrtest.py
  243. max_memuse = 0 # Disable bigmem tests (they will still be run with
  244. # small sizes, to make sure they work.)
  245. real_max_memuse = 0
  246. junit_xml_list = None # list of testsuite XML elements
  247. failfast = False
  248. # _original_stdout is meant to hold stdout at the time regrtest began.
  249. # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
  250. # The point is to have some flavor of stdout the user can actually see.
  251. _original_stdout = None
  252. def record_original_stdout(stdout):
  253. global _original_stdout
  254. _original_stdout = stdout
  255. def get_original_stdout():
  256. return _original_stdout or sys.stdout
  257. def unload(name):
  258. try:
  259. del sys.modules[name]
  260. except KeyError:
  261. pass
  262. def _force_run(path, func, *args):
  263. try:
  264. return func(*args)
  265. except OSError as err:
  266. if verbose >= 2:
  267. print('%s: %s' % (err.__class__.__name__, err))
  268. print('re-run %s%r' % (func.__name__, args))
  269. os.chmod(path, stat.S_IRWXU)
  270. return func(*args)
  271. if sys.platform.startswith("win"):
  272. def _waitfor(func, pathname, waitall=False):
  273. # Perform the operation
  274. func(pathname)
  275. # Now setup the wait loop
  276. if waitall:
  277. dirname = pathname
  278. else:
  279. dirname, name = os.path.split(pathname)
  280. dirname = dirname or '.'
  281. # Check for `pathname` to be removed from the filesystem.
  282. # The exponential backoff of the timeout amounts to a total
  283. # of ~1 second after which the deletion is probably an error
  284. # anyway.
  285. # Testing on an i7@4.3GHz shows that usually only 1 iteration is
  286. # required when contention occurs.
  287. timeout = 0.001
  288. while timeout < 1.0:
  289. # Note we are only testing for the existence of the file(s) in
  290. # the contents of the directory regardless of any security or
  291. # access rights. If we have made it this far, we have sufficient
  292. # permissions to do that much using Python's equivalent of the
  293. # Windows API FindFirstFile.
  294. # Other Windows APIs can fail or give incorrect results when
  295. # dealing with files that are pending deletion.
  296. L = os.listdir(dirname)
  297. if not (L if waitall else name in L):
  298. return
  299. # Increase the timeout and try again
  300. time.sleep(timeout)
  301. timeout *= 2
  302. warnings.warn('tests may fail, delete still pending for ' + pathname,
  303. RuntimeWarning, stacklevel=4)
  304. def _unlink(filename):
  305. _waitfor(os.unlink, filename)
  306. def _rmdir(dirname):
  307. _waitfor(os.rmdir, dirname)
  308. def _rmtree(path):
  309. def _rmtree_inner(path):
  310. for name in _force_run(path, os.listdir, path):
  311. fullname = os.path.join(path, name)
  312. try:
  313. mode = os.lstat(fullname).st_mode
  314. except OSError as exc:
  315. print("support.rmtree(): os.lstat(%r) failed with %s" % (fullname, exc),
  316. file=sys.__stderr__)
  317. mode = 0
  318. if stat.S_ISDIR(mode):
  319. _waitfor(_rmtree_inner, fullname, waitall=True)
  320. _force_run(fullname, os.rmdir, fullname)
  321. else:
  322. _force_run(fullname, os.unlink, fullname)
  323. _waitfor(_rmtree_inner, path, waitall=True)
  324. _waitfor(lambda p: _force_run(p, os.rmdir, p), path)
  325. def _longpath(path):
  326. try:
  327. import ctypes
  328. except ImportError:
  329. # No ctypes means we can't expands paths.
  330. pass
  331. else:
  332. buffer = ctypes.create_unicode_buffer(len(path) * 2)
  333. length = ctypes.windll.kernel32.GetLongPathNameW(path, buffer,
  334. len(buffer))
  335. if length:
  336. return buffer[:length]
  337. return path
  338. else:
  339. _unlink = os.unlink
  340. _rmdir = os.rmdir
  341. def _rmtree(path):
  342. try:
  343. shutil.rmtree(path)
  344. return
  345. except OSError:
  346. pass
  347. def _rmtree_inner(path):
  348. for name in _force_run(path, os.listdir, path):
  349. fullname = os.path.join(path, name)
  350. try:
  351. mode = os.lstat(fullname).st_mode
  352. except OSError:
  353. mode = 0
  354. if stat.S_ISDIR(mode):
  355. _rmtree_inner(fullname)
  356. _force_run(path, os.rmdir, fullname)
  357. else:
  358. _force_run(path, os.unlink, fullname)
  359. _rmtree_inner(path)
  360. os.rmdir(path)
  361. def _longpath(path):
  362. return path
  363. def unlink(filename):
  364. try:
  365. _unlink(filename)
  366. except (FileNotFoundError, NotADirectoryError):
  367. pass
  368. def rmdir(dirname):
  369. try:
  370. _rmdir(dirname)
  371. except FileNotFoundError:
  372. pass
  373. def rmtree(path):
  374. try:
  375. _rmtree(path)
  376. except FileNotFoundError:
  377. pass
  378. def make_legacy_pyc(source):
  379. """Move a PEP 3147/488 pyc file to its legacy pyc location.
  380. :param source: The file system path to the source file. The source file
  381. does not need to exist, however the PEP 3147/488 pyc file must exist.
  382. :return: The file system path to the legacy pyc file.
  383. """
  384. pyc_file = importlib.util.cache_from_source(source)
  385. up_one = os.path.dirname(os.path.abspath(source))
  386. legacy_pyc = os.path.join(up_one, source + 'c')
  387. os.rename(pyc_file, legacy_pyc)
  388. return legacy_pyc
  389. def forget(modname):
  390. """'Forget' a module was ever imported.
  391. This removes the module from sys.modules and deletes any PEP 3147/488 or
  392. legacy .pyc files.
  393. """
  394. unload(modname)
  395. for dirname in sys.path:
  396. source = os.path.join(dirname, modname + '.py')
  397. # It doesn't matter if they exist or not, unlink all possible
  398. # combinations of PEP 3147/488 and legacy pyc files.
  399. unlink(source + 'c')
  400. for opt in ('', 1, 2):
  401. unlink(importlib.util.cache_from_source(source, optimization=opt))
  402. # Check whether a gui is actually available
  403. def _is_gui_available():
  404. if hasattr(_is_gui_available, 'result'):
  405. return _is_gui_available.result
  406. reason = None
  407. if sys.platform.startswith('win'):
  408. # if Python is running as a service (such as the buildbot service),
  409. # gui interaction may be disallowed
  410. import ctypes
  411. import ctypes.wintypes
  412. UOI_FLAGS = 1
  413. WSF_VISIBLE = 0x0001
  414. class USEROBJECTFLAGS(ctypes.Structure):
  415. _fields_ = [("fInherit", ctypes.wintypes.BOOL),
  416. ("fReserved", ctypes.wintypes.BOOL),
  417. ("dwFlags", ctypes.wintypes.DWORD)]
  418. dll = ctypes.windll.user32
  419. h = dll.GetProcessWindowStation()
  420. if not h:
  421. raise ctypes.WinError()
  422. uof = USEROBJECTFLAGS()
  423. needed = ctypes.wintypes.DWORD()
  424. res = dll.GetUserObjectInformationW(h,
  425. UOI_FLAGS,
  426. ctypes.byref(uof),
  427. ctypes.sizeof(uof),
  428. ctypes.byref(needed))
  429. if not res:
  430. raise ctypes.WinError()
  431. if not bool(uof.dwFlags & WSF_VISIBLE):
  432. reason = "gui not available (WSF_VISIBLE flag not set)"
  433. elif sys.platform == 'darwin':
  434. # The Aqua Tk implementations on OS X can abort the process if
  435. # being called in an environment where a window server connection
  436. # cannot be made, for instance when invoked by a buildbot or ssh
  437. # process not running under the same user id as the current console
  438. # user. To avoid that, raise an exception if the window manager
  439. # connection is not available.
  440. from ctypes import cdll, c_int, pointer, Structure
  441. from ctypes.util import find_library
  442. app_services = cdll.LoadLibrary(find_library("ApplicationServices"))
  443. if app_services.CGMainDisplayID() == 0:
  444. reason = "gui tests cannot run without OS X window manager"
  445. else:
  446. class ProcessSerialNumber(Structure):
  447. _fields_ = [("highLongOfPSN", c_int),
  448. ("lowLongOfPSN", c_int)]
  449. psn = ProcessSerialNumber()
  450. psn_p = pointer(psn)
  451. if ( (app_services.GetCurrentProcess(psn_p) < 0) or
  452. (app_services.SetFrontProcess(psn_p) < 0) ):
  453. reason = "cannot run without OS X gui process"
  454. # check on every platform whether tkinter can actually do anything
  455. if not reason:
  456. try:
  457. from tkinter import Tk
  458. root = Tk()
  459. root.withdraw()
  460. root.update()
  461. root.destroy()
  462. except Exception as e:
  463. err_string = str(e)
  464. if len(err_string) > 50:
  465. err_string = err_string[:50] + ' [...]'
  466. reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__,
  467. err_string)
  468. _is_gui_available.reason = reason
  469. _is_gui_available.result = not reason
  470. return _is_gui_available.result
  471. def is_resource_enabled(resource):
  472. """Test whether a resource is enabled.
  473. Known resources are set by regrtest.py. If not running under regrtest.py,
  474. all resources are assumed enabled unless use_resources has been set.
  475. """
  476. return use_resources is None or resource in use_resources
  477. def requires(resource, msg=None):
  478. """Raise ResourceDenied if the specified resource is not available."""
  479. if not is_resource_enabled(resource):
  480. if msg is None:
  481. msg = "Use of the %r resource not enabled" % resource
  482. raise ResourceDenied(msg)
  483. if resource == 'gui' and not _is_gui_available():
  484. raise ResourceDenied(_is_gui_available.reason)
  485. def _requires_unix_version(sysname, min_version):
  486. """Decorator raising SkipTest if the OS is `sysname` and the version is less
  487. than `min_version`.
  488. For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
  489. the FreeBSD version is less than 7.2.
  490. """
  491. import platform
  492. min_version_txt = '.'.join(map(str, min_version))
  493. version_txt = platform.release().split('-', 1)[0]
  494. if platform.system() == sysname:
  495. try:
  496. version = tuple(map(int, version_txt.split('.')))
  497. except ValueError:
  498. skip = False
  499. else:
  500. skip = version < min_version
  501. else:
  502. skip = False
  503. return unittest.skipIf(
  504. skip,
  505. f"{sysname} version {min_version_txt} or higher required, not "
  506. f"{version_txt}"
  507. )
  508. def requires_freebsd_version(*min_version):
  509. """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
  510. less than `min_version`.
  511. For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
  512. version is less than 7.2.
  513. """
  514. return _requires_unix_version('FreeBSD', min_version)
  515. def requires_linux_version(*min_version):
  516. """Decorator raising SkipTest if the OS is Linux and the Linux version is
  517. less than `min_version`.
  518. For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
  519. version is less than 2.6.32.
  520. """
  521. return _requires_unix_version('Linux', min_version)
  522. def requires_mac_ver(*min_version):
  523. """Decorator raising SkipTest if the OS is Mac OS X and the OS X
  524. version if less than min_version.
  525. For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
  526. is lesser than 10.5.
  527. """
  528. def decorator(func):
  529. @functools.wraps(func)
  530. def wrapper(*args, **kw):
  531. if sys.platform == 'darwin':
  532. version_txt = platform.mac_ver()[0]
  533. try:
  534. version = tuple(map(int, version_txt.split('.')))
  535. except ValueError:
  536. pass
  537. else:
  538. if version < min_version:
  539. min_version_txt = '.'.join(map(str, min_version))
  540. raise unittest.SkipTest(
  541. "Mac OS X %s or higher required, not %s"
  542. % (min_version_txt, version_txt))
  543. return func(*args, **kw)
  544. wrapper.min_version = min_version
  545. return wrapper
  546. return decorator
  547. HOST = "localhost"
  548. HOSTv4 = "127.0.0.1"
  549. HOSTv6 = "::1"
  550. def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
  551. """Returns an unused port that should be suitable for binding. This is
  552. achieved by creating a temporary socket with the same family and type as
  553. the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
  554. the specified host address (defaults to 0.0.0.0) with the port set to 0,
  555. eliciting an unused ephemeral port from the OS. The temporary socket is
  556. then closed and deleted, and the ephemeral port is returned.
  557. Either this method or bind_port() should be used for any tests where a
  558. server socket needs to be bound to a particular port for the duration of
  559. the test. Which one to use depends on whether the calling code is creating
  560. a python socket, or if an unused port needs to be provided in a constructor
  561. or passed to an external program (i.e. the -accept argument to openssl's
  562. s_server mode). Always prefer bind_port() over find_unused_port() where
  563. possible. Hard coded ports should *NEVER* be used. As soon as a server
  564. socket is bound to a hard coded port, the ability to run multiple instances
  565. of the test simultaneously on the same host is compromised, which makes the
  566. test a ticking time bomb in a buildbot environment. On Unix buildbots, this
  567. may simply manifest as a failed test, which can be recovered from without
  568. intervention in most cases, but on Windows, the entire python process can
  569. completely and utterly wedge, requiring someone to log in to the buildbot
  570. and manually kill the affected process.
  571. (This is easy to reproduce on Windows, unfortunately, and can be traced to
  572. the SO_REUSEADDR socket option having different semantics on Windows versus
  573. Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
  574. listen and then accept connections on identical host/ports. An EADDRINUSE
  575. OSError will be raised at some point (depending on the platform and
  576. the order bind and listen were called on each socket).
  577. However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
  578. will ever be raised when attempting to bind two identical host/ports. When
  579. accept() is called on each socket, the second caller's process will steal
  580. the port from the first caller, leaving them both in an awkwardly wedged
  581. state where they'll no longer respond to any signals or graceful kills, and
  582. must be forcibly killed via OpenProcess()/TerminateProcess().
  583. The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
  584. instead of SO_REUSEADDR, which effectively affords the same semantics as
  585. SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
  586. Source world compared to Windows ones, this is a common mistake. A quick
  587. look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
  588. openssl.exe is called with the 's_server' option, for example. See
  589. http://bugs.python.org/issue2550 for more info. The following site also
  590. has a very thorough description about the implications of both REUSEADDR
  591. and EXCLUSIVEADDRUSE on Windows:
  592. http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
  593. XXX: although this approach is a vast improvement on previous attempts to
  594. elicit unused ports, it rests heavily on the assumption that the ephemeral
  595. port returned to us by the OS won't immediately be dished back out to some
  596. other process when we close and delete our temporary socket but before our
  597. calling code has a chance to bind the returned port. We can deal with this
  598. issue if/when we come across it.
  599. """
  600. tempsock = socket.socket(family, socktype)
  601. port = bind_port(tempsock)
  602. tempsock.close()
  603. del tempsock
  604. return port
  605. def bind_port(sock, host=HOST):
  606. """Bind the socket to a free port and return the port number. Relies on
  607. ephemeral ports in order to ensure we are using an unbound port. This is
  608. important as many tests may be running simultaneously, especially in a
  609. buildbot environment. This method raises an exception if the sock.family
  610. is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
  611. or SO_REUSEPORT set on it. Tests should *never* set these socket options
  612. for TCP/IP sockets. The only case for setting these options is testing
  613. multicasting via multiple UDP sockets.
  614. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
  615. on Windows), it will be set on the socket. This will prevent anyone else
  616. from bind()'ing to our host/port for the duration of the test.
  617. """
  618. if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
  619. if hasattr(socket, 'SO_REUSEADDR'):
  620. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
  621. raise TestFailed("tests should never set the SO_REUSEADDR " \
  622. "socket option on TCP/IP sockets!")
  623. if hasattr(socket, 'SO_REUSEPORT'):
  624. try:
  625. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
  626. raise TestFailed("tests should never set the SO_REUSEPORT " \
  627. "socket option on TCP/IP sockets!")
  628. except OSError:
  629. # Python's socket module was compiled using modern headers
  630. # thus defining SO_REUSEPORT but this process is running
  631. # under an older kernel that does not support SO_REUSEPORT.
  632. pass
  633. if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
  634. sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  635. sock.bind((host, 0))
  636. port = sock.getsockname()[1]
  637. return port
  638. def bind_unix_socket(sock, addr):
  639. """Bind a unix socket, raising SkipTest if PermissionError is raised."""
  640. assert sock.family == socket.AF_UNIX
  641. try:
  642. sock.bind(addr)
  643. except PermissionError:
  644. sock.close()
  645. raise unittest.SkipTest('cannot bind AF_UNIX sockets')
  646. def _is_ipv6_enabled():
  647. """Check whether IPv6 is enabled on this host."""
  648. if socket.has_ipv6:
  649. sock = None
  650. try:
  651. sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  652. sock.bind((HOSTv6, 0))
  653. return True
  654. except OSError:
  655. pass
  656. finally:
  657. if sock:
  658. sock.close()
  659. return False
  660. IPV6_ENABLED = _is_ipv6_enabled()
  661. def system_must_validate_cert(f):
  662. """Skip the test on TLS certificate validation failures."""
  663. @functools.wraps(f)
  664. def dec(*args, **kwargs):
  665. try:
  666. f(*args, **kwargs)
  667. except OSError as e:
  668. if "CERTIFICATE_VERIFY_FAILED" in str(e):
  669. raise unittest.SkipTest("system does not contain "
  670. "necessary certificates")
  671. raise
  672. return dec
  673. # A constant likely larger than the underlying OS pipe buffer size, to
  674. # make writes blocking.
  675. # Windows limit seems to be around 512 B, and many Unix kernels have a
  676. # 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
  677. # (see issue #17835 for a discussion of this number).
  678. PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
  679. # A constant likely larger than the underlying OS socket buffer size, to make
  680. # writes blocking.
  681. # The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
  682. # on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
  683. # for a discussion of this number).
  684. SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1
  685. # decorator for skipping tests on non-IEEE 754 platforms
  686. requires_IEEE_754 = unittest.skipUnless(
  687. float.__getformat__("double").startswith("IEEE"),
  688. "test requires IEEE 754 doubles")
  689. requires_zlib = unittest.skipUnless(zlib, 'requires zlib')
  690. requires_gzip = unittest.skipUnless(gzip, 'requires gzip')
  691. requires_bz2 = unittest.skipUnless(bz2, 'requires bz2')
  692. requires_lzma = unittest.skipUnless(lzma, 'requires lzma')
  693. is_jython = sys.platform.startswith('java')
  694. is_android = hasattr(sys, 'getandroidapilevel')
  695. if sys.platform != 'win32':
  696. unix_shell = '/system/bin/sh' if is_android else '/bin/sh'
  697. else:
  698. unix_shell = None
  699. # Filename used for testing
  700. if os.name == 'java':
  701. # Jython disallows @ in module names
  702. TESTFN = '$test'
  703. else:
  704. TESTFN = '@test'
  705. # Disambiguate TESTFN for parallel testing, while letting it remain a valid
  706. # module name.
  707. TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
  708. # Define the URL of a dedicated HTTP server for the network tests.
  709. # The URL must use clear-text HTTP: no redirection to encrypted HTTPS.
  710. TEST_HTTP_URL = "http://www.pythontest.net"
  711. # FS_NONASCII: non-ASCII character encodable by os.fsencode(),
  712. # or None if there is no such character.
  713. FS_NONASCII = None
  714. for character in (
  715. # First try printable and common characters to have a readable filename.
  716. # For each character, the encoding list are just example of encodings able
  717. # to encode the character (the list is not exhaustive).
  718. # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
  719. '\u00E6',
  720. # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
  721. '\u0130',
  722. # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
  723. '\u0141',
  724. # U+03C6 (Greek Small Letter Phi): cp1253
  725. '\u03C6',
  726. # U+041A (Cyrillic Capital Letter Ka): cp1251
  727. '\u041A',
  728. # U+05D0 (Hebrew Letter Alef): Encodable to cp424
  729. '\u05D0',
  730. # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
  731. '\u060C',
  732. # U+062A (Arabic Letter Teh): cp720
  733. '\u062A',
  734. # U+0E01 (Thai Character Ko Kai): cp874
  735. '\u0E01',
  736. # Then try more "special" characters. "special" because they may be
  737. # interpreted or displayed differently depending on the exact locale
  738. # encoding and the font.
  739. # U+00A0 (No-Break Space)
  740. '\u00A0',
  741. # U+20AC (Euro Sign)
  742. '\u20AC',
  743. ):
  744. try:
  745. # If Python is set up to use the legacy 'mbcs' in Windows,
  746. # 'replace' error mode is used, and encode() returns b'?'
  747. # for characters missing in the ANSI codepage
  748. if os.fsdecode(os.fsencode(character)) != character:
  749. raise UnicodeError
  750. except UnicodeError:
  751. pass
  752. else:
  753. FS_NONASCII = character
  754. break
  755. # TESTFN_UNICODE is a non-ascii filename
  756. TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
  757. if sys.platform == 'darwin':
  758. # In Mac OS X's VFS API file names are, by definition, canonically
  759. # decomposed Unicode, encoded using UTF-8. See QA1173:
  760. # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
  761. import unicodedata
  762. TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
  763. TESTFN_ENCODING = sys.getfilesystemencoding()
  764. # TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
  765. # encoded by the filesystem encoding (in strict mode). It can be None if we
  766. # cannot generate such filename.
  767. TESTFN_UNENCODABLE = None
  768. if os.name == 'nt':
  769. # skip win32s (0) or Windows 9x/ME (1)
  770. if sys.getwindowsversion().platform >= 2:
  771. # Different kinds of characters from various languages to minimize the
  772. # probability that the whole name is encodable to MBCS (issue #9819)
  773. TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
  774. try:
  775. TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
  776. except UnicodeEncodeError:
  777. pass
  778. else:
  779. print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
  780. 'Unicode filename tests may not be effective'
  781. % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
  782. TESTFN_UNENCODABLE = None
  783. # Mac OS X denies unencodable filenames (invalid utf-8)
  784. elif sys.platform != 'darwin':
  785. try:
  786. # ascii and utf-8 cannot encode the byte 0xff
  787. b'\xff'.decode(TESTFN_ENCODING)
  788. except UnicodeDecodeError:
  789. # 0xff will be encoded using the surrogate character u+DCFF
  790. TESTFN_UNENCODABLE = TESTFN \
  791. + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
  792. else:
  793. # File system encoding (eg. ISO-8859-* encodings) can encode
  794. # the byte 0xff. Skip some unicode filename tests.
  795. pass
  796. # TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be
  797. # decoded from the filesystem encoding (in strict mode). It can be None if we
  798. # cannot generate such filename (ex: the latin1 encoding can decode any byte
  799. # sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks
  800. # to the surrogateescape error handler (PEP 383), but not from the filesystem
  801. # encoding in strict mode.
  802. TESTFN_UNDECODABLE = None
  803. for name in (
  804. # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows
  805. # accepts it to create a file or a directory, or don't accept to enter to
  806. # such directory (when the bytes name is used). So test b'\xe7' first: it is
  807. # not decodable from cp932.
  808. b'\xe7w\xf0',
  809. # undecodable from ASCII, UTF-8
  810. b'\xff',
  811. # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856
  812. # and cp857
  813. b'\xae\xd5'
  814. # undecodable from UTF-8 (UNIX and Mac OS X)
  815. b'\xed\xb2\x80', b'\xed\xb4\x80',
  816. # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252,
  817. # cp1253, cp1254, cp1255, cp1257, cp1258
  818. b'\x81\x98',
  819. ):
  820. try:
  821. name.decode(TESTFN_ENCODING)
  822. except UnicodeDecodeError:
  823. TESTFN_UNDECODABLE = os.fsencode(TESTFN) + name
  824. break
  825. if FS_NONASCII:
  826. TESTFN_NONASCII = TESTFN + '-' + FS_NONASCII
  827. else:
  828. TESTFN_NONASCII = None
  829. # Save the initial cwd
  830. SAVEDCWD = os.getcwd()
  831. # Set by libregrtest/main.py so we can skip tests that are not
  832. # useful for PGO
  833. PGO = False
  834. @contextlib.contextmanager
  835. def temp_dir(path=None, quiet=False):
  836. """Return a context manager that creates a temporary directory.
  837. Arguments:
  838. path: the directory to create temporarily. If omitted or None,
  839. defaults to creating a temporary directory using tempfile.mkdtemp.
  840. quiet: if False (the default), the context manager raises an exception
  841. on error. Otherwise, if the path is specified and cannot be
  842. created, only a warning is issued.
  843. """
  844. dir_created = False
  845. if path is None:
  846. path = tempfile.mkdtemp()
  847. dir_created = True
  848. path = os.path.realpath(path)
  849. else:
  850. try:
  851. os.mkdir(path)
  852. dir_created = True
  853. except OSError as exc:
  854. if not quiet:
  855. raise
  856. warnings.warn(f'tests may fail, unable to create '
  857. f'temporary directory {path!r}: {exc}',
  858. RuntimeWarning, stacklevel=3)
  859. if dir_created:
  860. pid = os.getpid()
  861. try:
  862. yield path
  863. finally:
  864. # In case the process forks, let only the parent remove the
  865. # directory. The child has a different process id. (bpo-30028)
  866. if dir_created and pid == os.getpid():
  867. rmtree(path)
  868. @contextlib.contextmanager
  869. def change_cwd(path, quiet=False):
  870. """Return a context manager that changes the current working directory.
  871. Arguments:
  872. path: the directory to use as the temporary current working directory.
  873. quiet: if False (the default), the context manager raises an exception
  874. on error. Otherwise, it issues only a warning and keeps the current
  875. working directory the same.
  876. """
  877. saved_dir = os.getcwd()
  878. try:
  879. os.chdir(path)
  880. except OSError as exc:
  881. if not quiet:
  882. raise
  883. warnings.warn(f'tests may fail, unable to change the current working '
  884. f'directory to {path!r}: {exc}',
  885. RuntimeWarning, stacklevel=3)
  886. try:
  887. yield os.getcwd()
  888. finally:
  889. os.chdir(saved_dir)
  890. @contextlib.contextmanager
  891. def temp_cwd(name='tempcwd', quiet=False):
  892. """
  893. Context manager that temporarily creates and changes the CWD.
  894. The function temporarily changes the current working directory
  895. after creating a temporary directory in the current directory with
  896. name *name*. If *name* is None, the temporary directory is
  897. created using tempfile.mkdtemp.
  898. If *quiet* is False (default) and it is not possible to
  899. create or change the CWD, an error is raised. If *quiet* is True,
  900. only a warning is raised and the original CWD is used.
  901. """
  902. with temp_dir(path=name, quiet=quiet) as temp_path:
  903. with change_cwd(temp_path, quiet=quiet) as cwd_dir:
  904. yield cwd_dir
  905. if hasattr(os, "umask"):
  906. @contextlib.contextmanager
  907. def temp_umask(umask):
  908. """Context manager that temporarily sets the process umask."""
  909. oldmask = os.umask(umask)
  910. try:
  911. yield
  912. finally:
  913. os.umask(oldmask)
  914. # TEST_HOME_DIR refers to the top level directory of the "test" package
  915. # that contains Python's regression test suite
  916. TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__))
  917. TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR)
  918. # TEST_DATA_DIR is used as a target download location for remote resources
  919. TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data")
  920. def findfile(filename, subdir=None):
  921. """Try to find a file on sys.path or in the test directory. If it is not
  922. found the argument passed to the function is returned (this does not
  923. necessarily signal failure; could still be the legitimate path).
  924. Setting *subdir* indicates a relative path to use to find the file
  925. rather than looking directly in the path directories.
  926. """
  927. if os.path.isabs(filename):
  928. return filename
  929. if subdir is not None:
  930. filename = os.path.join(subdir, filename)
  931. path = [TEST_HOME_DIR] + sys.path
  932. for dn in path:
  933. fn = os.path.join(dn, filename)
  934. if os.path.exists(fn): return fn
  935. return filename
  936. def create_empty_file(filename):
  937. """Create an empty file. If the file already exists, truncate it."""
  938. fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
  939. os.close(fd)
  940. def sortdict(dict):
  941. "Like repr(dict), but in sorted order."
  942. items = sorted(dict.items())
  943. reprpairs = ["%r: %r" % pair for pair in items]
  944. withcommas = ", ".join(reprpairs)
  945. return "{%s}" % withcommas
  946. def make_bad_fd():
  947. """
  948. Create an invalid file descriptor by opening and closing a file and return
  949. its fd.
  950. """
  951. file = open(TESTFN, "wb")
  952. try:
  953. return file.fileno()
  954. finally:
  955. file.close()
  956. unlink(TESTFN)
  957. def check_syntax_error(testcase, statement, *, lineno=None, offset=None):
  958. with testcase.assertRaises(SyntaxError) as cm:
  959. compile(statement, '<test string>', 'exec')
  960. err = cm.exception
  961. testcase.assertIsNotNone(err.lineno)
  962. if lineno is not None:
  963. testcase.assertEqual(err.lineno, lineno)
  964. testcase.assertIsNotNone(err.offset)
  965. if offset is not None:
  966. testcase.assertEqual(err.offset, offset)
  967. def open_urlresource(url, *args, **kw):
  968. import urllib.request, urllib.parse
  969. check = kw.pop('check', None)
  970. filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
  971. fn = os.path.join(TEST_DATA_DIR, filename)
  972. def check_valid_file(fn):
  973. f = open(fn, *args, **kw)
  974. if check is None:
  975. return f
  976. elif check(f):
  977. f.seek(0)
  978. return f
  979. f.close()
  980. if os.path.exists(fn):
  981. f = check_valid_file(fn)
  982. if f is not None:
  983. return f
  984. unlink(fn)
  985. # Verify the requirement before downloading the file
  986. requires('urlfetch')
  987. if verbose:
  988. print('\tfetching %s ...' % url, file=get_original_stdout())
  989. opener = urllib.request.build_opener()
  990. if gzip:
  991. opener.addheaders.append(('Accept-Encoding', 'gzip'))
  992. f = opener.open(url, timeout=15)
  993. if gzip and f.headers.get('Content-Encoding') == 'gzip':
  994. f = gzip.GzipFile(fileobj=f)
  995. try:
  996. with open(fn, "wb") as out:
  997. s = f.read()
  998. while s:
  999. out.write(s)
  1000. s = f.read()
  1001. finally:
  1002. f.close()
  1003. f = check_valid_file(fn)
  1004. if f is not None:
  1005. return f
  1006. raise TestFailed('invalid resource %r' % fn)
  1007. class WarningsRecorder(object):
  1008. """Convenience wrapper for the warnings list returned on
  1009. entry to the warnings.catch_warnings() context manager.
  1010. """
  1011. def __init__(self, warnings_list):
  1012. self._warnings = warnings_list
  1013. self._last = 0
  1014. def __getattr__(self, attr):
  1015. if len(self._warnings) > self._last:
  1016. return getattr(self._warnings[-1], attr)
  1017. elif attr in warnings.WarningMessage._WARNING_DETAILS:
  1018. return None
  1019. raise AttributeError("%r has no attribute %r" % (self, attr))
  1020. @property
  1021. def warnings(self):
  1022. return self._warnings[self._last:]
  1023. def reset(self):
  1024. self._last = len(self._warnings)
  1025. def _filterwarnings(filters, quiet=False):
  1026. """Catch the warnings, then check if all the expected
  1027. warnings have been raised and re-raise unexpected warnings.
  1028. If 'quiet' is True, only re-raise the unexpected warnings.
  1029. """
  1030. # Clear the warning registry of the calling module
  1031. # in order to re-raise the warnings.
  1032. frame = sys._getframe(2)
  1033. registry = frame.f_globals.get('__warningregistry__')
  1034. if registry:
  1035. registry.clear()
  1036. with warnings.catch_warnings(record=True) as w:
  1037. # Set filter "always" to record all warnings. Because
  1038. # test_warnings swap the module, we need to look up in
  1039. # the sys.modules dictionary.
  1040. sys.modules['warnings'].simplefilter("always")
  1041. yield WarningsRecorder(w)
  1042. # Filter the recorded warnings
  1043. reraise = list(w)
  1044. missing = []
  1045. for msg, cat in filters:
  1046. seen = False
  1047. for w in reraise[:]:
  1048. warning = w.message
  1049. # Filter out the matching messages
  1050. if (re.match(msg, str(warning), re.I) and
  1051. issubclass(warning.__class__, cat)):
  1052. seen = True
  1053. reraise.remove(w)
  1054. if not seen and not quiet:
  1055. # This filter caught nothing
  1056. missing.append((msg, cat.__name__))
  1057. if reraise:
  1058. raise AssertionError("unhandled warning %s" % reraise[0])
  1059. if missing:
  1060. raise AssertionError("filter (%r, %s) did not catch any warning" %
  1061. missing[0])
  1062. @contextlib.contextmanager
  1063. def check_warnings(*filters, **kwargs):
  1064. """Context manager to silence warnings.
  1065. Accept 2-tuples as positional arguments:
  1066. ("message regexp", WarningCategory)
  1067. Optional argument:
  1068. - if 'quiet' is True, it does not fail if a filter catches nothing
  1069. (default True without argument,
  1070. default False if some filters are defined)
  1071. Without argument, it defaults to:
  1072. check_warnings(("", Warning), quiet=True)
  1073. """
  1074. quiet = kwargs.get('quiet')
  1075. if not filters:
  1076. filters = (("", Warning),)
  1077. # Preserve backward compatibility
  1078. if quiet is None:
  1079. quiet = True
  1080. return _filterwarnings(filters, quiet)
  1081. @contextlib.contextmanager
  1082. def check_no_resource_warning(testcase):
  1083. """Context manager to check that no ResourceWarning is emitted.
  1084. Usage:
  1085. with check_no_resource_warning(self):
  1086. f = open(...)
  1087. ...
  1088. del f
  1089. You must remove the object which may emit ResourceWarning before
  1090. the end of the context manager.
  1091. """
  1092. with warnings.catch_warnings(record=True) as warns:
  1093. warnings.filterwarnings('always', category=ResourceWarning)
  1094. yield
  1095. gc_collect()
  1096. testcase.assertEqual(warns, [])
  1097. class CleanImport(object):
  1098. """Context manager to force import to return a new module reference.
  1099. This is useful for testing module-level behaviours, such as
  1100. the emission of a DeprecationWarning on import.
  1101. Use like this:
  1102. with CleanImport("foo"):
  1103. importlib.import_module("foo") # new reference
  1104. """
  1105. def __init__(self, *module_names):
  1106. self.original_modules = sys.modules.copy()
  1107. for module_name in module_names:
  1108. if module_name in sys.modules:
  1109. module = sys.modules[module_name]
  1110. # It is possible that module_name is just an alias for
  1111. # another module (e.g. stub for modules renamed in 3.x).
  1112. # In that case, we also need delete the real module to clear
  1113. # the import cache.
  1114. if module.__name__ != module_name:
  1115. del sys.modules[module.__name__]
  1116. del sys.modules[module_name]
  1117. def __enter__(self):
  1118. return self
  1119. def __exit__(self, *ignore_exc):
  1120. sys.modules.update(self.original_modules)
  1121. class EnvironmentVarGuard(collections.abc.MutableMapping):
  1122. """Class to help protect the environment variable properly. Can be used as
  1123. a context manager."""
  1124. def __init__(self):
  1125. self._environ = os.environ
  1126. self._changed = {}
  1127. def __getitem__(self, envvar):
  1128. return self._environ[envvar]
  1129. def __setitem__(self, envvar, value):
  1130. # Remember the initial value on the first access
  1131. if envvar not in self._changed:
  1132. self._changed[envvar] = self._environ.get(envvar)
  1133. self._environ[envvar] = value
  1134. def __delitem__(self, envvar):
  1135. # Remember the initial value on the first access
  1136. if envvar not in self._changed:
  1137. self._changed[envvar] = self._environ.get(envvar)
  1138. if envvar in self._environ:
  1139. del self._environ[envvar]
  1140. def keys(self):
  1141. return self._environ.keys()
  1142. def __iter__(self):
  1143. return iter(self._environ)
  1144. def __len__(self):
  1145. return len(self._environ)
  1146. def set(self, envvar, value):
  1147. self[envvar] = value
  1148. def unset(self, envvar):
  1149. del self[envvar]
  1150. def __enter__(self):
  1151. return self
  1152. def __exit__(self, *ignore_exc):
  1153. for (k, v) in self._changed.items():
  1154. if v is None:
  1155. if k in self._environ:
  1156. del self._environ[k]
  1157. else:
  1158. self._environ[k] = v
  1159. os.environ = self._environ
  1160. class DirsOnSysPath(object):
  1161. """Context manager to temporarily add directories to sys.path.
  1162. This makes a copy of sys.path, appends any directories given
  1163. as positional arguments, then reverts sys.path to the copied
  1164. settings when the context ends.
  1165. Note that *all* sys.path modifications in the body of the
  1166. context manager, including replacement of the object,
  1167. will be reverted at the end of the block.
  1168. """
  1169. def __init__(self, *paths):
  1170. self.original_value = sys.path[:]
  1171. self.original_object = sys.path
  1172. sys.path.extend(paths)
  1173. def __enter__(self):
  1174. return self
  1175. def __exit__(self, *ignore_exc):
  1176. sys.path = self.original_object
  1177. sys.path[:] = self.original_value
  1178. class TransientResource(object):
  1179. """Raise ResourceDenied if an exception is raised while the context manager
  1180. is in effect that matches the specified exception and attributes."""
  1181. def __init__(self, exc, **kwargs):
  1182. self.exc = exc
  1183. self.attrs = kwargs
  1184. def __enter__(self):
  1185. return self
  1186. def __exit__(self, type_=None, value=None, traceback=None):
  1187. """If type_ is a subclass of self.exc and value has attributes matching
  1188. self.attrs, raise ResourceDenied. Otherwise let the exception
  1189. propagate (if any)."""
  1190. if type_ is not None and issubclass(self.exc, type_):
  1191. for attr, attr_value in self.attrs.items():
  1192. if not hasattr(value, attr):
  1193. break
  1194. if getattr(value, attr) != attr_value:
  1195. break
  1196. else:
  1197. raise ResourceDenied("an optional resource is not available")
  1198. # Context managers that raise ResourceDenied when various issues
  1199. # with the Internet connection manifest themselves as exceptions.
  1200. # XXX deprecate these and use transient_internet() instead
  1201. time_out = TransientResource(OSError, errno=errno.ETIMEDOUT)
  1202. socket_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
  1203. ioerror_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
  1204. def get_socket_conn_refused_errs():
  1205. """
  1206. Get the different socket error numbers ('errno') which can be received
  1207. when a connection is refused.
  1208. """
  1209. errors = [errno.ECONNREFUSED]
  1210. if hasattr(errno, 'ENETUNREACH'):
  1211. # On Solaris, ENETUNREACH is returned sometimes instead of ECONNREFUSED
  1212. errors.append(errno.ENETUNREACH)
  1213. if hasattr(errno, 'EADDRNOTAVAIL'):
  1214. # bpo-31910: socket.create_connection() fails randomly
  1215. # with EADDRNOTAVAIL on Travis CI
  1216. errors.append(errno.EADDRNOTAVAIL)
  1217. if hasattr(errno, 'EHOSTUNREACH'):
  1218. # bpo-37583: The destination host cannot be reached
  1219. errors.append(errno.EHOSTUNREACH)
  1220. return errors
  1221. @contextlib.contextmanager
  1222. def transient_internet(resource_name, *, timeout=30.0, errnos=()):
  1223. """Return a context manager that raises ResourceDenied when various issues
  1224. with the Internet connection manifest themselves as exceptions."""
  1225. default_errnos = [
  1226. ('ECONNREFUSED', 111),
  1227. ('ECONNRESET', 104),
  1228. ('EHOSTUNREACH', 113),
  1229. ('ENETUNREACH', 101),
  1230. ('ETIMEDOUT', 110),
  1231. # socket.create_connection() fails randomly with
  1232. # EADDRNOTAVAIL on Travis CI.
  1233. ('EADDRNOTAVAIL', 99),
  1234. ]
  1235. default_gai_errnos = [
  1236. ('EAI_AGAIN', -3),
  1237. ('EAI_FAIL', -4),
  1238. ('EAI_NONAME', -2),
  1239. ('EAI_NODATA', -5),
  1240. # Encountered when trying to resolve IPv6-only hostnames
  1241. ('WSANO_DATA', 11004),
  1242. ]
  1243. denied = ResourceDenied("Resource %r is not available" % resource_name)
  1244. captured_errnos = errnos
  1245. gai_errnos = []
  1246. if not captured_errnos:
  1247. captured_errnos = [getattr(errno, name, num)
  1248. for (name, num) in default_errnos]
  1249. gai_errnos = [getattr(socket, name, num)
  1250. for (name, num) in default_gai_errnos]
  1251. def filter_error(err):
  1252. n = getattr(err, 'errno', None)
  1253. if (isinstance(err, socket.timeout) or
  1254. (isinstance(err, socket.gaierror) and n in gai_errnos) or
  1255. (isinstance(err, urllib.error.HTTPError) and
  1256. 500 <= err.code <= 599) or
  1257. (isinstance(err, urllib.error.URLError) and
  1258. (("ConnectionRefusedError" in err.reason) or
  1259. ("TimeoutError" in err.reason) or
  1260. ("EOFError" in err.reason))) or
  1261. n in captured_errnos):
  1262. if not verbose:
  1263. sys.stderr.write(denied.args[0] + "\n")
  1264. raise denied from err
  1265. old_timeout = socket.getdefaulttimeout()
  1266. try:
  1267. if timeout is not None:
  1268. socket.setdefaulttimeout(timeout)
  1269. yield
  1270. except nntplib.NNTPTemporaryError as err:
  1271. if verbose:
  1272. sys.stderr.write(denied.args[0] + "\n")
  1273. raise denied from err
  1274. except OSError as err:
  1275. # urllib can wrap original socket errors multiple times (!), we must
  1276. # unwrap to get at the original error.
  1277. while True:
  1278. a = err.args
  1279. if len(a) >= 1 and isinstance(a[0], OSError):
  1280. err = a[0]
  1281. # The error can also be wrapped as args[1]:
  1282. # except socket.error as msg:
  1283. # raise OSError('socket error', msg).with_traceback(sys.exc_info()[2])
  1284. elif len(a) >= 2 and isinstance(a[1], OSError):
  1285. err = a[1]
  1286. else:
  1287. break
  1288. filter_error(err)
  1289. raise
  1290. # XXX should we catch generic exceptions and look for their
  1291. # __cause__ or __context__?
  1292. finally:
  1293. socket.setdefaulttimeout(old_timeout)
  1294. @contextlib.contextmanager
  1295. def captured_output(stream_name):
  1296. """Return a context manager used by captured_stdout/stdin/stderr
  1297. that temporarily replaces the sys stream *stream_name* with a StringIO."""
  1298. import io
  1299. orig_stdout = getattr(sys, stream_name)
  1300. setattr(sys, stream_name, io.StringIO())
  1301. try:
  1302. yield getattr(sys, stream_name)
  1303. finally:
  1304. setattr(sys, stream_name, orig_stdout)
  1305. def captured_stdout():
  1306. """Capture the output of sys.stdout:
  1307. with captured_stdout() as stdout:
  1308. print("hello")
  1309. self.assertEqual(stdout.getvalue(), "hello\\n")
  1310. """
  1311. return captured_output("stdout")
  1312. def captured_stderr():
  1313. """Capture the output of sys.stderr:
  1314. with captured_stderr() as stderr:
  1315. print("hello", file=sys.stderr)
  1316. self.assertEqual(stderr.getvalue(), "hello\\n")
  1317. """
  1318. return captured_output("stderr")
  1319. def captured_stdin():
  1320. """Capture the input to sys.stdin:
  1321. with captured_stdin() as stdin:
  1322. stdin.write('hello\\n')
  1323. stdin.seek(0)
  1324. # call test code that consumes from sys.stdin
  1325. captured = input()
  1326. self.assertEqual(captured, "hello")
  1327. """
  1328. return captured_output("stdin")
  1329. def gc_collect():
  1330. """Force as many objects as possible to be collected.
  1331. In non-CPython implementations of Python, this is needed because timely
  1332. deallocation is not guaranteed by the garbage collector. (Even in CPython
  1333. this can be the case in case of reference cycles.) This means that __del__
  1334. methods may be called later than expected and weakrefs may remain alive for
  1335. longer than expected. This function tries its best to force all garbage
  1336. objects to disappear.
  1337. """
  1338. gc.collect()
  1339. if is_jython:
  1340. time.sleep(0.1)
  1341. gc.collect()
  1342. gc.collect()
  1343. @contextlib.contextmanager
  1344. def disable_gc():
  1345. have_gc = gc.isenabled()
  1346. gc.disable()
  1347. try:
  1348. yield
  1349. finally:
  1350. if have_gc:
  1351. gc.enable()
  1352. def python_is_optimized():
  1353. """Find if Python was built with optimizations."""
  1354. cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
  1355. final_opt = ""
  1356. for opt in cflags.split():
  1357. if opt.startswith('-O'):
  1358. final_opt = opt
  1359. return final_opt not in ('', '-O0', '-Og')
  1360. _header = 'nP'
  1361. _align = '0n'
  1362. if hasattr(sys, "gettotalrefcount"):
  1363. _header = '2P' + _header
  1364. _align = '0P'
  1365. _vheader = _header + 'n'
  1366. def calcobjsize(fmt):
  1367. return struct.calcsize(_header + fmt + _align)
  1368. def calcvobjsize(fmt):
  1369. return struct.calcsize(_vheader + fmt + _align)
  1370. _TPFLAGS_HAVE_GC = 1<<14
  1371. _TPFLAGS_HEAPTYPE = 1<<9
  1372. def check_sizeof(test, o, size):
  1373. import _testcapi
  1374. result = sys.getsizeof(o)
  1375. # add GC header size
  1376. if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
  1377. ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
  1378. size += _testcapi.SIZEOF_PYGC_HEAD
  1379. msg = 'wrong size for %s: got %d, expected %d' \
  1380. % (type(o), result, size)
  1381. test.assertEqual(result, size, msg)
  1382. #=======================================================================
  1383. # Decorator for running a function in a different locale, correctly resetting
  1384. # it afterwards.
  1385. def run_with_locale(catstr, *locales):
  1386. def decorator(func):
  1387. def inner(*args, **kwds):
  1388. try:
  1389. import locale
  1390. category = getattr(locale, catstr)
  1391. orig_locale = locale.setlocale(category)
  1392. except AttributeError:
  1393. # if the test author gives us an invalid category string
  1394. raise
  1395. except:
  1396. # cannot retrieve original locale, so do nothing
  1397. locale = orig_locale = None
  1398. else:
  1399. for loc in locales:
  1400. try:
  1401. locale.setlocale(category, loc)
  1402. break
  1403. except:
  1404. pass
  1405. # now run the function, resetting the locale on exceptions
  1406. try:
  1407. return func(*args, **kwds)
  1408. finally:
  1409. if locale and orig_locale:
  1410. locale.setlocale(category, orig_locale)
  1411. inner.__name__ = func.__name__
  1412. inner.__doc__ = func.__doc__
  1413. return inner
  1414. return decorator
  1415. #=======================================================================
  1416. # Decorator for running a function in a specific timezone, correctly
  1417. # resetting it afterwards.
  1418. def run_with_tz(tz):
  1419. def decorator(func):
  1420. def inner(*args, **kwds):
  1421. try:
  1422. tzset = time.tzset
  1423. except AttributeError:
  1424. raise unittest.SkipTest("tzset required")
  1425. if 'TZ' in os.environ:
  1426. orig_tz = os.environ['TZ']
  1427. else:
  1428. orig_tz = None
  1429. os.environ['TZ'] = tz
  1430. tzset()
  1431. # now run the function, resetting the tz on exceptions
  1432. try:
  1433. return func(*args, **kwds)
  1434. finally:
  1435. if orig_tz is None:
  1436. del os.environ['TZ']
  1437. else:
  1438. os.environ['TZ'] = orig_tz
  1439. time.tzset()
  1440. inner.__name__ = func.__name__
  1441. inner.__doc__ = func.__doc__
  1442. return inner
  1443. return decorator
  1444. #=======================================================================
  1445. # Big-memory-test support. Separate from 'resources' because memory use
  1446. # should be configurable.
  1447. # Some handy shorthands. Note that these are used for byte-limits as well
  1448. # as size-limits, in the various bigmem tests
  1449. _1M = 1024*1024
  1450. _1G = 1024 * _1M
  1451. _2G = 2 * _1G
  1452. _4G = 4 * _1G
  1453. MAX_Py_ssize_t = sys.maxsize
  1454. def set_memlimit(limit):
  1455. global max_memuse
  1456. global real_max_memuse
  1457. sizes = {
  1458. 'k': 1024,
  1459. 'm': _1M,
  1460. 'g': _1G,
  1461. 't': 1024*_1G,
  1462. }
  1463. m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
  1464. re.IGNORECASE | re.VERBOSE)
  1465. if m is None:
  1466. raise ValueError('Invalid memory limit %r' % (limit,))
  1467. memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
  1468. real_max_memuse = memlimit
  1469. if memlimit > MAX_Py_ssize_t:
  1470. memlimit = MAX_Py_ssize_t
  1471. if memlimit < _2G - 1:
  1472. raise ValueError('Memory limit %r too low to be useful' % (limit,))
  1473. max_memuse = memlimit
  1474. class _MemoryWatchdog:
  1475. """An object which periodically watches the process' memory consumption
  1476. and prints it out.
  1477. """
  1478. def __init__(self):
  1479. self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
  1480. self.started = False
  1481. def start(self):
  1482. try:
  1483. f = open(self.procfile, 'r')
  1484. except OSError as e:
  1485. warnings.warn('/proc not available for stats: {}'.format(e),
  1486. RuntimeWarning)
  1487. sys.stderr.flush()
  1488. return
  1489. watchdog_script = findfile("memory_watchdog.py")
  1490. self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
  1491. stdin=f, stderr=subprocess.DEVNULL)
  1492. f.close()
  1493. self.started = True
  1494. def stop(self):
  1495. if self.started:
  1496. self.mem_watchdog.terminate()
  1497. self.mem_watchdog.wait()
  1498. def bigmemtest(size, memuse, dry_run=True):
  1499. """Decorator for bigmem tests.
  1500. 'size' is a requested size for the test (in arbitrary, test-interpreted
  1501. units.) 'memuse' is the number of bytes per unit for the test, or a good
  1502. estimate of it. For example, a test that needs two byte buffers, of 4 GiB
  1503. each, could be decorated with @bigmemtest(size=_4G, memuse=2).
  1504. The 'size' argument is normally passed to the decorated test method as an
  1505. extra argument. If 'dry_run' is true, the value passed to the test method
  1506. may be less than the requested value. If 'dry_run' is false, it means the
  1507. test doesn't support dummy runs when -M is not specified.
  1508. """
  1509. def decorator(f):
  1510. def wrapper(self):
  1511. size = wrapper.size
  1512. memuse = wrapper.memuse
  1513. if not real_max_memuse:
  1514. maxsize = 5147
  1515. else:
  1516. maxsize = size
  1517. if ((real_max_memuse or not dry_run)
  1518. and real_max_memuse < maxsize * memuse):
  1519. raise unittest.SkipTest(
  1520. "not enough memory: %.1fG minimum needed"
  1521. % (size * memuse / (1024 ** 3)))
  1522. if real_max_memuse and verbose:
  1523. print()
  1524. print(" ... expected peak memory use: {peak:.1f}G"
  1525. .format(peak=size * memuse / (1024 ** 3)))
  1526. watchdog = _MemoryWatchdog()
  1527. watchdog.start()
  1528. else:
  1529. watchdog = None
  1530. try:
  1531. return f(self, maxsize)
  1532. finally:
  1533. if watchdog:
  1534. watchdog.stop()
  1535. wrapper.size = size
  1536. wrapper.memuse = memuse
  1537. return wrapper
  1538. return decorator
  1539. def bigaddrspacetest(f):
  1540. """Decorator for tests that fill the address space."""
  1541. def wrapper(self):
  1542. if max_memuse < MAX_Py_ssize_t:
  1543. if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
  1544. raise unittest.SkipTest(
  1545. "not enough memory: try a 32-bit build instead")
  1546. else:
  1547. raise unittest.SkipTest(
  1548. "not enough memory: %.1fG minimum needed"
  1549. % (MAX_Py_ssize_t / (1024 ** 3)))
  1550. else:
  1551. return f(self)
  1552. return wrapper
  1553. #=======================================================================
  1554. # unittest integration.
  1555. class BasicTestRunner:
  1556. def run(self, test):
  1557. result = unittest.TestResult()
  1558. test(result)
  1559. return result
  1560. def _id(obj):
  1561. return obj
  1562. def requires_resource(resource):
  1563. if resource == 'gui' and not _is_gui_available():
  1564. return unittest.skip(_is_gui_available.reason)
  1565. if is_resource_enabled(resource):
  1566. return _id
  1567. else:
  1568. return unittest.skip("resource {0!r} is not enabled".format(resource))
  1569. def cpython_only(test):
  1570. """
  1571. Decorator for tests only applicable on CPython.
  1572. """
  1573. return impl_detail(cpython=True)(test)
  1574. def impl_detail(msg=None, **guards):
  1575. if check_impl_detail(**guards):
  1576. return _id
  1577. if msg is None:
  1578. guardnames, default = _parse_guards(guards)
  1579. if default:
  1580. msg = "implementation detail not available on {0}"
  1581. else:
  1582. msg = "implementation detail specific to {0}"
  1583. guardnames = sorted(guardnames.keys())
  1584. msg = msg.format(' or '.join(guardnames))
  1585. return unittest.skip(msg)
  1586. def _parse_guards(guards):
  1587. # Returns a tuple ({platform_name: run_me}, default_value)
  1588. if not guards:
  1589. return ({'cpython': True}, False)
  1590. is_true = list(guards.values())[0]
  1591. assert list(guards.values()) == [is_true] * len(guards) # all True or all False
  1592. return (guards, not is_true)
  1593. # Use the following check to guard CPython's implementation-specific tests --
  1594. # or to run them only on the implementation(s) guarded by the arguments.
  1595. def check_impl_detail(**guards):
  1596. """This function returns True or False depending on the host platform.
  1597. Examples:
  1598. if check_impl_detail(): # only on CPython (default)
  1599. if check_impl_detail(jython=True): # only on Jython
  1600. if check_impl_detail(cpython=False): # everywhere except on CPython
  1601. """
  1602. guards, default = _parse_guards(guards)
  1603. return guards.get(platform.python_implementation().lower(), default)
  1604. def no_tracing(func):
  1605. """Decorator to temporarily turn off tracing for the duration of a test."""
  1606. if not hasattr(sys, 'gettrace'):
  1607. return func
  1608. else:
  1609. @functools.wraps(func)
  1610. def wrapper(*args, **kwargs):
  1611. original_trace = sys.gettrace()
  1612. try:
  1613. sys.settrace(None)
  1614. return func(*args, **kwargs)
  1615. finally:
  1616. sys.settrace(original_trace)
  1617. return wrapper
  1618. def refcount_test(test):
  1619. """Decorator for tests which involve reference counting.
  1620. To start, the decorator does not run the test if is not run by CPython.
  1621. After that, any trace function is unset during the test to prevent
  1622. unexpected refcounts caused by the trace function.
  1623. """
  1624. return no_tracing(cpython_only(test))
  1625. def _filter_suite(suite, pred):
  1626. """Recursively filter test cases in a suite based on a predicate."""
  1627. newtests = []
  1628. for test in suite._tests:
  1629. if isinstance(test, unittest.TestSuite):
  1630. _filter_suite(test, pred)
  1631. newtests.append(test)
  1632. else:
  1633. if pred(test):
  1634. newtests.append(test)
  1635. suite._tests = newtests
  1636. def _run_suite(suite):
  1637. """Run tests from a unittest.TestSuite-derived class."""
  1638. runner = get_test_runner(sys.stdout,
  1639. verbosity=verbose,
  1640. capture_output=(junit_xml_list is not None))
  1641. result = runner.run(suite)
  1642. if junit_xml_list is not None:
  1643. junit_xml_list.append(result.get_xml_element())
  1644. if not result.testsRun and not result.skipped:
  1645. raise TestDidNotRun
  1646. if not result.wasSuccessful():
  1647. if len(result.errors) == 1 and not result.failures:
  1648. err = result.errors[0][1]
  1649. elif len(result.failures) == 1 and not result.errors:
  1650. err = result.failures[0][1]
  1651. else:
  1652. err = "multiple errors occurred"
  1653. if not verbose: err += "; run in verbose mode for details"
  1654. raise TestFailed(err)
  1655. # By default, don't filter tests
  1656. _match_test_func = None
  1657. _accept_test_patterns = None
  1658. _ignore_test_patterns = None
  1659. def match_test(test):
  1660. # Function used by support.run_unittest() and regrtest --list-cases
  1661. if _match_test_func is None:
  1662. return True
  1663. else:
  1664. return _match_test_func(test.id())
  1665. def _is_full_match_test(pattern):
  1666. # If a pattern contains at least one dot, it's considered
  1667. # as a full test identifier.
  1668. # Example: 'test.test_os.FileTests.test_access'.
  1669. #
  1670. # ignore patterns which contain fnmatch patterns: '*', '?', '[...]'
  1671. # or '[!...]'. For example, ignore 'test_access*'.
  1672. return ('.' in pattern) and (not re.search(r'[?*\[\]]', pattern))
  1673. def set_match_tests(accept_patterns=None, ignore_patterns=None):
  1674. global _match_test_func, _accept_test_patterns, _ignore_test_patterns
  1675. if accept_patterns is None:
  1676. accept_patterns = ()
  1677. if ignore_patterns is None:
  1678. ignore_patterns = ()
  1679. accept_func = ignore_func = None
  1680. if accept_patterns != _accept_test_patterns:
  1681. accept_patterns, accept_func = _compile_match_function(accept_patterns)
  1682. if ignore_patterns != _ignore_test_patterns:
  1683. ignore_patterns, ignore_func = _compile_match_function(ignore_patterns)
  1684. # Create a copy since patterns can be mutable and so modified later
  1685. _accept_test_patterns = tuple(accept_patterns)
  1686. _ignore_test_patterns = tuple(ignore_patterns)
  1687. if accept_func is not None or ignore_func is not None:
  1688. def match_function(test_id):
  1689. accept = True
  1690. ignore = False
  1691. if accept_func:
  1692. accept = accept_func(test_id)
  1693. if ignore_func:
  1694. ignore = ignore_func(test_id)
  1695. return accept and not ignore
  1696. _match_test_func = match_function
  1697. def _compile_match_function(patterns):
  1698. if not patterns:
  1699. func = None
  1700. # set_match_tests(None) behaves as set_match_tests(())
  1701. patterns = ()
  1702. elif all(map(_is_full_match_test, patterns)):
  1703. # Simple case: all patterns are full test identifier.
  1704. # The test.bisect_cmd utility only uses such full test identifiers.
  1705. func = set(patterns).__contains__
  1706. else:
  1707. regex = '|'.join(map(fnmatch.translate, patterns))
  1708. # The search *is* case sensitive on purpose:
  1709. # don't use flags=re.IGNORECASE
  1710. regex_match = re.compile(regex).match
  1711. def match_test_regex(test_id):
  1712. if regex_match(test_id):
  1713. # The regex matchs the whole identifier like
  1714. # 'test.test_os.FileTests.test_access'
  1715. return True
  1716. else:
  1717. # Try to match parts of the test identifier.
  1718. # For example, split 'test.test_os.FileTests.test_access'
  1719. # into: 'test', 'test_os', 'FileTests' and 'test_access'.
  1720. return any(map(regex_match, test_id.split(".")))
  1721. func = match_test_regex
  1722. return patterns, func
  1723. def run_unittest(*classes):
  1724. """Run tests from unittest.TestCase-derived classes."""
  1725. valid_types = (unittest.TestSuite, unittest.TestCase)
  1726. suite = unittest.TestSuite()
  1727. for cls in classes:
  1728. if isinstance(cls, str):
  1729. if cls in sys.modules:
  1730. suite.addTest(unittest.findTestCases(sys.modules[cls]))
  1731. else:
  1732. raise ValueError("str arguments must be keys in sys.modules")
  1733. elif isinstance(cls, valid_types):
  1734. suite.addTest(cls)
  1735. else:
  1736. suite.addTest(unittest.makeSuite(cls))
  1737. _filter_suite(suite, match_test)
  1738. _run_suite(suite)
  1739. #=======================================================================
  1740. # Check for the presence of docstrings.
  1741. # Rather than trying to enumerate all the cases where docstrings may be
  1742. # disabled, we just check for that directly
  1743. def _check_docstrings():
  1744. """Just used to check if docstrings are enabled"""
  1745. MISSING_C_DOCSTRINGS = (check_impl_detail() and
  1746. sys.platform != 'win32' and
  1747. not sysconfig.get_config_var('WITH_DOC_STRINGS'))
  1748. HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and
  1749. not MISSING_C_DOCSTRINGS)
  1750. requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
  1751. "test requires docstrings")
  1752. #=======================================================================
  1753. # doctest driver.
  1754. def run_doctest(module, verbosity=None, optionflags=0):
  1755. """Run doctest on the given module. Return (#failures, #tests).
  1756. If optional argument verbosity is not specified (or is None), pass
  1757. support's belief about verbosity on to doctest. Else doctest's
  1758. usual behavior is used (it searches sys.argv for -v).
  1759. """
  1760. import doctest
  1761. if verbosity is None:
  1762. verbosity = verbose
  1763. else:
  1764. verbosity = None
  1765. f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags)
  1766. if f:
  1767. raise TestFailed("%d of %d doctests failed" % (f, t))
  1768. if verbose:
  1769. print('doctest (%s) ... %d tests with zero failures' %
  1770. (module.__name__, t))
  1771. return f, t
  1772. #=======================================================================
  1773. # Support for saving and restoring the imported modules.
  1774. def modules_setup():
  1775. return sys.modules.copy(),
  1776. def modules_cleanup(oldmodules):
  1777. # Encoders/decoders are registered permanently within the internal
  1778. # codec cache. If we destroy the corresponding modules their
  1779. # globals will be set to None which will trip up the cached functions.
  1780. encodings = [(k, v) for k, v in sys.modules.items()
  1781. if k.startswith('encodings.')]
  1782. sys.modules.clear()
  1783. sys.modules.update(encodings)
  1784. # XXX: This kind of problem can affect more than just encodings. In particular
  1785. # extension modules (such as _ssl) don't cope with reloading properly.
  1786. # Really, test modules should be cleaning out the test specific modules they
  1787. # know they added (ala test_runpy) rather than relying on this function (as
  1788. # test_importhooks and test_pkg do currently).
  1789. # Implicitly imported *real* modules should be left alone (see issue 10556).
  1790. sys.modules.update(oldmodules)
  1791. #=======================================================================
  1792. # Threading support to prevent reporting refleaks when running regrtest.py -R
  1793. # Flag used by saved_test_environment of test.libregrtest.save_env,
  1794. # to check if a test modified the environment. The flag should be set to False
  1795. # before running a new test.
  1796. #
  1797. # For example, threading_cleanup() sets the flag is the function fails
  1798. # to cleanup threads.
  1799. environment_altered = False
  1800. # NOTE: we use thread._count() rather than threading.enumerate() (or the
  1801. # moral equivalent thereof) because a threading.Thread object is still alive
  1802. # until its __bootstrap() method has returned, even after it has been
  1803. # unregistered from the threading module.
  1804. # thread._count(), on the other hand, only gets decremented *after* the
  1805. # __bootstrap() method has returned, which gives us reliable reference counts
  1806. # at the end of a test run.
  1807. def threading_setup():
  1808. return _thread._count(), threading._dangling.copy()
  1809. def threading_cleanup(*original_values):
  1810. global environment_altered
  1811. _MAX_COUNT = 100
  1812. for count in range(_MAX_COUNT):
  1813. values = _thread._count(), threading._dangling
  1814. if values == original_values:
  1815. break
  1816. if not count:
  1817. # Display a warning at the first iteration
  1818. environment_altered = True
  1819. dangling_threads = values[1]
  1820. print("Warning -- threading_cleanup() failed to cleanup "
  1821. "%s threads (count: %s, dangling: %s)"
  1822. % (values[0] - original_values[0],
  1823. values[0], len(dangling_threads)),
  1824. file=sys.stderr)
  1825. for thread in dangling_threads:
  1826. print(f"Dangling thread: {thread!r}", file=sys.stderr)
  1827. sys.stderr.flush()
  1828. # Don't hold references to threads
  1829. dangling_threads = None
  1830. values = None
  1831. time.sleep(0.01)
  1832. gc_collect()
  1833. def reap_threads(func):
  1834. """Use this function when threads are being used. This will
  1835. ensure that the threads are cleaned up even when the test fails.
  1836. """
  1837. @functools.wraps(func)
  1838. def decorator(*args):
  1839. key = threading_setup()
  1840. try:
  1841. return func(*args)
  1842. finally:
  1843. threading_cleanup(*key)
  1844. return decorator
  1845. @contextlib.contextmanager
  1846. def wait_threads_exit(timeout=60.0):
  1847. """
  1848. bpo-31234: Context manager to wait until all threads created in the with
  1849. statement exit.
  1850. Use _thread.count() to check if threads exited. Indirectly, wait until
  1851. threads exit the internal t_bootstrap() C function of the _thread module.
  1852. threading_setup() and threading_cleanup() are designed to emit a warning
  1853. if a test leaves running threads in the background. This context manager
  1854. is designed to cleanup threads started by the _thread.start_new_thread()
  1855. which doesn't allow to wait for thread exit, whereas thread.Thread has a
  1856. join() method.
  1857. """
  1858. old_count = _thread._count()
  1859. try:
  1860. yield
  1861. finally:
  1862. start_time = time.monotonic()
  1863. deadline = start_time + timeout
  1864. while True:
  1865. count = _thread._count()
  1866. if count <= old_count:
  1867. break
  1868. if time.monotonic() > deadline:
  1869. dt = time.monotonic() - start_time
  1870. msg = (f"wait_threads() failed to cleanup {count - old_count} "
  1871. f"threads after {dt:.1f} seconds "
  1872. f"(count: {count}, old count: {old_count})")
  1873. raise AssertionError(msg)
  1874. time.sleep(0.010)
  1875. gc_collect()
  1876. def join_thread(thread, timeout=30.0):
  1877. """Join a thread. Raise an AssertionError if the thread is still alive
  1878. after timeout seconds.
  1879. """
  1880. thread.join(timeout)
  1881. if thread.is_alive():
  1882. msg = f"failed to join the thread in {timeout:.1f} seconds"
  1883. raise AssertionError(msg)
  1884. def reap_children():
  1885. """Use this function at the end of test_main() whenever sub-processes
  1886. are started. This will help ensure that no extra children (zombies)
  1887. stick around to hog resources and create problems when looking
  1888. for refleaks.
  1889. """
  1890. global environment_altered
  1891. # Need os.waitpid(-1, os.WNOHANG): Windows is not supported
  1892. if not (hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG')):
  1893. return
  1894. # Reap all our dead child processes so we don't leave zombies around.
  1895. # These hog resources and might be causing some of the buildbots to die.
  1896. while True:
  1897. try:
  1898. # Read the exit status of any child process which already completed
  1899. pid, status = os.waitpid(-1, os.WNOHANG)
  1900. except OSError:
  1901. break
  1902. if pid == 0:
  1903. break
  1904. print("Warning -- reap_children() reaped child process %s"
  1905. % pid, file=sys.stderr)
  1906. environment_altered = True
  1907. @contextlib.contextmanager
  1908. def start_threads(threads, unlock=None):
  1909. threads = list(threads)
  1910. started = []
  1911. try:
  1912. try:
  1913. for t in threads:
  1914. t.start()
  1915. started.append(t)
  1916. except:
  1917. if verbose:
  1918. print("Can't start %d threads, only %d threads started" %
  1919. (len(threads), len(started)))
  1920. raise
  1921. yield
  1922. finally:
  1923. try:
  1924. if unlock:
  1925. unlock()
  1926. endtime = starttime = time.monotonic()
  1927. for timeout in range(1, 16):
  1928. endtime += 60
  1929. for t in started:
  1930. t.join(max(endtime - time.monotonic(), 0.01))
  1931. started = [t for t in started if t.is_alive()]
  1932. if not started:
  1933. break
  1934. if verbose:
  1935. print('Unable to join %d threads during a period of '
  1936. '%d minutes' % (len(started), timeout))
  1937. finally:
  1938. started = [t for t in started if t.is_alive()]
  1939. if started:
  1940. faulthandler.dump_traceback(sys.stdout)
  1941. raise AssertionError('Unable to join %d threads' % len(started))
  1942. @contextlib.contextmanager
  1943. def swap_attr(obj, attr, new_val):
  1944. """Temporary swap out an attribute with a new object.
  1945. Usage:
  1946. with swap_attr(obj, "attr", 5):
  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. The old value (or None if it doesn't exist) will be assigned to the
  1953. target of the "as" clause, if there is one.
  1954. """
  1955. if hasattr(obj, attr):
  1956. real_val = getattr(obj, attr)
  1957. setattr(obj, attr, new_val)
  1958. try:
  1959. yield real_val
  1960. finally:
  1961. setattr(obj, attr, real_val)
  1962. else:
  1963. setattr(obj, attr, new_val)
  1964. try:
  1965. yield
  1966. finally:
  1967. if hasattr(obj, attr):
  1968. delattr(obj, attr)
  1969. @contextlib.contextmanager
  1970. def swap_item(obj, item, new_val):
  1971. """Temporary swap out an item with a new object.
  1972. Usage:
  1973. with swap_item(obj, "item", 5):
  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. The old value (or None if it doesn't exist) will be assigned to the
  1980. target of the "as" clause, if there is one.
  1981. """
  1982. if item in obj:
  1983. real_val = obj[item]
  1984. obj[item] = new_val
  1985. try:
  1986. yield real_val
  1987. finally:
  1988. obj[item] = real_val
  1989. else:
  1990. obj[item] = new_val
  1991. try:
  1992. yield
  1993. finally:
  1994. if item in obj:
  1995. del obj[item]
  1996. def strip_python_stderr(stderr):
  1997. """Strip the stderr of a Python process from potential debug output
  1998. emitted by the interpreter.
  1999. This will typically be run on the result of the communicate() method
  2000. of a subprocess.Popen object.
  2001. """
  2002. stderr = re.sub(br"\[\d+ refs, \d+ blocks\]\r?\n?", b"", stderr).strip()
  2003. return stderr
  2004. requires_type_collecting = unittest.skipIf(hasattr(sys, 'getcounts'),
  2005. 'types are immortal if COUNT_ALLOCS is defined')
  2006. def args_from_interpreter_flags():
  2007. """Return a list of command-line arguments reproducing the current
  2008. settings in sys.flags and sys.warnoptions."""
  2009. return subprocess._args_from_interpreter_flags()
  2010. def optim_args_from_interpreter_flags():
  2011. """Return a list of command-line arguments reproducing the current
  2012. optimization settings in sys.flags."""
  2013. return subprocess._optim_args_from_interpreter_flags()
  2014. #============================================================
  2015. # Support for assertions about logging.
  2016. #============================================================
  2017. class TestHandler(logging.handlers.BufferingHandler):
  2018. def __init__(self, matcher):
  2019. # BufferingHandler takes a "capacity" argument
  2020. # so as to know when to flush. As we're overriding
  2021. # shouldFlush anyway, we can set a capacity of zero.
  2022. # You can call flush() manually to clear out the
  2023. # buffer.
  2024. logging.handlers.BufferingHandler.__init__(self, 0)
  2025. self.matcher = matcher
  2026. def shouldFlush(self):
  2027. return False
  2028. def emit(self, record):
  2029. self.format(record)
  2030. self.buffer.append(record.__dict__)
  2031. def matches(self, **kwargs):
  2032. """
  2033. Look for a saved dict whose keys/values match the supplied arguments.
  2034. """
  2035. result = False
  2036. for d in self.buffer:
  2037. if self.matcher.matches(d, **kwargs):
  2038. result = True
  2039. break
  2040. return result
  2041. class Matcher(object):
  2042. _partial_matches = ('msg', 'message')
  2043. def matches(self, d, **kwargs):
  2044. """
  2045. Try to match a single dict with the supplied arguments.
  2046. Keys whose values are strings and which are in self._partial_matches
  2047. will be checked for partial (i.e. substring) matches. You can extend
  2048. this scheme to (for example) do regular expression matching, etc.
  2049. """
  2050. result = True
  2051. for k in kwargs:
  2052. v = kwargs[k]
  2053. dv = d.get(k)
  2054. if not self.match_value(k, dv, v):
  2055. result = False
  2056. break
  2057. return result
  2058. def match_value(self, k, dv, v):
  2059. """
  2060. Try to match a single stored value (dv) with a supplied value (v).
  2061. """
  2062. if type(v) != type(dv):
  2063. result = False
  2064. elif type(dv) is not str or k not in self._partial_matches:
  2065. result = (v == dv)
  2066. else:
  2067. result = dv.find(v) >= 0
  2068. return result
  2069. _can_symlink = None
  2070. def can_symlink():
  2071. global _can_symlink
  2072. if _can_symlink is not None:
  2073. return _can_symlink
  2074. symlink_path = TESTFN + "can_symlink"
  2075. try:
  2076. os.symlink(TESTFN, symlink_path)
  2077. can = True
  2078. except (OSError, NotImplementedError, AttributeError):
  2079. can = False
  2080. else:
  2081. os.remove(symlink_path)
  2082. _can_symlink = can
  2083. return can
  2084. def skip_unless_symlink(test):
  2085. """Skip decorator for tests that require functional symlink"""
  2086. ok = can_symlink()
  2087. msg = "Requires functional symlink implementation"
  2088. return test if ok else unittest.skip(msg)(test)
  2089. _can_xattr = None
  2090. def can_xattr():
  2091. global _can_xattr
  2092. if _can_xattr is not None:
  2093. return _can_xattr
  2094. if not hasattr(os, "setxattr"):
  2095. can = False
  2096. else:
  2097. tmp_dir = tempfile.mkdtemp()
  2098. tmp_fp, tmp_name = tempfile.mkstemp(dir=tmp_dir)
  2099. try:
  2100. with open(TESTFN, "wb") as fp:
  2101. try:
  2102. # TESTFN & tempfile may use different file systems with
  2103. # different capabilities
  2104. os.setxattr(tmp_fp, b"user.test", b"")
  2105. os.setxattr(tmp_name, b"trusted.foo", b"42")
  2106. os.setxattr(fp.fileno(), b"user.test", b"")
  2107. # Kernels < 2.6.39 don't respect setxattr flags.
  2108. kernel_version = platform.release()
  2109. m = re.match(r"2.6.(\d{1,2})", kernel_version)
  2110. can = m is None or int(m.group(1)) >= 39
  2111. except OSError:
  2112. can = False
  2113. finally:
  2114. unlink(TESTFN)
  2115. unlink(tmp_name)
  2116. rmdir(tmp_dir)
  2117. _can_xattr = can
  2118. return can
  2119. def skip_unless_xattr(test):
  2120. """Skip decorator for tests that require functional extended attributes"""
  2121. ok = can_xattr()
  2122. msg = "no non-broken extended attribute support"
  2123. return test if ok else unittest.skip(msg)(test)
  2124. _bind_nix_socket_error = None
  2125. def skip_unless_bind_unix_socket(test):
  2126. """Decorator for tests requiring a functional bind() for unix sockets."""
  2127. if not hasattr(socket, 'AF_UNIX'):
  2128. return unittest.skip('No UNIX Sockets')(test)
  2129. global _bind_nix_socket_error
  2130. if _bind_nix_socket_error is None:
  2131. path = TESTFN + "can_bind_unix_socket"
  2132. with socket.socket(socket.AF_UNIX) as sock:
  2133. try:
  2134. sock.bind(path)
  2135. _bind_nix_socket_error = False
  2136. except OSError as e:
  2137. _bind_nix_socket_error = e
  2138. finally:
  2139. unlink(path)
  2140. if _bind_nix_socket_error:
  2141. msg = 'Requires a functional unix bind(): %s' % _bind_nix_socket_error
  2142. return unittest.skip(msg)(test)
  2143. else:
  2144. return test
  2145. def fs_is_case_insensitive(directory):
  2146. """Detects if the file system for the specified directory is case-insensitive."""
  2147. with tempfile.NamedTemporaryFile(dir=directory) as base:
  2148. base_path = base.name
  2149. case_path = base_path.upper()
  2150. if case_path == base_path:
  2151. case_path = base_path.lower()
  2152. try:
  2153. return os.path.samefile(base_path, case_path)
  2154. except FileNotFoundError:
  2155. return False
  2156. def detect_api_mismatch(ref_api, other_api, *, ignore=()):
  2157. """Returns the set of items in ref_api not in other_api, except for a
  2158. defined list of items to be ignored in this check.
  2159. By default this skips private attributes beginning with '_' but
  2160. includes all magic methods, i.e. those starting and ending in '__'.
  2161. """
  2162. missing_items = set(dir(ref_api)) - set(dir(other_api))
  2163. if ignore:
  2164. missing_items -= set(ignore)
  2165. missing_items = set(m for m in missing_items
  2166. if not m.startswith('_') or m.endswith('__'))
  2167. return missing_items
  2168. def check__all__(test_case, module, name_of_module=None, extra=(),
  2169. blacklist=()):
  2170. """Assert that the __all__ variable of 'module' contains all public names.
  2171. The module's public names (its API) are detected automatically based on
  2172. whether they match the public name convention and were defined in
  2173. 'module'.
  2174. The 'name_of_module' argument can specify (as a string or tuple thereof)
  2175. what module(s) an API could be defined in in order to be detected as a
  2176. public API. One case for this is when 'module' imports part of its public
  2177. API from other modules, possibly a C backend (like 'csv' and its '_csv').
  2178. The 'extra' argument can be a set of names that wouldn't otherwise be
  2179. automatically detected as "public", like objects without a proper
  2180. '__module__' attribute. If provided, it will be added to the
  2181. automatically detected ones.
  2182. The 'blacklist' argument can be a set of names that must not be treated
  2183. as part of the public API even though their names indicate otherwise.
  2184. Usage:
  2185. import bar
  2186. import foo
  2187. import unittest
  2188. from test import support
  2189. class MiscTestCase(unittest.TestCase):
  2190. def test__all__(self):
  2191. support.check__all__(self, foo)
  2192. class OtherTestCase(unittest.TestCase):
  2193. def test__all__(self):
  2194. extra = {'BAR_CONST', 'FOO_CONST'}
  2195. blacklist = {'baz'} # Undocumented name.
  2196. # bar imports part of its API from _bar.
  2197. support.check__all__(self, bar, ('bar', '_bar'),
  2198. extra=extra, blacklist=blacklist)
  2199. """
  2200. if name_of_module is None:
  2201. name_of_module = (module.__name__, )
  2202. elif isinstance(name_of_module, str):
  2203. name_of_module = (name_of_module, )
  2204. expected = set(extra)
  2205. for name in dir(module):
  2206. if name.startswith('_') or name in blacklist:
  2207. continue
  2208. obj = getattr(module, name)
  2209. if (getattr(obj, '__module__', None) in name_of_module or
  2210. (not hasattr(obj, '__module__') and
  2211. not isinstance(obj, types.ModuleType))):
  2212. expected.add(name)
  2213. test_case.assertCountEqual(module.__all__, expected)
  2214. class SuppressCrashReport:
  2215. """Try to prevent a crash report from popping up.
  2216. On Windows, don't display the Windows Error Reporting dialog. On UNIX,
  2217. disable the creation of coredump file.
  2218. """
  2219. old_value = None
  2220. old_modes = None
  2221. def __enter__(self):
  2222. """On Windows, disable Windows Error Reporting dialogs using
  2223. SetErrorMode.
  2224. On UNIX, try to save the previous core file size limit, then set
  2225. soft limit to 0.
  2226. """
  2227. if sys.platform.startswith('win'):
  2228. # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
  2229. # GetErrorMode is not available on Windows XP and Windows Server 2003,
  2230. # but SetErrorMode returns the previous value, so we can use that
  2231. import ctypes
  2232. self._k32 = ctypes.windll.kernel32
  2233. SEM_NOGPFAULTERRORBOX = 0x02
  2234. self.old_value = self._k32.SetErrorMode(SEM_NOGPFAULTERRORBOX)
  2235. self._k32.SetErrorMode(self.old_value | SEM_NOGPFAULTERRORBOX)
  2236. # Suppress assert dialogs in debug builds
  2237. # (see http://bugs.python.org/issue23314)
  2238. try:
  2239. import msvcrt
  2240. msvcrt.CrtSetReportMode
  2241. except (AttributeError, ImportError):
  2242. # no msvcrt or a release build
  2243. pass
  2244. else:
  2245. self.old_modes = {}
  2246. for report_type in [msvcrt.CRT_WARN,
  2247. msvcrt.CRT_ERROR,
  2248. msvcrt.CRT_ASSERT]:
  2249. old_mode = msvcrt.CrtSetReportMode(report_type,
  2250. msvcrt.CRTDBG_MODE_FILE)
  2251. old_file = msvcrt.CrtSetReportFile(report_type,
  2252. msvcrt.CRTDBG_FILE_STDERR)
  2253. self.old_modes[report_type] = old_mode, old_file
  2254. else:
  2255. if resource is not None:
  2256. try:
  2257. self.old_value = resource.getrlimit(resource.RLIMIT_CORE)
  2258. resource.setrlimit(resource.RLIMIT_CORE,
  2259. (0, self.old_value[1]))
  2260. except (ValueError, OSError):
  2261. pass
  2262. if sys.platform == 'darwin':
  2263. # Check if the 'Crash Reporter' on OSX was configured
  2264. # in 'Developer' mode and warn that it will get triggered
  2265. # when it is.
  2266. #
  2267. # This assumes that this context manager is used in tests
  2268. # that might trigger the next manager.
  2269. cmd = ['/usr/bin/defaults', 'read',
  2270. 'com.apple.CrashReporter', 'DialogType']
  2271. proc = subprocess.Popen(cmd,
  2272. stdout=subprocess.PIPE,
  2273. stderr=subprocess.PIPE)
  2274. with proc:
  2275. stdout = proc.communicate()[0]
  2276. if stdout.strip() == b'developer':
  2277. print("this test triggers the Crash Reporter, "
  2278. "that is intentional", end='', flush=True)
  2279. return self
  2280. def __exit__(self, *ignore_exc):
  2281. """Restore Windows ErrorMode or core file behavior to initial value."""
  2282. if self.old_value is None:
  2283. return
  2284. if sys.platform.startswith('win'):
  2285. self._k32.SetErrorMode(self.old_value)
  2286. if self.old_modes:
  2287. import msvcrt
  2288. for report_type, (old_mode, old_file) in self.old_modes.items():
  2289. msvcrt.CrtSetReportMode(report_type, old_mode)
  2290. msvcrt.CrtSetReportFile(report_type, old_file)
  2291. else:
  2292. if resource is not None:
  2293. try:
  2294. resource.setrlimit(resource.RLIMIT_CORE, self.old_value)
  2295. except (ValueError, OSError):
  2296. pass
  2297. def patch(test_instance, object_to_patch, attr_name, new_value):
  2298. """Override 'object_to_patch'.'attr_name' with 'new_value'.
  2299. Also, add a cleanup procedure to 'test_instance' to restore
  2300. 'object_to_patch' value for 'attr_name'.
  2301. The 'attr_name' should be a valid attribute for 'object_to_patch'.
  2302. """
  2303. # check that 'attr_name' is a real attribute for 'object_to_patch'
  2304. # will raise AttributeError if it does not exist
  2305. getattr(object_to_patch, attr_name)
  2306. # keep a copy of the old value
  2307. attr_is_local = False
  2308. try:
  2309. old_value = object_to_patch.__dict__[attr_name]
  2310. except (AttributeError, KeyError):
  2311. old_value = getattr(object_to_patch, attr_name, None)
  2312. else:
  2313. attr_is_local = True
  2314. # restore the value when the test is done
  2315. def cleanup():
  2316. if attr_is_local:
  2317. setattr(object_to_patch, attr_name, old_value)
  2318. else:
  2319. delattr(object_to_patch, attr_name)
  2320. test_instance.addCleanup(cleanup)
  2321. # actually override the attribute
  2322. setattr(object_to_patch, attr_name, new_value)
  2323. def run_in_subinterp(code):
  2324. """
  2325. Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
  2326. module is enabled.
  2327. """
  2328. # Issue #10915, #15751: PyGILState_*() functions don't work with
  2329. # sub-interpreters, the tracemalloc module uses these functions internally
  2330. try:
  2331. import tracemalloc
  2332. except ImportError:
  2333. pass
  2334. else:
  2335. if tracemalloc.is_tracing():
  2336. raise unittest.SkipTest("run_in_subinterp() cannot be used "
  2337. "if tracemalloc module is tracing "
  2338. "memory allocations")
  2339. import _testcapi
  2340. return _testcapi.run_in_subinterp(code)
  2341. def check_free_after_iterating(test, iter, cls, args=()):
  2342. class A(cls):
  2343. def __del__(self):
  2344. nonlocal done
  2345. done = True
  2346. try:
  2347. next(it)
  2348. except StopIteration:
  2349. pass
  2350. done = False
  2351. it = iter(A(*args))
  2352. # Issue 26494: Shouldn't crash
  2353. test.assertRaises(StopIteration, next, it)
  2354. # The sequence should be deallocated just after the end of iterating
  2355. gc_collect()
  2356. test.assertTrue(done)
  2357. def missing_compiler_executable(cmd_names=[]):
  2358. """Check if the compiler components used to build the interpreter exist.
  2359. Check for the existence of the compiler executables whose names are listed
  2360. in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
  2361. and return the first missing executable or None when none is found
  2362. missing.
  2363. """
  2364. from distutils import ccompiler, sysconfig, spawn
  2365. compiler = ccompiler.new_compiler()
  2366. sysconfig.customize_compiler(compiler)
  2367. for name in compiler.executables:
  2368. if cmd_names and name not in cmd_names:
  2369. continue
  2370. cmd = getattr(compiler, name)
  2371. if cmd_names:
  2372. assert cmd is not None, \
  2373. "the '%s' executable is not configured" % name
  2374. elif cmd is None:
  2375. continue
  2376. if spawn.find_executable(cmd[0]) is None:
  2377. return cmd[0]
  2378. _is_android_emulator = None
  2379. def setswitchinterval(interval):
  2380. # Setting a very low gil interval on the Android emulator causes python
  2381. # to hang (issue #26939).
  2382. minimum_interval = 1e-5
  2383. if is_android and interval < minimum_interval:
  2384. global _is_android_emulator
  2385. if _is_android_emulator is None:
  2386. _is_android_emulator = (subprocess.check_output(
  2387. ['getprop', 'ro.kernel.qemu']).strip() == b'1')
  2388. if _is_android_emulator:
  2389. interval = minimum_interval
  2390. return sys.setswitchinterval(interval)
  2391. @contextlib.contextmanager
  2392. def disable_faulthandler():
  2393. # use sys.__stderr__ instead of sys.stderr, since regrtest replaces
  2394. # sys.stderr with a StringIO which has no file descriptor when a test
  2395. # is run with -W/--verbose3.
  2396. fd = sys.__stderr__.fileno()
  2397. is_enabled = faulthandler.is_enabled()
  2398. try:
  2399. faulthandler.disable()
  2400. yield
  2401. finally:
  2402. if is_enabled:
  2403. faulthandler.enable(file=fd, all_threads=True)
  2404. def fd_count():
  2405. """Count the number of open file descriptors.
  2406. """
  2407. if sys.platform.startswith(('linux', 'freebsd')):
  2408. try:
  2409. names = os.listdir("/proc/self/fd")
  2410. # Subtract one because listdir() internally opens a file
  2411. # descriptor to list the content of the /proc/self/fd/ directory.
  2412. return len(names) - 1
  2413. except FileNotFoundError:
  2414. pass
  2415. MAXFD = 256
  2416. if hasattr(os, 'sysconf'):
  2417. try:
  2418. MAXFD = os.sysconf("SC_OPEN_MAX")
  2419. except OSError:
  2420. pass
  2421. old_modes = None
  2422. if sys.platform == 'win32':
  2423. # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
  2424. # on invalid file descriptor if Python is compiled in debug mode
  2425. try:
  2426. import msvcrt
  2427. msvcrt.CrtSetReportMode
  2428. except (AttributeError, ImportError):
  2429. # no msvcrt or a release build
  2430. pass
  2431. else:
  2432. old_modes = {}
  2433. for report_type in (msvcrt.CRT_WARN,
  2434. msvcrt.CRT_ERROR,
  2435. msvcrt.CRT_ASSERT):
  2436. old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0)
  2437. try:
  2438. count = 0
  2439. for fd in range(MAXFD):
  2440. try:
  2441. # Prefer dup() over fstat(). fstat() can require input/output
  2442. # whereas dup() doesn't.
  2443. fd2 = os.dup(fd)
  2444. except OSError as e:
  2445. if e.errno != errno.EBADF:
  2446. raise
  2447. else:
  2448. os.close(fd2)
  2449. count += 1
  2450. finally:
  2451. if old_modes is not None:
  2452. for report_type in (msvcrt.CRT_WARN,
  2453. msvcrt.CRT_ERROR,
  2454. msvcrt.CRT_ASSERT):
  2455. msvcrt.CrtSetReportMode(report_type, old_modes[report_type])
  2456. return count
  2457. class SaveSignals:
  2458. """
  2459. Save an restore signal handlers.
  2460. This class is only able to save/restore signal handlers registered
  2461. by the Python signal module: see bpo-13285 for "external" signal
  2462. handlers.
  2463. """
  2464. def __init__(self):
  2465. import signal
  2466. self.signal = signal
  2467. self.signals = list(range(1, signal.NSIG))
  2468. # SIGKILL and SIGSTOP signals cannot be ignored nor caught
  2469. for signame in ('SIGKILL', 'SIGSTOP'):
  2470. try:
  2471. signum = getattr(signal, signame)
  2472. except AttributeError:
  2473. continue
  2474. self.signals.remove(signum)
  2475. self.handlers = {}
  2476. def save(self):
  2477. for signum in self.signals:
  2478. handler = self.signal.getsignal(signum)
  2479. if handler is None:
  2480. # getsignal() returns None if a signal handler was not
  2481. # registered by the Python signal module,
  2482. # and the handler is not SIG_DFL nor SIG_IGN.
  2483. #
  2484. # Ignore the signal: we cannot restore the handler.
  2485. continue
  2486. self.handlers[signum] = handler
  2487. def restore(self):
  2488. for signum, handler in self.handlers.items():
  2489. self.signal.signal(signum, handler)
  2490. def with_pymalloc():
  2491. import _testcapi
  2492. return _testcapi.WITH_PYMALLOC
  2493. class FakePath:
  2494. """Simple implementing of the path protocol.
  2495. """
  2496. def __init__(self, path):
  2497. self.path = path
  2498. def __repr__(self):
  2499. return f'<FakePath {self.path!r}>'
  2500. def __fspath__(self):
  2501. if (isinstance(self.path, BaseException) or
  2502. isinstance(self.path, type) and
  2503. issubclass(self.path, BaseException)):
  2504. raise self.path
  2505. else:
  2506. return self.path
  2507. class _ALWAYS_EQ:
  2508. """
  2509. Object that is equal to anything.
  2510. """
  2511. def __eq__(self, other):
  2512. return True
  2513. def __ne__(self, other):
  2514. return False
  2515. ALWAYS_EQ = _ALWAYS_EQ()
  2516. @functools.total_ordering
  2517. class _LARGEST:
  2518. """
  2519. Object that is greater than anything (except itself).
  2520. """
  2521. def __eq__(self, other):
  2522. return isinstance(other, _LARGEST)
  2523. def __lt__(self, other):
  2524. return False
  2525. LARGEST = _LARGEST()
  2526. @functools.total_ordering
  2527. class _SMALLEST:
  2528. """
  2529. Object that is less than anything (except itself).
  2530. """
  2531. def __eq__(self, other):
  2532. return isinstance(other, _SMALLEST)
  2533. def __gt__(self, other):
  2534. return False
  2535. SMALLEST = _SMALLEST()