test_regrtest.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. """
  2. Tests of regrtest.py.
  3. Note: test_regrtest cannot be run twice in parallel.
  4. """
  5. import contextlib
  6. import glob
  7. import io
  8. import os.path
  9. import platform
  10. import re
  11. import subprocess
  12. import sys
  13. import sysconfig
  14. import tempfile
  15. import textwrap
  16. import time
  17. import unittest
  18. from test import libregrtest
  19. from test import support
  20. from test.support import os_helper
  21. from test.libregrtest import utils, setup
  22. if not support.has_subprocess_support:
  23. raise unittest.SkipTest("test module requires subprocess")
  24. Py_DEBUG = hasattr(sys, 'gettotalrefcount')
  25. ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..')
  26. ROOT_DIR = os.path.abspath(os.path.normpath(ROOT_DIR))
  27. LOG_PREFIX = r'[0-9]+:[0-9]+:[0-9]+ (?:load avg: [0-9]+\.[0-9]{2} )?'
  28. TEST_INTERRUPTED = textwrap.dedent("""
  29. from signal import SIGINT, raise_signal
  30. try:
  31. raise_signal(SIGINT)
  32. except ImportError:
  33. import os
  34. os.kill(os.getpid(), SIGINT)
  35. """)
  36. class ParseArgsTestCase(unittest.TestCase):
  37. """
  38. Test regrtest's argument parsing, function _parse_args().
  39. """
  40. def checkError(self, args, msg):
  41. with support.captured_stderr() as err, self.assertRaises(SystemExit):
  42. libregrtest._parse_args(args)
  43. self.assertIn(msg, err.getvalue())
  44. def test_help(self):
  45. for opt in '-h', '--help':
  46. with self.subTest(opt=opt):
  47. with support.captured_stdout() as out, \
  48. self.assertRaises(SystemExit):
  49. libregrtest._parse_args([opt])
  50. self.assertIn('Run Python regression tests.', out.getvalue())
  51. def test_timeout(self):
  52. ns = libregrtest._parse_args(['--timeout', '4.2'])
  53. self.assertEqual(ns.timeout, 4.2)
  54. self.checkError(['--timeout'], 'expected one argument')
  55. self.checkError(['--timeout', 'foo'], 'invalid float value')
  56. def test_wait(self):
  57. ns = libregrtest._parse_args(['--wait'])
  58. self.assertTrue(ns.wait)
  59. def test_worker_args(self):
  60. ns = libregrtest._parse_args(['--worker-args', '[[], {}]'])
  61. self.assertEqual(ns.worker_args, '[[], {}]')
  62. self.checkError(['--worker-args'], 'expected one argument')
  63. def test_start(self):
  64. for opt in '-S', '--start':
  65. with self.subTest(opt=opt):
  66. ns = libregrtest._parse_args([opt, 'foo'])
  67. self.assertEqual(ns.start, 'foo')
  68. self.checkError([opt], 'expected one argument')
  69. def test_verbose(self):
  70. ns = libregrtest._parse_args(['-v'])
  71. self.assertEqual(ns.verbose, 1)
  72. ns = libregrtest._parse_args(['-vvv'])
  73. self.assertEqual(ns.verbose, 3)
  74. ns = libregrtest._parse_args(['--verbose'])
  75. self.assertEqual(ns.verbose, 1)
  76. ns = libregrtest._parse_args(['--verbose'] * 3)
  77. self.assertEqual(ns.verbose, 3)
  78. ns = libregrtest._parse_args([])
  79. self.assertEqual(ns.verbose, 0)
  80. def test_verbose2(self):
  81. for opt in '-w', '--verbose2':
  82. with self.subTest(opt=opt):
  83. ns = libregrtest._parse_args([opt])
  84. self.assertTrue(ns.verbose2)
  85. def test_verbose3(self):
  86. for opt in '-W', '--verbose3':
  87. with self.subTest(opt=opt):
  88. ns = libregrtest._parse_args([opt])
  89. self.assertTrue(ns.verbose3)
  90. def test_quiet(self):
  91. for opt in '-q', '--quiet':
  92. with self.subTest(opt=opt):
  93. ns = libregrtest._parse_args([opt])
  94. self.assertTrue(ns.quiet)
  95. self.assertEqual(ns.verbose, 0)
  96. def test_slowest(self):
  97. for opt in '-o', '--slowest':
  98. with self.subTest(opt=opt):
  99. ns = libregrtest._parse_args([opt])
  100. self.assertTrue(ns.print_slow)
  101. def test_header(self):
  102. ns = libregrtest._parse_args(['--header'])
  103. self.assertTrue(ns.header)
  104. ns = libregrtest._parse_args(['--verbose'])
  105. self.assertTrue(ns.header)
  106. def test_randomize(self):
  107. for opt in '-r', '--randomize':
  108. with self.subTest(opt=opt):
  109. ns = libregrtest._parse_args([opt])
  110. self.assertTrue(ns.randomize)
  111. def test_randseed(self):
  112. ns = libregrtest._parse_args(['--randseed', '12345'])
  113. self.assertEqual(ns.random_seed, 12345)
  114. self.assertTrue(ns.randomize)
  115. self.checkError(['--randseed'], 'expected one argument')
  116. self.checkError(['--randseed', 'foo'], 'invalid int value')
  117. def test_fromfile(self):
  118. for opt in '-f', '--fromfile':
  119. with self.subTest(opt=opt):
  120. ns = libregrtest._parse_args([opt, 'foo'])
  121. self.assertEqual(ns.fromfile, 'foo')
  122. self.checkError([opt], 'expected one argument')
  123. self.checkError([opt, 'foo', '-s'], "don't go together")
  124. def test_exclude(self):
  125. for opt in '-x', '--exclude':
  126. with self.subTest(opt=opt):
  127. ns = libregrtest._parse_args([opt])
  128. self.assertTrue(ns.exclude)
  129. def test_single(self):
  130. for opt in '-s', '--single':
  131. with self.subTest(opt=opt):
  132. ns = libregrtest._parse_args([opt])
  133. self.assertTrue(ns.single)
  134. self.checkError([opt, '-f', 'foo'], "don't go together")
  135. def test_ignore(self):
  136. for opt in '-i', '--ignore':
  137. with self.subTest(opt=opt):
  138. ns = libregrtest._parse_args([opt, 'pattern'])
  139. self.assertEqual(ns.ignore_tests, ['pattern'])
  140. self.checkError([opt], 'expected one argument')
  141. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  142. with open(os_helper.TESTFN, "w") as fp:
  143. print('matchfile1', file=fp)
  144. print('matchfile2', file=fp)
  145. filename = os.path.abspath(os_helper.TESTFN)
  146. ns = libregrtest._parse_args(['-m', 'match',
  147. '--ignorefile', filename])
  148. self.assertEqual(ns.ignore_tests,
  149. ['matchfile1', 'matchfile2'])
  150. def test_match(self):
  151. for opt in '-m', '--match':
  152. with self.subTest(opt=opt):
  153. ns = libregrtest._parse_args([opt, 'pattern'])
  154. self.assertEqual(ns.match_tests, ['pattern'])
  155. self.checkError([opt], 'expected one argument')
  156. ns = libregrtest._parse_args(['-m', 'pattern1',
  157. '-m', 'pattern2'])
  158. self.assertEqual(ns.match_tests, ['pattern1', 'pattern2'])
  159. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  160. with open(os_helper.TESTFN, "w") as fp:
  161. print('matchfile1', file=fp)
  162. print('matchfile2', file=fp)
  163. filename = os.path.abspath(os_helper.TESTFN)
  164. ns = libregrtest._parse_args(['-m', 'match',
  165. '--matchfile', filename])
  166. self.assertEqual(ns.match_tests,
  167. ['match', 'matchfile1', 'matchfile2'])
  168. def test_failfast(self):
  169. for opt in '-G', '--failfast':
  170. with self.subTest(opt=opt):
  171. ns = libregrtest._parse_args([opt, '-v'])
  172. self.assertTrue(ns.failfast)
  173. ns = libregrtest._parse_args([opt, '-W'])
  174. self.assertTrue(ns.failfast)
  175. self.checkError([opt], '-G/--failfast needs either -v or -W')
  176. def test_use(self):
  177. for opt in '-u', '--use':
  178. with self.subTest(opt=opt):
  179. ns = libregrtest._parse_args([opt, 'gui,network'])
  180. self.assertEqual(ns.use_resources, ['gui', 'network'])
  181. ns = libregrtest._parse_args([opt, 'gui,none,network'])
  182. self.assertEqual(ns.use_resources, ['network'])
  183. expected = list(libregrtest.ALL_RESOURCES)
  184. expected.remove('gui')
  185. ns = libregrtest._parse_args([opt, 'all,-gui'])
  186. self.assertEqual(ns.use_resources, expected)
  187. self.checkError([opt], 'expected one argument')
  188. self.checkError([opt, 'foo'], 'invalid resource')
  189. # all + a resource not part of "all"
  190. ns = libregrtest._parse_args([opt, 'all,tzdata'])
  191. self.assertEqual(ns.use_resources,
  192. list(libregrtest.ALL_RESOURCES) + ['tzdata'])
  193. # test another resource which is not part of "all"
  194. ns = libregrtest._parse_args([opt, 'extralargefile'])
  195. self.assertEqual(ns.use_resources, ['extralargefile'])
  196. def test_memlimit(self):
  197. for opt in '-M', '--memlimit':
  198. with self.subTest(opt=opt):
  199. ns = libregrtest._parse_args([opt, '4G'])
  200. self.assertEqual(ns.memlimit, '4G')
  201. self.checkError([opt], 'expected one argument')
  202. def test_testdir(self):
  203. ns = libregrtest._parse_args(['--testdir', 'foo'])
  204. self.assertEqual(ns.testdir, os.path.join(os_helper.SAVEDCWD, 'foo'))
  205. self.checkError(['--testdir'], 'expected one argument')
  206. def test_runleaks(self):
  207. for opt in '-L', '--runleaks':
  208. with self.subTest(opt=opt):
  209. ns = libregrtest._parse_args([opt])
  210. self.assertTrue(ns.runleaks)
  211. def test_huntrleaks(self):
  212. for opt in '-R', '--huntrleaks':
  213. with self.subTest(opt=opt):
  214. ns = libregrtest._parse_args([opt, ':'])
  215. self.assertEqual(ns.huntrleaks, (5, 4, 'reflog.txt'))
  216. ns = libregrtest._parse_args([opt, '6:'])
  217. self.assertEqual(ns.huntrleaks, (6, 4, 'reflog.txt'))
  218. ns = libregrtest._parse_args([opt, ':3'])
  219. self.assertEqual(ns.huntrleaks, (5, 3, 'reflog.txt'))
  220. ns = libregrtest._parse_args([opt, '6:3:leaks.log'])
  221. self.assertEqual(ns.huntrleaks, (6, 3, 'leaks.log'))
  222. self.checkError([opt], 'expected one argument')
  223. self.checkError([opt, '6'],
  224. 'needs 2 or 3 colon-separated arguments')
  225. self.checkError([opt, 'foo:'], 'invalid huntrleaks value')
  226. self.checkError([opt, '6:foo'], 'invalid huntrleaks value')
  227. def test_multiprocess(self):
  228. for opt in '-j', '--multiprocess':
  229. with self.subTest(opt=opt):
  230. ns = libregrtest._parse_args([opt, '2'])
  231. self.assertEqual(ns.use_mp, 2)
  232. self.checkError([opt], 'expected one argument')
  233. self.checkError([opt, 'foo'], 'invalid int value')
  234. self.checkError([opt, '2', '-T'], "don't go together")
  235. self.checkError([opt, '0', '-T'], "don't go together")
  236. def test_coverage(self):
  237. for opt in '-T', '--coverage':
  238. with self.subTest(opt=opt):
  239. ns = libregrtest._parse_args([opt])
  240. self.assertTrue(ns.trace)
  241. def test_coverdir(self):
  242. for opt in '-D', '--coverdir':
  243. with self.subTest(opt=opt):
  244. ns = libregrtest._parse_args([opt, 'foo'])
  245. self.assertEqual(ns.coverdir,
  246. os.path.join(os_helper.SAVEDCWD, 'foo'))
  247. self.checkError([opt], 'expected one argument')
  248. def test_nocoverdir(self):
  249. for opt in '-N', '--nocoverdir':
  250. with self.subTest(opt=opt):
  251. ns = libregrtest._parse_args([opt])
  252. self.assertIsNone(ns.coverdir)
  253. def test_threshold(self):
  254. for opt in '-t', '--threshold':
  255. with self.subTest(opt=opt):
  256. ns = libregrtest._parse_args([opt, '1000'])
  257. self.assertEqual(ns.threshold, 1000)
  258. self.checkError([opt], 'expected one argument')
  259. self.checkError([opt, 'foo'], 'invalid int value')
  260. def test_nowindows(self):
  261. for opt in '-n', '--nowindows':
  262. with self.subTest(opt=opt):
  263. with contextlib.redirect_stderr(io.StringIO()) as stderr:
  264. ns = libregrtest._parse_args([opt])
  265. self.assertTrue(ns.nowindows)
  266. err = stderr.getvalue()
  267. self.assertIn('the --nowindows (-n) option is deprecated', err)
  268. def test_forever(self):
  269. for opt in '-F', '--forever':
  270. with self.subTest(opt=opt):
  271. ns = libregrtest._parse_args([opt])
  272. self.assertTrue(ns.forever)
  273. def test_unrecognized_argument(self):
  274. self.checkError(['--xxx'], 'usage:')
  275. def test_long_option__partial(self):
  276. ns = libregrtest._parse_args(['--qui'])
  277. self.assertTrue(ns.quiet)
  278. self.assertEqual(ns.verbose, 0)
  279. def test_two_options(self):
  280. ns = libregrtest._parse_args(['--quiet', '--exclude'])
  281. self.assertTrue(ns.quiet)
  282. self.assertEqual(ns.verbose, 0)
  283. self.assertTrue(ns.exclude)
  284. def test_option_with_empty_string_value(self):
  285. ns = libregrtest._parse_args(['--start', ''])
  286. self.assertEqual(ns.start, '')
  287. def test_arg(self):
  288. ns = libregrtest._parse_args(['foo'])
  289. self.assertEqual(ns.args, ['foo'])
  290. def test_option_and_arg(self):
  291. ns = libregrtest._parse_args(['--quiet', 'foo'])
  292. self.assertTrue(ns.quiet)
  293. self.assertEqual(ns.verbose, 0)
  294. self.assertEqual(ns.args, ['foo'])
  295. def test_arg_option_arg(self):
  296. ns = libregrtest._parse_args(['test_unaryop', '-v', 'test_binop'])
  297. self.assertEqual(ns.verbose, 1)
  298. self.assertEqual(ns.args, ['test_unaryop', 'test_binop'])
  299. def test_unknown_option(self):
  300. self.checkError(['--unknown-option'],
  301. 'unrecognized arguments: --unknown-option')
  302. class BaseTestCase(unittest.TestCase):
  303. TEST_UNIQUE_ID = 1
  304. TESTNAME_PREFIX = 'test_regrtest_'
  305. TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+'
  306. def setUp(self):
  307. self.testdir = os.path.realpath(os.path.dirname(__file__))
  308. self.tmptestdir = tempfile.mkdtemp()
  309. self.addCleanup(os_helper.rmtree, self.tmptestdir)
  310. def create_test(self, name=None, code=None):
  311. if not name:
  312. name = 'noop%s' % BaseTestCase.TEST_UNIQUE_ID
  313. BaseTestCase.TEST_UNIQUE_ID += 1
  314. if code is None:
  315. code = textwrap.dedent("""
  316. import unittest
  317. class Tests(unittest.TestCase):
  318. def test_empty_test(self):
  319. pass
  320. """)
  321. # test_regrtest cannot be run twice in parallel because
  322. # of setUp() and create_test()
  323. name = self.TESTNAME_PREFIX + name
  324. path = os.path.join(self.tmptestdir, name + '.py')
  325. self.addCleanup(os_helper.unlink, path)
  326. # Use 'x' mode to ensure that we do not override existing tests
  327. try:
  328. with open(path, 'x', encoding='utf-8') as fp:
  329. fp.write(code)
  330. except PermissionError as exc:
  331. if not sysconfig.is_python_build():
  332. self.skipTest("cannot write %s: %s" % (path, exc))
  333. raise
  334. return name
  335. def regex_search(self, regex, output):
  336. match = re.search(regex, output, re.MULTILINE)
  337. if not match:
  338. self.fail("%r not found in %r" % (regex, output))
  339. return match
  340. def check_line(self, output, regex):
  341. regex = re.compile(r'^' + regex, re.MULTILINE)
  342. self.assertRegex(output, regex)
  343. def parse_executed_tests(self, output):
  344. regex = (r'^%s\[ *[0-9]+(?:/ *[0-9]+)*\] (%s)'
  345. % (LOG_PREFIX, self.TESTNAME_REGEX))
  346. parser = re.finditer(regex, output, re.MULTILINE)
  347. return list(match.group(1) for match in parser)
  348. def check_executed_tests(self, output, tests, skipped=(), failed=(),
  349. env_changed=(), omitted=(),
  350. rerun={}, no_test_ran=(),
  351. randomize=False, interrupted=False,
  352. fail_env_changed=False):
  353. if isinstance(tests, str):
  354. tests = [tests]
  355. if isinstance(skipped, str):
  356. skipped = [skipped]
  357. if isinstance(failed, str):
  358. failed = [failed]
  359. if isinstance(env_changed, str):
  360. env_changed = [env_changed]
  361. if isinstance(omitted, str):
  362. omitted = [omitted]
  363. if isinstance(no_test_ran, str):
  364. no_test_ran = [no_test_ran]
  365. executed = self.parse_executed_tests(output)
  366. if randomize:
  367. self.assertEqual(set(executed), set(tests), output)
  368. else:
  369. self.assertEqual(executed, tests, output)
  370. def plural(count):
  371. return 's' if count != 1 else ''
  372. def list_regex(line_format, tests):
  373. count = len(tests)
  374. names = ' '.join(sorted(tests))
  375. regex = line_format % (count, plural(count))
  376. regex = r'%s:\n %s$' % (regex, names)
  377. return regex
  378. if skipped:
  379. regex = list_regex('%s test%s skipped', skipped)
  380. self.check_line(output, regex)
  381. if failed:
  382. regex = list_regex('%s test%s failed', failed)
  383. self.check_line(output, regex)
  384. if env_changed:
  385. regex = list_regex('%s test%s altered the execution environment',
  386. env_changed)
  387. self.check_line(output, regex)
  388. if omitted:
  389. regex = list_regex('%s test%s omitted', omitted)
  390. self.check_line(output, regex)
  391. if rerun:
  392. regex = list_regex('%s re-run test%s', rerun.keys())
  393. self.check_line(output, regex)
  394. regex = LOG_PREFIX + r"Re-running failed tests in verbose mode"
  395. self.check_line(output, regex)
  396. for name, match in rerun.items():
  397. regex = LOG_PREFIX + f"Re-running {name} in verbose mode \\(matching: {match}\\)"
  398. self.check_line(output, regex)
  399. if no_test_ran:
  400. regex = list_regex('%s test%s run no tests', no_test_ran)
  401. self.check_line(output, regex)
  402. good = (len(tests) - len(skipped) - len(failed)
  403. - len(omitted) - len(env_changed) - len(no_test_ran))
  404. if good:
  405. regex = r'%s test%s OK\.$' % (good, plural(good))
  406. if not skipped and not failed and good > 1:
  407. regex = 'All %s' % regex
  408. self.check_line(output, regex)
  409. if interrupted:
  410. self.check_line(output, 'Test suite interrupted by signal SIGINT.')
  411. result = []
  412. if failed:
  413. result.append('FAILURE')
  414. elif fail_env_changed and env_changed:
  415. result.append('ENV CHANGED')
  416. if interrupted:
  417. result.append('INTERRUPTED')
  418. if not any((good, result, failed, interrupted, skipped,
  419. env_changed, fail_env_changed)):
  420. result.append("NO TEST RUN")
  421. elif not result:
  422. result.append('SUCCESS')
  423. result = ', '.join(result)
  424. if rerun:
  425. self.check_line(output, 'Tests result: FAILURE')
  426. result = 'FAILURE then %s' % result
  427. self.check_line(output, 'Tests result: %s' % result)
  428. def parse_random_seed(self, output):
  429. match = self.regex_search(r'Using random seed ([0-9]+)', output)
  430. randseed = int(match.group(1))
  431. self.assertTrue(0 <= randseed <= 10000000, randseed)
  432. return randseed
  433. def run_command(self, args, input=None, exitcode=0, **kw):
  434. if not input:
  435. input = ''
  436. if 'stderr' not in kw:
  437. kw['stderr'] = subprocess.STDOUT
  438. proc = subprocess.run(args,
  439. universal_newlines=True,
  440. input=input,
  441. stdout=subprocess.PIPE,
  442. **kw)
  443. if proc.returncode != exitcode:
  444. msg = ("Command %s failed with exit code %s\n"
  445. "\n"
  446. "stdout:\n"
  447. "---\n"
  448. "%s\n"
  449. "---\n"
  450. % (str(args), proc.returncode, proc.stdout))
  451. if proc.stderr:
  452. msg += ("\n"
  453. "stderr:\n"
  454. "---\n"
  455. "%s"
  456. "---\n"
  457. % proc.stderr)
  458. self.fail(msg)
  459. return proc
  460. def run_python(self, args, **kw):
  461. args = [sys.executable, '-X', 'faulthandler', '-I', *args]
  462. proc = self.run_command(args, **kw)
  463. return proc.stdout
  464. class CheckActualTests(BaseTestCase):
  465. def test_finds_expected_number_of_tests(self):
  466. """
  467. Check that regrtest appears to find the expected set of tests.
  468. """
  469. args = ['-Wd', '-E', '-bb', '-m', 'test.regrtest', '--list-tests']
  470. output = self.run_python(args)
  471. rough_number_of_tests_found = len(output.splitlines())
  472. actual_testsuite_glob = os.path.join(glob.escape(os.path.dirname(__file__)),
  473. 'test*.py')
  474. rough_counted_test_py_files = len(glob.glob(actual_testsuite_glob))
  475. # We're not trying to duplicate test finding logic in here,
  476. # just give a rough estimate of how many there should be and
  477. # be near that. This is a regression test to prevent mishaps
  478. # such as https://bugs.python.org/issue37667 in the future.
  479. # If you need to change the values in here during some
  480. # mythical future test suite reorganization, don't go
  481. # overboard with logic and keep that goal in mind.
  482. self.assertGreater(rough_number_of_tests_found,
  483. rough_counted_test_py_files*9//10,
  484. msg='Unexpectedly low number of tests found in:\n'
  485. f'{", ".join(output.splitlines())}')
  486. class ProgramsTestCase(BaseTestCase):
  487. """
  488. Test various ways to run the Python test suite. Use options close
  489. to options used on the buildbot.
  490. """
  491. NTEST = 4
  492. def setUp(self):
  493. super().setUp()
  494. # Create NTEST tests doing nothing
  495. self.tests = [self.create_test() for index in range(self.NTEST)]
  496. self.python_args = ['-Wd', '-E', '-bb']
  497. self.regrtest_args = ['-uall', '-rwW',
  498. '--testdir=%s' % self.tmptestdir]
  499. self.regrtest_args.extend(('--timeout', '3600', '-j4'))
  500. if sys.platform == 'win32':
  501. self.regrtest_args.append('-n')
  502. def check_output(self, output):
  503. self.parse_random_seed(output)
  504. self.check_executed_tests(output, self.tests, randomize=True)
  505. def run_tests(self, args):
  506. output = self.run_python(args)
  507. self.check_output(output)
  508. def test_script_regrtest(self):
  509. # Lib/test/regrtest.py
  510. script = os.path.join(self.testdir, 'regrtest.py')
  511. args = [*self.python_args, script, *self.regrtest_args, *self.tests]
  512. self.run_tests(args)
  513. def test_module_test(self):
  514. # -m test
  515. args = [*self.python_args, '-m', 'test',
  516. *self.regrtest_args, *self.tests]
  517. self.run_tests(args)
  518. def test_module_regrtest(self):
  519. # -m test.regrtest
  520. args = [*self.python_args, '-m', 'test.regrtest',
  521. *self.regrtest_args, *self.tests]
  522. self.run_tests(args)
  523. def test_module_autotest(self):
  524. # -m test.autotest
  525. args = [*self.python_args, '-m', 'test.autotest',
  526. *self.regrtest_args, *self.tests]
  527. self.run_tests(args)
  528. def test_module_from_test_autotest(self):
  529. # from test import autotest
  530. code = 'from test import autotest'
  531. args = [*self.python_args, '-c', code,
  532. *self.regrtest_args, *self.tests]
  533. self.run_tests(args)
  534. def test_script_autotest(self):
  535. # Lib/test/autotest.py
  536. script = os.path.join(self.testdir, 'autotest.py')
  537. args = [*self.python_args, script, *self.regrtest_args, *self.tests]
  538. self.run_tests(args)
  539. @unittest.skipUnless(sysconfig.is_python_build(),
  540. 'run_tests.py script is not installed')
  541. def test_tools_script_run_tests(self):
  542. # Tools/scripts/run_tests.py
  543. script = os.path.join(ROOT_DIR, 'Tools', 'scripts', 'run_tests.py')
  544. args = [script, *self.regrtest_args, *self.tests]
  545. self.run_tests(args)
  546. def run_batch(self, *args):
  547. proc = self.run_command(args)
  548. self.check_output(proc.stdout)
  549. @unittest.skipUnless(sysconfig.is_python_build(),
  550. 'test.bat script is not installed')
  551. @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
  552. def test_tools_buildbot_test(self):
  553. # Tools\buildbot\test.bat
  554. script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat')
  555. test_args = ['--testdir=%s' % self.tmptestdir]
  556. if platform.machine() == 'ARM64':
  557. test_args.append('-arm64') # ARM 64-bit build
  558. elif platform.machine() == 'ARM':
  559. test_args.append('-arm32') # 32-bit ARM build
  560. elif platform.architecture()[0] == '64bit':
  561. test_args.append('-x64') # 64-bit build
  562. if not Py_DEBUG:
  563. test_args.append('+d') # Release build, use python.exe
  564. self.run_batch(script, *test_args, *self.tests)
  565. @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
  566. def test_pcbuild_rt(self):
  567. # PCbuild\rt.bat
  568. script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat')
  569. if not os.path.isfile(script):
  570. self.skipTest(f'File "{script}" does not exist')
  571. rt_args = ["-q"] # Quick, don't run tests twice
  572. if platform.machine() == 'ARM64':
  573. rt_args.append('-arm64') # ARM 64-bit build
  574. elif platform.machine() == 'ARM':
  575. rt_args.append('-arm32') # 32-bit ARM build
  576. elif platform.architecture()[0] == '64bit':
  577. rt_args.append('-x64') # 64-bit build
  578. if Py_DEBUG:
  579. rt_args.append('-d') # Debug build, use python_d.exe
  580. self.run_batch(script, *rt_args, *self.regrtest_args, *self.tests)
  581. class ArgsTestCase(BaseTestCase):
  582. """
  583. Test arguments of the Python test suite.
  584. """
  585. def run_tests(self, *testargs, **kw):
  586. cmdargs = ['-m', 'test', '--testdir=%s' % self.tmptestdir, *testargs]
  587. return self.run_python(cmdargs, **kw)
  588. def test_failing_test(self):
  589. # test a failing test
  590. code = textwrap.dedent("""
  591. import unittest
  592. class FailingTest(unittest.TestCase):
  593. def test_failing(self):
  594. self.fail("bug")
  595. """)
  596. test_ok = self.create_test('ok')
  597. test_failing = self.create_test('failing', code=code)
  598. tests = [test_ok, test_failing]
  599. output = self.run_tests(*tests, exitcode=2)
  600. self.check_executed_tests(output, tests, failed=test_failing)
  601. def test_resources(self):
  602. # test -u command line option
  603. tests = {}
  604. for resource in ('audio', 'network'):
  605. code = textwrap.dedent("""
  606. from test import support; support.requires(%r)
  607. import unittest
  608. class PassingTest(unittest.TestCase):
  609. def test_pass(self):
  610. pass
  611. """ % resource)
  612. tests[resource] = self.create_test(resource, code)
  613. test_names = sorted(tests.values())
  614. # -u all: 2 resources enabled
  615. output = self.run_tests('-u', 'all', *test_names)
  616. self.check_executed_tests(output, test_names)
  617. # -u audio: 1 resource enabled
  618. output = self.run_tests('-uaudio', *test_names)
  619. self.check_executed_tests(output, test_names,
  620. skipped=tests['network'])
  621. # no option: 0 resources enabled
  622. output = self.run_tests(*test_names)
  623. self.check_executed_tests(output, test_names,
  624. skipped=test_names)
  625. def test_random(self):
  626. # test -r and --randseed command line option
  627. code = textwrap.dedent("""
  628. import random
  629. print("TESTRANDOM: %s" % random.randint(1, 1000))
  630. """)
  631. test = self.create_test('random', code)
  632. # first run to get the output with the random seed
  633. output = self.run_tests('-r', test)
  634. randseed = self.parse_random_seed(output)
  635. match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
  636. test_random = int(match.group(1))
  637. # try to reproduce with the random seed
  638. output = self.run_tests('-r', '--randseed=%s' % randseed, test)
  639. randseed2 = self.parse_random_seed(output)
  640. self.assertEqual(randseed2, randseed)
  641. match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
  642. test_random2 = int(match.group(1))
  643. self.assertEqual(test_random2, test_random)
  644. def test_fromfile(self):
  645. # test --fromfile
  646. tests = [self.create_test() for index in range(5)]
  647. # Write the list of files using a format similar to regrtest output:
  648. # [1/2] test_1
  649. # [2/2] test_2
  650. filename = os_helper.TESTFN
  651. self.addCleanup(os_helper.unlink, filename)
  652. # test format '0:00:00 [2/7] test_opcodes -- test_grammar took 0 sec'
  653. with open(filename, "w") as fp:
  654. previous = None
  655. for index, name in enumerate(tests, 1):
  656. line = ("00:00:%02i [%s/%s] %s"
  657. % (index, index, len(tests), name))
  658. if previous:
  659. line += " -- %s took 0 sec" % previous
  660. print(line, file=fp)
  661. previous = name
  662. output = self.run_tests('--fromfile', filename)
  663. self.check_executed_tests(output, tests)
  664. # test format '[2/7] test_opcodes'
  665. with open(filename, "w") as fp:
  666. for index, name in enumerate(tests, 1):
  667. print("[%s/%s] %s" % (index, len(tests), name), file=fp)
  668. output = self.run_tests('--fromfile', filename)
  669. self.check_executed_tests(output, tests)
  670. # test format 'test_opcodes'
  671. with open(filename, "w") as fp:
  672. for name in tests:
  673. print(name, file=fp)
  674. output = self.run_tests('--fromfile', filename)
  675. self.check_executed_tests(output, tests)
  676. # test format 'Lib/test/test_opcodes.py'
  677. with open(filename, "w") as fp:
  678. for name in tests:
  679. print('Lib/test/%s.py' % name, file=fp)
  680. output = self.run_tests('--fromfile', filename)
  681. self.check_executed_tests(output, tests)
  682. def test_interrupted(self):
  683. code = TEST_INTERRUPTED
  684. test = self.create_test('sigint', code=code)
  685. output = self.run_tests(test, exitcode=130)
  686. self.check_executed_tests(output, test, omitted=test,
  687. interrupted=True)
  688. def test_slowest(self):
  689. # test --slowest
  690. tests = [self.create_test() for index in range(3)]
  691. output = self.run_tests("--slowest", *tests)
  692. self.check_executed_tests(output, tests)
  693. regex = ('10 slowest tests:\n'
  694. '(?:- %s: .*\n){%s}'
  695. % (self.TESTNAME_REGEX, len(tests)))
  696. self.check_line(output, regex)
  697. def test_slowest_interrupted(self):
  698. # Issue #25373: test --slowest with an interrupted test
  699. code = TEST_INTERRUPTED
  700. test = self.create_test("sigint", code=code)
  701. for multiprocessing in (False, True):
  702. with self.subTest(multiprocessing=multiprocessing):
  703. if multiprocessing:
  704. args = ("--slowest", "-j2", test)
  705. else:
  706. args = ("--slowest", test)
  707. output = self.run_tests(*args, exitcode=130)
  708. self.check_executed_tests(output, test,
  709. omitted=test, interrupted=True)
  710. regex = ('10 slowest tests:\n')
  711. self.check_line(output, regex)
  712. def test_coverage(self):
  713. # test --coverage
  714. test = self.create_test('coverage')
  715. output = self.run_tests("--coverage", test)
  716. self.check_executed_tests(output, [test])
  717. regex = (r'lines +cov% +module +\(path\)\n'
  718. r'(?: *[0-9]+ *[0-9]{1,2}% *[^ ]+ +\([^)]+\)+)+')
  719. self.check_line(output, regex)
  720. def test_wait(self):
  721. # test --wait
  722. test = self.create_test('wait')
  723. output = self.run_tests("--wait", test, input='key')
  724. self.check_line(output, 'Press any key to continue')
  725. def test_forever(self):
  726. # test --forever
  727. code = textwrap.dedent("""
  728. import builtins
  729. import unittest
  730. class ForeverTester(unittest.TestCase):
  731. def test_run(self):
  732. # Store the state in the builtins module, because the test
  733. # module is reload at each run
  734. if 'RUN' in builtins.__dict__:
  735. builtins.__dict__['RUN'] += 1
  736. if builtins.__dict__['RUN'] >= 3:
  737. self.fail("fail at the 3rd runs")
  738. else:
  739. builtins.__dict__['RUN'] = 1
  740. """)
  741. test = self.create_test('forever', code=code)
  742. output = self.run_tests('--forever', test, exitcode=2)
  743. self.check_executed_tests(output, [test]*3, failed=test)
  744. def check_leak(self, code, what):
  745. test = self.create_test('huntrleaks', code=code)
  746. filename = 'reflog.txt'
  747. self.addCleanup(os_helper.unlink, filename)
  748. output = self.run_tests('--huntrleaks', '3:3:', test,
  749. exitcode=2,
  750. stderr=subprocess.STDOUT)
  751. self.check_executed_tests(output, [test], failed=test)
  752. line = 'beginning 6 repetitions\n123456\n......\n'
  753. self.check_line(output, re.escape(line))
  754. line2 = '%s leaked [1, 1, 1] %s, sum=3\n' % (test, what)
  755. self.assertIn(line2, output)
  756. with open(filename) as fp:
  757. reflog = fp.read()
  758. self.assertIn(line2, reflog)
  759. @unittest.skipUnless(Py_DEBUG, 'need a debug build')
  760. def test_huntrleaks(self):
  761. # test --huntrleaks
  762. code = textwrap.dedent("""
  763. import unittest
  764. GLOBAL_LIST = []
  765. class RefLeakTest(unittest.TestCase):
  766. def test_leak(self):
  767. GLOBAL_LIST.append(object())
  768. """)
  769. self.check_leak(code, 'references')
  770. @unittest.skipUnless(Py_DEBUG, 'need a debug build')
  771. def test_huntrleaks_fd_leak(self):
  772. # test --huntrleaks for file descriptor leak
  773. code = textwrap.dedent("""
  774. import os
  775. import unittest
  776. class FDLeakTest(unittest.TestCase):
  777. def test_leak(self):
  778. fd = os.open(__file__, os.O_RDONLY)
  779. # bug: never close the file descriptor
  780. """)
  781. self.check_leak(code, 'file descriptors')
  782. def test_list_tests(self):
  783. # test --list-tests
  784. tests = [self.create_test() for i in range(5)]
  785. output = self.run_tests('--list-tests', *tests)
  786. self.assertEqual(output.rstrip().splitlines(),
  787. tests)
  788. def test_list_cases(self):
  789. # test --list-cases
  790. code = textwrap.dedent("""
  791. import unittest
  792. class Tests(unittest.TestCase):
  793. def test_method1(self):
  794. pass
  795. def test_method2(self):
  796. pass
  797. """)
  798. testname = self.create_test(code=code)
  799. # Test --list-cases
  800. all_methods = ['%s.Tests.test_method1' % testname,
  801. '%s.Tests.test_method2' % testname]
  802. output = self.run_tests('--list-cases', testname)
  803. self.assertEqual(output.splitlines(), all_methods)
  804. # Test --list-cases with --match
  805. all_methods = ['%s.Tests.test_method1' % testname]
  806. output = self.run_tests('--list-cases',
  807. '-m', 'test_method1',
  808. testname)
  809. self.assertEqual(output.splitlines(), all_methods)
  810. @support.cpython_only
  811. def test_crashed(self):
  812. # Any code which causes a crash
  813. code = 'import faulthandler; faulthandler._sigsegv()'
  814. crash_test = self.create_test(name="crash", code=code)
  815. tests = [crash_test]
  816. output = self.run_tests("-j2", *tests, exitcode=2)
  817. self.check_executed_tests(output, tests, failed=crash_test,
  818. randomize=True)
  819. def parse_methods(self, output):
  820. regex = re.compile("^(test[^ ]+).*ok$", flags=re.MULTILINE)
  821. return [match.group(1) for match in regex.finditer(output)]
  822. def test_ignorefile(self):
  823. code = textwrap.dedent("""
  824. import unittest
  825. class Tests(unittest.TestCase):
  826. def test_method1(self):
  827. pass
  828. def test_method2(self):
  829. pass
  830. def test_method3(self):
  831. pass
  832. def test_method4(self):
  833. pass
  834. """)
  835. all_methods = ['test_method1', 'test_method2',
  836. 'test_method3', 'test_method4']
  837. testname = self.create_test(code=code)
  838. # only run a subset
  839. filename = os_helper.TESTFN
  840. self.addCleanup(os_helper.unlink, filename)
  841. subset = [
  842. # only ignore the method name
  843. 'test_method1',
  844. # ignore the full identifier
  845. '%s.Tests.test_method3' % testname]
  846. with open(filename, "w") as fp:
  847. for name in subset:
  848. print(name, file=fp)
  849. output = self.run_tests("-v", "--ignorefile", filename, testname)
  850. methods = self.parse_methods(output)
  851. subset = ['test_method2', 'test_method4']
  852. self.assertEqual(methods, subset)
  853. def test_matchfile(self):
  854. code = textwrap.dedent("""
  855. import unittest
  856. class Tests(unittest.TestCase):
  857. def test_method1(self):
  858. pass
  859. def test_method2(self):
  860. pass
  861. def test_method3(self):
  862. pass
  863. def test_method4(self):
  864. pass
  865. """)
  866. all_methods = ['test_method1', 'test_method2',
  867. 'test_method3', 'test_method4']
  868. testname = self.create_test(code=code)
  869. # by default, all methods should be run
  870. output = self.run_tests("-v", testname)
  871. methods = self.parse_methods(output)
  872. self.assertEqual(methods, all_methods)
  873. # only run a subset
  874. filename = os_helper.TESTFN
  875. self.addCleanup(os_helper.unlink, filename)
  876. subset = [
  877. # only match the method name
  878. 'test_method1',
  879. # match the full identifier
  880. '%s.Tests.test_method3' % testname]
  881. with open(filename, "w") as fp:
  882. for name in subset:
  883. print(name, file=fp)
  884. output = self.run_tests("-v", "--matchfile", filename, testname)
  885. methods = self.parse_methods(output)
  886. subset = ['test_method1', 'test_method3']
  887. self.assertEqual(methods, subset)
  888. def test_env_changed(self):
  889. code = textwrap.dedent("""
  890. import unittest
  891. class Tests(unittest.TestCase):
  892. def test_env_changed(self):
  893. open("env_changed", "w").close()
  894. """)
  895. testname = self.create_test(code=code)
  896. # don't fail by default
  897. output = self.run_tests(testname)
  898. self.check_executed_tests(output, [testname], env_changed=testname)
  899. # fail with --fail-env-changed
  900. output = self.run_tests("--fail-env-changed", testname, exitcode=3)
  901. self.check_executed_tests(output, [testname], env_changed=testname,
  902. fail_env_changed=True)
  903. def test_rerun_fail(self):
  904. # FAILURE then FAILURE
  905. code = textwrap.dedent("""
  906. import unittest
  907. class Tests(unittest.TestCase):
  908. def test_succeed(self):
  909. return
  910. def test_fail_always(self):
  911. # test that always fails
  912. self.fail("bug")
  913. """)
  914. testname = self.create_test(code=code)
  915. output = self.run_tests("-w", testname, exitcode=2)
  916. self.check_executed_tests(output, [testname],
  917. failed=testname, rerun={testname: "test_fail_always"})
  918. def test_rerun_success(self):
  919. # FAILURE then SUCCESS
  920. code = textwrap.dedent("""
  921. import builtins
  922. import unittest
  923. class Tests(unittest.TestCase):
  924. def test_succeed(self):
  925. return
  926. def test_fail_once(self):
  927. if not hasattr(builtins, '_test_failed'):
  928. builtins._test_failed = True
  929. self.fail("bug")
  930. """)
  931. testname = self.create_test(code=code)
  932. output = self.run_tests("-w", testname, exitcode=0)
  933. self.check_executed_tests(output, [testname],
  934. rerun={testname: "test_fail_once"})
  935. def test_no_tests_ran(self):
  936. code = textwrap.dedent("""
  937. import unittest
  938. class Tests(unittest.TestCase):
  939. def test_bug(self):
  940. pass
  941. """)
  942. testname = self.create_test(code=code)
  943. output = self.run_tests(testname, "-m", "nosuchtest", exitcode=0)
  944. self.check_executed_tests(output, [testname], no_test_ran=testname)
  945. def test_no_tests_ran_skip(self):
  946. code = textwrap.dedent("""
  947. import unittest
  948. class Tests(unittest.TestCase):
  949. def test_skipped(self):
  950. self.skipTest("because")
  951. """)
  952. testname = self.create_test(code=code)
  953. output = self.run_tests(testname, exitcode=0)
  954. self.check_executed_tests(output, [testname])
  955. def test_no_tests_ran_multiple_tests_nonexistent(self):
  956. code = textwrap.dedent("""
  957. import unittest
  958. class Tests(unittest.TestCase):
  959. def test_bug(self):
  960. pass
  961. """)
  962. testname = self.create_test(code=code)
  963. testname2 = self.create_test(code=code)
  964. output = self.run_tests(testname, testname2, "-m", "nosuchtest", exitcode=0)
  965. self.check_executed_tests(output, [testname, testname2],
  966. no_test_ran=[testname, testname2])
  967. def test_no_test_ran_some_test_exist_some_not(self):
  968. code = textwrap.dedent("""
  969. import unittest
  970. class Tests(unittest.TestCase):
  971. def test_bug(self):
  972. pass
  973. """)
  974. testname = self.create_test(code=code)
  975. other_code = textwrap.dedent("""
  976. import unittest
  977. class Tests(unittest.TestCase):
  978. def test_other_bug(self):
  979. pass
  980. """)
  981. testname2 = self.create_test(code=other_code)
  982. output = self.run_tests(testname, testname2, "-m", "nosuchtest",
  983. "-m", "test_other_bug", exitcode=0)
  984. self.check_executed_tests(output, [testname, testname2],
  985. no_test_ran=[testname])
  986. @support.cpython_only
  987. def test_uncollectable(self):
  988. code = textwrap.dedent(r"""
  989. import _testcapi
  990. import gc
  991. import unittest
  992. @_testcapi.with_tp_del
  993. class Garbage:
  994. def __tp_del__(self):
  995. pass
  996. class Tests(unittest.TestCase):
  997. def test_garbage(self):
  998. # create an uncollectable object
  999. obj = Garbage()
  1000. obj.ref_cycle = obj
  1001. obj = None
  1002. """)
  1003. testname = self.create_test(code=code)
  1004. output = self.run_tests("--fail-env-changed", testname, exitcode=3)
  1005. self.check_executed_tests(output, [testname],
  1006. env_changed=[testname],
  1007. fail_env_changed=True)
  1008. def test_multiprocessing_timeout(self):
  1009. code = textwrap.dedent(r"""
  1010. import time
  1011. import unittest
  1012. try:
  1013. import faulthandler
  1014. except ImportError:
  1015. faulthandler = None
  1016. class Tests(unittest.TestCase):
  1017. # test hangs and so should be stopped by the timeout
  1018. def test_sleep(self):
  1019. # we want to test regrtest multiprocessing timeout,
  1020. # not faulthandler timeout
  1021. if faulthandler is not None:
  1022. faulthandler.cancel_dump_traceback_later()
  1023. time.sleep(60 * 5)
  1024. """)
  1025. testname = self.create_test(code=code)
  1026. output = self.run_tests("-j2", "--timeout=1.0", testname, exitcode=2)
  1027. self.check_executed_tests(output, [testname],
  1028. failed=testname)
  1029. self.assertRegex(output,
  1030. re.compile('%s timed out' % testname, re.MULTILINE))
  1031. def test_unraisable_exc(self):
  1032. # --fail-env-changed must catch unraisable exception.
  1033. # The exception must be displayed even if sys.stderr is redirected.
  1034. code = textwrap.dedent(r"""
  1035. import unittest
  1036. import weakref
  1037. from test.support import captured_stderr
  1038. class MyObject:
  1039. pass
  1040. def weakref_callback(obj):
  1041. raise Exception("weakref callback bug")
  1042. class Tests(unittest.TestCase):
  1043. def test_unraisable_exc(self):
  1044. obj = MyObject()
  1045. ref = weakref.ref(obj, weakref_callback)
  1046. with captured_stderr() as stderr:
  1047. # call weakref_callback() which logs
  1048. # an unraisable exception
  1049. obj = None
  1050. self.assertEqual(stderr.getvalue(), '')
  1051. """)
  1052. testname = self.create_test(code=code)
  1053. output = self.run_tests("--fail-env-changed", "-v", testname, exitcode=3)
  1054. self.check_executed_tests(output, [testname],
  1055. env_changed=[testname],
  1056. fail_env_changed=True)
  1057. self.assertIn("Warning -- Unraisable exception", output)
  1058. self.assertIn("Exception: weakref callback bug", output)
  1059. def test_threading_excepthook(self):
  1060. # --fail-env-changed must catch uncaught thread exception.
  1061. # The exception must be displayed even if sys.stderr is redirected.
  1062. code = textwrap.dedent(r"""
  1063. import threading
  1064. import unittest
  1065. from test.support import captured_stderr
  1066. class MyObject:
  1067. pass
  1068. def func_bug():
  1069. raise Exception("bug in thread")
  1070. class Tests(unittest.TestCase):
  1071. def test_threading_excepthook(self):
  1072. with captured_stderr() as stderr:
  1073. thread = threading.Thread(target=func_bug)
  1074. thread.start()
  1075. thread.join()
  1076. self.assertEqual(stderr.getvalue(), '')
  1077. """)
  1078. testname = self.create_test(code=code)
  1079. output = self.run_tests("--fail-env-changed", "-v", testname, exitcode=3)
  1080. self.check_executed_tests(output, [testname],
  1081. env_changed=[testname],
  1082. fail_env_changed=True)
  1083. self.assertIn("Warning -- Uncaught thread exception", output)
  1084. self.assertIn("Exception: bug in thread", output)
  1085. def test_print_warning(self):
  1086. # bpo-45410: The order of messages must be preserved when -W and
  1087. # support.print_warning() are used.
  1088. code = textwrap.dedent(r"""
  1089. import sys
  1090. import unittest
  1091. from test import support
  1092. class MyObject:
  1093. pass
  1094. def func_bug():
  1095. raise Exception("bug in thread")
  1096. class Tests(unittest.TestCase):
  1097. def test_print_warning(self):
  1098. print("msg1: stdout")
  1099. support.print_warning("msg2: print_warning")
  1100. # Fail with ENV CHANGED to see print_warning() log
  1101. support.environment_altered = True
  1102. """)
  1103. testname = self.create_test(code=code)
  1104. # Expect an output like:
  1105. #
  1106. # test_threading_excepthook (test.test_x.Tests) ... msg1: stdout
  1107. # Warning -- msg2: print_warning
  1108. # ok
  1109. regex = (r"test_print_warning.*msg1: stdout\n"
  1110. r"Warning -- msg2: print_warning\n"
  1111. r"ok\n")
  1112. for option in ("-v", "-W"):
  1113. with self.subTest(option=option):
  1114. cmd = ["--fail-env-changed", option, testname]
  1115. output = self.run_tests(*cmd, exitcode=3)
  1116. self.check_executed_tests(output, [testname],
  1117. env_changed=[testname],
  1118. fail_env_changed=True)
  1119. self.assertRegex(output, regex)
  1120. def test_unicode_guard_env(self):
  1121. guard = os.environ.get(setup.UNICODE_GUARD_ENV)
  1122. self.assertIsNotNone(guard, f"{setup.UNICODE_GUARD_ENV} not set")
  1123. if guard.isascii():
  1124. # Skip to signify that the env var value was changed by the user;
  1125. # possibly to something ASCII to work around Unicode issues.
  1126. self.skipTest("Modified guard")
  1127. def test_cleanup(self):
  1128. dirname = os.path.join(self.tmptestdir, "test_python_123")
  1129. os.mkdir(dirname)
  1130. filename = os.path.join(self.tmptestdir, "test_python_456")
  1131. open(filename, "wb").close()
  1132. names = [dirname, filename]
  1133. cmdargs = ['-m', 'test',
  1134. '--tempdir=%s' % self.tmptestdir,
  1135. '--cleanup']
  1136. self.run_python(cmdargs)
  1137. for name in names:
  1138. self.assertFalse(os.path.exists(name), name)
  1139. class TestUtils(unittest.TestCase):
  1140. def test_format_duration(self):
  1141. self.assertEqual(utils.format_duration(0),
  1142. '0 ms')
  1143. self.assertEqual(utils.format_duration(1e-9),
  1144. '1 ms')
  1145. self.assertEqual(utils.format_duration(10e-3),
  1146. '10 ms')
  1147. self.assertEqual(utils.format_duration(1.5),
  1148. '1.5 sec')
  1149. self.assertEqual(utils.format_duration(1),
  1150. '1.0 sec')
  1151. self.assertEqual(utils.format_duration(2 * 60),
  1152. '2 min')
  1153. self.assertEqual(utils.format_duration(2 * 60 + 1),
  1154. '2 min 1 sec')
  1155. self.assertEqual(utils.format_duration(3 * 3600),
  1156. '3 hour')
  1157. self.assertEqual(utils.format_duration(3 * 3600 + 2 * 60 + 1),
  1158. '3 hour 2 min')
  1159. self.assertEqual(utils.format_duration(3 * 3600 + 1),
  1160. '3 hour 1 sec')
  1161. if __name__ == '__main__':
  1162. unittest.main()