main.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. import faulthandler
  2. import locale
  3. import os
  4. import platform
  5. import random
  6. import re
  7. import sys
  8. import sysconfig
  9. import tempfile
  10. import time
  11. import unittest
  12. from test.libregrtest.cmdline import _parse_args
  13. from test.libregrtest.runtest import (
  14. findtests, runtest, get_abs_module, is_failed,
  15. STDTESTS, NOTTESTS, PROGRESS_MIN_TIME,
  16. Passed, Failed, EnvChanged, Skipped, ResourceDenied, Interrupted,
  17. ChildError, DidNotRun)
  18. from test.libregrtest.setup import setup_tests
  19. from test.libregrtest.pgo import setup_pgo_tests
  20. from test.libregrtest.utils import removepy, count, format_duration, printlist
  21. from test import support
  22. from test.support import os_helper
  23. from test.support import threading_helper
  24. # bpo-38203: Maximum delay in seconds to exit Python (call Py_Finalize()).
  25. # Used to protect against threading._shutdown() hang.
  26. # Must be smaller than buildbot "1200 seconds without output" limit.
  27. EXIT_TIMEOUT = 120.0
  28. class Regrtest:
  29. """Execute a test suite.
  30. This also parses command-line options and modifies its behavior
  31. accordingly.
  32. tests -- a list of strings containing test names (optional)
  33. testdir -- the directory in which to look for tests (optional)
  34. Users other than the Python test suite will certainly want to
  35. specify testdir; if it's omitted, the directory containing the
  36. Python test suite is searched for.
  37. If the tests argument is omitted, the tests listed on the
  38. command-line will be used. If that's empty, too, then all *.py
  39. files beginning with test_ will be used.
  40. The other default arguments (verbose, quiet, exclude,
  41. single, randomize, use_resources, trace, coverdir,
  42. print_slow, and random_seed) allow programmers calling main()
  43. directly to set the values that would normally be set by flags
  44. on the command line.
  45. """
  46. def __init__(self):
  47. # Namespace of command line options
  48. self.ns = None
  49. # tests
  50. self.tests = []
  51. self.selected = []
  52. # test results
  53. self.good = []
  54. self.bad = []
  55. self.skipped = []
  56. self.resource_denieds = []
  57. self.environment_changed = []
  58. self.run_no_tests = []
  59. self.need_rerun = []
  60. self.rerun = []
  61. self.first_result = None
  62. self.interrupted = False
  63. # used by --slow
  64. self.test_times = []
  65. # used by --coverage, trace.Trace instance
  66. self.tracer = None
  67. # used to display the progress bar "[ 3/100]"
  68. self.start_time = time.monotonic()
  69. self.test_count = ''
  70. self.test_count_width = 1
  71. # used by --single
  72. self.next_single_test = None
  73. self.next_single_filename = None
  74. # used by --junit-xml
  75. self.testsuite_xml = None
  76. # misc
  77. self.win_load_tracker = None
  78. self.tmp_dir = None
  79. self.worker_test_name = None
  80. def get_executed(self):
  81. return (set(self.good) | set(self.bad) | set(self.skipped)
  82. | set(self.resource_denieds) | set(self.environment_changed)
  83. | set(self.run_no_tests))
  84. def accumulate_result(self, result, rerun=False):
  85. test_name = result.name
  86. if not isinstance(result, (ChildError, Interrupted)) and not rerun:
  87. self.test_times.append((result.duration_sec, test_name))
  88. if isinstance(result, Passed):
  89. self.good.append(test_name)
  90. elif isinstance(result, ResourceDenied):
  91. self.skipped.append(test_name)
  92. self.resource_denieds.append(test_name)
  93. elif isinstance(result, Skipped):
  94. self.skipped.append(test_name)
  95. elif isinstance(result, EnvChanged):
  96. self.environment_changed.append(test_name)
  97. elif isinstance(result, Failed):
  98. if not rerun:
  99. self.bad.append(test_name)
  100. self.need_rerun.append(result)
  101. elif isinstance(result, DidNotRun):
  102. self.run_no_tests.append(test_name)
  103. elif isinstance(result, Interrupted):
  104. self.interrupted = True
  105. else:
  106. raise ValueError("invalid test result: %r" % result)
  107. if rerun and not isinstance(result, (Failed, Interrupted)):
  108. self.bad.remove(test_name)
  109. xml_data = result.xml_data
  110. if xml_data:
  111. import xml.etree.ElementTree as ET
  112. for e in xml_data:
  113. try:
  114. self.testsuite_xml.append(ET.fromstring(e))
  115. except ET.ParseError:
  116. print(xml_data, file=sys.__stderr__)
  117. raise
  118. def log(self, line=''):
  119. empty = not line
  120. # add the system load prefix: "load avg: 1.80 "
  121. load_avg = self.getloadavg()
  122. if load_avg is not None:
  123. line = f"load avg: {load_avg:.2f} {line}"
  124. # add the timestamp prefix: "0:01:05 "
  125. test_time = time.monotonic() - self.start_time
  126. mins, secs = divmod(int(test_time), 60)
  127. hours, mins = divmod(mins, 60)
  128. test_time = "%d:%02d:%02d" % (hours, mins, secs)
  129. line = f"{test_time} {line}"
  130. if empty:
  131. line = line[:-1]
  132. print(line, flush=True)
  133. def display_progress(self, test_index, text):
  134. if self.ns.quiet:
  135. return
  136. # "[ 51/405/1] test_tcl passed"
  137. line = f"{test_index:{self.test_count_width}}{self.test_count}"
  138. fails = len(self.bad) + len(self.environment_changed)
  139. if fails and not self.ns.pgo:
  140. line = f"{line}/{fails}"
  141. self.log(f"[{line}] {text}")
  142. def parse_args(self, kwargs):
  143. ns = _parse_args(sys.argv[1:], **kwargs)
  144. if ns.xmlpath:
  145. support.junit_xml_list = self.testsuite_xml = []
  146. worker_args = ns.worker_args
  147. if worker_args is not None:
  148. from test.libregrtest.runtest_mp import parse_worker_args
  149. ns, test_name = parse_worker_args(ns.worker_args)
  150. ns.worker_args = worker_args
  151. self.worker_test_name = test_name
  152. # Strip .py extensions.
  153. removepy(ns.args)
  154. if ns.huntrleaks:
  155. warmup, repetitions, _ = ns.huntrleaks
  156. if warmup < 1 or repetitions < 1:
  157. msg = ("Invalid values for the --huntrleaks/-R parameters. The "
  158. "number of warmups and repetitions must be at least 1 "
  159. "each (1:1).")
  160. print(msg, file=sys.stderr, flush=True)
  161. sys.exit(2)
  162. if ns.tempdir:
  163. ns.tempdir = os.path.expanduser(ns.tempdir)
  164. self.ns = ns
  165. def find_tests(self, tests):
  166. self.tests = tests
  167. if self.ns.single:
  168. self.next_single_filename = os.path.join(self.tmp_dir, 'pynexttest')
  169. try:
  170. with open(self.next_single_filename, 'r') as fp:
  171. next_test = fp.read().strip()
  172. self.tests = [next_test]
  173. except OSError:
  174. pass
  175. if self.ns.fromfile:
  176. self.tests = []
  177. # regex to match 'test_builtin' in line:
  178. # '0:00:00 [ 4/400] test_builtin -- test_dict took 1 sec'
  179. regex = re.compile(r'\btest_[a-zA-Z0-9_]+\b')
  180. with open(os.path.join(os_helper.SAVEDCWD, self.ns.fromfile)) as fp:
  181. for line in fp:
  182. line = line.split('#', 1)[0]
  183. line = line.strip()
  184. match = regex.search(line)
  185. if match is not None:
  186. self.tests.append(match.group())
  187. removepy(self.tests)
  188. if self.ns.pgo:
  189. # add default PGO tests if no tests are specified
  190. setup_pgo_tests(self.ns)
  191. stdtests = STDTESTS[:]
  192. nottests = NOTTESTS.copy()
  193. if self.ns.exclude:
  194. for arg in self.ns.args:
  195. if arg in stdtests:
  196. stdtests.remove(arg)
  197. nottests.add(arg)
  198. self.ns.args = []
  199. # if testdir is set, then we are not running the python tests suite, so
  200. # don't add default tests to be executed or skipped (pass empty values)
  201. if self.ns.testdir:
  202. alltests = findtests(self.ns.testdir, list(), set())
  203. else:
  204. alltests = findtests(self.ns.testdir, stdtests, nottests)
  205. if not self.ns.fromfile:
  206. self.selected = self.tests or self.ns.args or alltests
  207. else:
  208. self.selected = self.tests
  209. if self.ns.single:
  210. self.selected = self.selected[:1]
  211. try:
  212. pos = alltests.index(self.selected[0])
  213. self.next_single_test = alltests[pos + 1]
  214. except IndexError:
  215. pass
  216. # Remove all the selected tests that precede start if it's set.
  217. if self.ns.start:
  218. try:
  219. del self.selected[:self.selected.index(self.ns.start)]
  220. except ValueError:
  221. print("Couldn't find starting test (%s), using all tests"
  222. % self.ns.start, file=sys.stderr)
  223. if self.ns.randomize:
  224. if self.ns.random_seed is None:
  225. self.ns.random_seed = random.randrange(10000000)
  226. random.seed(self.ns.random_seed)
  227. random.shuffle(self.selected)
  228. def list_tests(self):
  229. for name in self.selected:
  230. print(name)
  231. def _list_cases(self, suite):
  232. for test in suite:
  233. if isinstance(test, unittest.loader._FailedTest):
  234. continue
  235. if isinstance(test, unittest.TestSuite):
  236. self._list_cases(test)
  237. elif isinstance(test, unittest.TestCase):
  238. if support.match_test(test):
  239. print(test.id())
  240. def list_cases(self):
  241. support.verbose = False
  242. support.set_match_tests(self.ns.match_tests, self.ns.ignore_tests)
  243. for test_name in self.selected:
  244. abstest = get_abs_module(self.ns, test_name)
  245. try:
  246. suite = unittest.defaultTestLoader.loadTestsFromName(abstest)
  247. self._list_cases(suite)
  248. except unittest.SkipTest:
  249. self.skipped.append(test_name)
  250. if self.skipped:
  251. print(file=sys.stderr)
  252. print(count(len(self.skipped), "test"), "skipped:", file=sys.stderr)
  253. printlist(self.skipped, file=sys.stderr)
  254. def rerun_failed_tests(self):
  255. self.log()
  256. if self.ns.python:
  257. # Temp patch for https://github.com/python/cpython/issues/94052
  258. self.log(
  259. "Re-running failed tests is not supported with --python "
  260. "host runner option."
  261. )
  262. return
  263. self.ns.verbose = True
  264. self.ns.failfast = False
  265. self.ns.verbose3 = False
  266. self.first_result = self.get_tests_result()
  267. self.log("Re-running failed tests in verbose mode")
  268. rerun_list = list(self.need_rerun)
  269. self.need_rerun.clear()
  270. for result in rerun_list:
  271. test_name = result.name
  272. self.rerun.append(test_name)
  273. errors = result.errors or []
  274. failures = result.failures or []
  275. error_names = [test_full_name.split(" ")[0] for (test_full_name, *_) in errors]
  276. failure_names = [test_full_name.split(" ")[0] for (test_full_name, *_) in failures]
  277. self.ns.verbose = True
  278. orig_match_tests = self.ns.match_tests
  279. if errors or failures:
  280. if self.ns.match_tests is None:
  281. self.ns.match_tests = []
  282. self.ns.match_tests.extend(error_names)
  283. self.ns.match_tests.extend(failure_names)
  284. matching = "matching: " + ", ".join(self.ns.match_tests)
  285. self.log(f"Re-running {test_name} in verbose mode ({matching})")
  286. else:
  287. self.log(f"Re-running {test_name} in verbose mode")
  288. result = runtest(self.ns, test_name)
  289. self.ns.match_tests = orig_match_tests
  290. self.accumulate_result(result, rerun=True)
  291. if isinstance(result, Interrupted):
  292. break
  293. if self.bad:
  294. print(count(len(self.bad), 'test'), "failed again:")
  295. printlist(self.bad)
  296. self.display_result()
  297. def display_result(self):
  298. # If running the test suite for PGO then no one cares about results.
  299. if self.ns.pgo:
  300. return
  301. print()
  302. print("== Tests result: %s ==" % self.get_tests_result())
  303. if self.interrupted:
  304. print("Test suite interrupted by signal SIGINT.")
  305. omitted = set(self.selected) - self.get_executed()
  306. if omitted:
  307. print()
  308. print(count(len(omitted), "test"), "omitted:")
  309. printlist(omitted)
  310. if self.good and not self.ns.quiet:
  311. print()
  312. if (not self.bad
  313. and not self.skipped
  314. and not self.interrupted
  315. and len(self.good) > 1):
  316. print("All", end=' ')
  317. print(count(len(self.good), "test"), "OK.")
  318. if self.ns.print_slow:
  319. self.test_times.sort(reverse=True)
  320. print()
  321. print("10 slowest tests:")
  322. for test_time, test in self.test_times[:10]:
  323. print("- %s: %s" % (test, format_duration(test_time)))
  324. if self.bad:
  325. print()
  326. print(count(len(self.bad), "test"), "failed:")
  327. printlist(self.bad)
  328. if self.environment_changed:
  329. print()
  330. print("{} altered the execution environment:".format(
  331. count(len(self.environment_changed), "test")))
  332. printlist(self.environment_changed)
  333. if self.skipped and not self.ns.quiet:
  334. print()
  335. print(count(len(self.skipped), "test"), "skipped:")
  336. printlist(self.skipped)
  337. if self.rerun:
  338. print()
  339. print("%s:" % count(len(self.rerun), "re-run test"))
  340. printlist(self.rerun)
  341. if self.run_no_tests:
  342. print()
  343. print(count(len(self.run_no_tests), "test"), "run no tests:")
  344. printlist(self.run_no_tests)
  345. def run_tests_sequential(self):
  346. if self.ns.trace:
  347. import trace
  348. self.tracer = trace.Trace(trace=False, count=True)
  349. save_modules = sys.modules.keys()
  350. msg = "Run tests sequentially"
  351. if self.ns.timeout:
  352. msg += " (timeout: %s)" % format_duration(self.ns.timeout)
  353. self.log(msg)
  354. previous_test = None
  355. for test_index, test_name in enumerate(self.tests, 1):
  356. start_time = time.monotonic()
  357. text = test_name
  358. if previous_test:
  359. text = '%s -- %s' % (text, previous_test)
  360. self.display_progress(test_index, text)
  361. if self.tracer:
  362. # If we're tracing code coverage, then we don't exit with status
  363. # if on a false return value from main.
  364. cmd = ('result = runtest(self.ns, test_name); '
  365. 'self.accumulate_result(result)')
  366. ns = dict(locals())
  367. self.tracer.runctx(cmd, globals=globals(), locals=ns)
  368. result = ns['result']
  369. else:
  370. result = runtest(self.ns, test_name)
  371. self.accumulate_result(result)
  372. if isinstance(result, Interrupted):
  373. break
  374. previous_test = str(result)
  375. test_time = time.monotonic() - start_time
  376. if test_time >= PROGRESS_MIN_TIME:
  377. previous_test = "%s in %s" % (previous_test, format_duration(test_time))
  378. elif isinstance(result, Passed):
  379. # be quiet: say nothing if the test passed shortly
  380. previous_test = None
  381. # Unload the newly imported modules (best effort finalization)
  382. for module in sys.modules.keys():
  383. if module not in save_modules and module.startswith("test."):
  384. support.unload(module)
  385. if self.ns.failfast and is_failed(result, self.ns):
  386. break
  387. if previous_test:
  388. print(previous_test)
  389. def _test_forever(self, tests):
  390. while True:
  391. for test_name in tests:
  392. yield test_name
  393. if self.bad:
  394. return
  395. if self.ns.fail_env_changed and self.environment_changed:
  396. return
  397. def display_header(self):
  398. # Print basic platform information
  399. print("==", platform.python_implementation(), *sys.version.split())
  400. print("==", platform.platform(aliased=True),
  401. "%s-endian" % sys.byteorder)
  402. print("== cwd:", os.getcwd())
  403. cpu_count = os.cpu_count()
  404. if cpu_count:
  405. print("== CPU count:", cpu_count)
  406. print("== encodings: locale=%s, FS=%s"
  407. % (locale.getencoding(), sys.getfilesystemencoding()))
  408. def get_tests_result(self):
  409. result = []
  410. if self.bad:
  411. result.append("FAILURE")
  412. elif self.ns.fail_env_changed and self.environment_changed:
  413. result.append("ENV CHANGED")
  414. elif not any((self.good, self.bad, self.skipped, self.interrupted,
  415. self.environment_changed)):
  416. result.append("NO TEST RUN")
  417. if self.interrupted:
  418. result.append("INTERRUPTED")
  419. if not result:
  420. result.append("SUCCESS")
  421. result = ', '.join(result)
  422. if self.first_result:
  423. result = '%s then %s' % (self.first_result, result)
  424. return result
  425. def run_tests(self):
  426. # For a partial run, we do not need to clutter the output.
  427. if (self.ns.header
  428. or not(self.ns.pgo or self.ns.quiet or self.ns.single
  429. or self.tests or self.ns.args)):
  430. self.display_header()
  431. if self.ns.huntrleaks:
  432. warmup, repetitions, _ = self.ns.huntrleaks
  433. if warmup < 3:
  434. msg = ("WARNING: Running tests with --huntrleaks/-R and less than "
  435. "3 warmup repetitions can give false positives!")
  436. print(msg, file=sys.stdout, flush=True)
  437. if self.ns.randomize:
  438. print("Using random seed", self.ns.random_seed)
  439. if self.ns.forever:
  440. self.tests = self._test_forever(list(self.selected))
  441. self.test_count = ''
  442. self.test_count_width = 3
  443. else:
  444. self.tests = iter(self.selected)
  445. self.test_count = '/{}'.format(len(self.selected))
  446. self.test_count_width = len(self.test_count) - 1
  447. if self.ns.use_mp:
  448. from test.libregrtest.runtest_mp import run_tests_multiprocess
  449. # If we're on windows and this is the parent runner (not a worker),
  450. # track the load average.
  451. if sys.platform == 'win32' and self.worker_test_name is None:
  452. from test.libregrtest.win_utils import WindowsLoadTracker
  453. try:
  454. self.win_load_tracker = WindowsLoadTracker()
  455. except PermissionError as error:
  456. # Standard accounts may not have access to the performance
  457. # counters.
  458. print(f'Failed to create WindowsLoadTracker: {error}')
  459. try:
  460. run_tests_multiprocess(self)
  461. finally:
  462. if self.win_load_tracker is not None:
  463. self.win_load_tracker.close()
  464. self.win_load_tracker = None
  465. else:
  466. self.run_tests_sequential()
  467. def finalize(self):
  468. if self.next_single_filename:
  469. if self.next_single_test:
  470. with open(self.next_single_filename, 'w') as fp:
  471. fp.write(self.next_single_test + '\n')
  472. else:
  473. os.unlink(self.next_single_filename)
  474. if self.tracer:
  475. r = self.tracer.results()
  476. r.write_results(show_missing=True, summary=True,
  477. coverdir=self.ns.coverdir)
  478. print()
  479. duration = time.monotonic() - self.start_time
  480. print("Total duration: %s" % format_duration(duration))
  481. print("Tests result: %s" % self.get_tests_result())
  482. if self.ns.runleaks:
  483. os.system("leaks %d" % os.getpid())
  484. def save_xml_result(self):
  485. if not self.ns.xmlpath and not self.testsuite_xml:
  486. return
  487. import xml.etree.ElementTree as ET
  488. root = ET.Element("testsuites")
  489. # Manually count the totals for the overall summary
  490. totals = {'tests': 0, 'errors': 0, 'failures': 0}
  491. for suite in self.testsuite_xml:
  492. root.append(suite)
  493. for k in totals:
  494. try:
  495. totals[k] += int(suite.get(k, 0))
  496. except ValueError:
  497. pass
  498. for k, v in totals.items():
  499. root.set(k, str(v))
  500. xmlpath = os.path.join(os_helper.SAVEDCWD, self.ns.xmlpath)
  501. with open(xmlpath, 'wb') as f:
  502. for s in ET.tostringlist(root):
  503. f.write(s)
  504. def fix_umask(self):
  505. if support.is_emscripten:
  506. # Emscripten has default umask 0o777, which breaks some tests.
  507. # see https://github.com/emscripten-core/emscripten/issues/17269
  508. old_mask = os.umask(0)
  509. if old_mask == 0o777:
  510. os.umask(0o027)
  511. else:
  512. os.umask(old_mask)
  513. def set_temp_dir(self):
  514. if self.ns.tempdir:
  515. self.tmp_dir = self.ns.tempdir
  516. if not self.tmp_dir:
  517. # When tests are run from the Python build directory, it is best practice
  518. # to keep the test files in a subfolder. This eases the cleanup of leftover
  519. # files using the "make distclean" command.
  520. if sysconfig.is_python_build():
  521. self.tmp_dir = sysconfig.get_config_var('abs_builddir')
  522. if self.tmp_dir is None:
  523. # bpo-30284: On Windows, only srcdir is available. Using
  524. # abs_builddir mostly matters on UNIX when building Python
  525. # out of the source tree, especially when the source tree
  526. # is read only.
  527. self.tmp_dir = sysconfig.get_config_var('srcdir')
  528. self.tmp_dir = os.path.join(self.tmp_dir, 'build')
  529. else:
  530. self.tmp_dir = tempfile.gettempdir()
  531. self.tmp_dir = os.path.abspath(self.tmp_dir)
  532. def create_temp_dir(self):
  533. os.makedirs(self.tmp_dir, exist_ok=True)
  534. # Define a writable temp dir that will be used as cwd while running
  535. # the tests. The name of the dir includes the pid to allow parallel
  536. # testing (see the -j option).
  537. # Emscripten and WASI have stubbed getpid(), Emscripten has only
  538. # milisecond clock resolution. Use randint() instead.
  539. if sys.platform in {"emscripten", "wasi"}:
  540. nounce = random.randint(0, 1_000_000)
  541. else:
  542. nounce = os.getpid()
  543. if self.worker_test_name is not None:
  544. test_cwd = 'test_python_worker_{}'.format(nounce)
  545. else:
  546. test_cwd = 'test_python_{}'.format(nounce)
  547. test_cwd += os_helper.FS_NONASCII
  548. test_cwd = os.path.join(self.tmp_dir, test_cwd)
  549. return test_cwd
  550. def cleanup(self):
  551. import glob
  552. path = os.path.join(glob.escape(self.tmp_dir), 'test_python_*')
  553. print("Cleanup %s directory" % self.tmp_dir)
  554. for name in glob.glob(path):
  555. if os.path.isdir(name):
  556. print("Remove directory: %s" % name)
  557. os_helper.rmtree(name)
  558. else:
  559. print("Remove file: %s" % name)
  560. os_helper.unlink(name)
  561. def main(self, tests=None, **kwargs):
  562. self.parse_args(kwargs)
  563. self.set_temp_dir()
  564. self.fix_umask()
  565. if self.ns.cleanup:
  566. self.cleanup()
  567. sys.exit(0)
  568. test_cwd = self.create_temp_dir()
  569. try:
  570. # Run the tests in a context manager that temporarily changes the CWD
  571. # to a temporary and writable directory. If it's not possible to
  572. # create or change the CWD, the original CWD will be used.
  573. # The original CWD is available from os_helper.SAVEDCWD.
  574. with os_helper.temp_cwd(test_cwd, quiet=True):
  575. # When using multiprocessing, worker processes will use test_cwd
  576. # as their parent temporary directory. So when the main process
  577. # exit, it removes also subdirectories of worker processes.
  578. self.ns.tempdir = test_cwd
  579. self._main(tests, kwargs)
  580. except SystemExit as exc:
  581. # bpo-38203: Python can hang at exit in Py_Finalize(), especially
  582. # on threading._shutdown() call: put a timeout
  583. if threading_helper.can_start_thread:
  584. faulthandler.dump_traceback_later(EXIT_TIMEOUT, exit=True)
  585. sys.exit(exc.code)
  586. def getloadavg(self):
  587. if self.win_load_tracker is not None:
  588. return self.win_load_tracker.getloadavg()
  589. if hasattr(os, 'getloadavg'):
  590. return os.getloadavg()[0]
  591. return None
  592. def _main(self, tests, kwargs):
  593. if self.worker_test_name is not None:
  594. from test.libregrtest.runtest_mp import run_tests_worker
  595. run_tests_worker(self.ns, self.worker_test_name)
  596. if self.ns.wait:
  597. input("Press any key to continue...")
  598. support.PGO = self.ns.pgo
  599. support.PGO_EXTENDED = self.ns.pgo_extended
  600. setup_tests(self.ns)
  601. self.find_tests(tests)
  602. if self.ns.list_tests:
  603. self.list_tests()
  604. sys.exit(0)
  605. if self.ns.list_cases:
  606. self.list_cases()
  607. sys.exit(0)
  608. self.run_tests()
  609. self.display_result()
  610. if self.ns.verbose2 and self.bad:
  611. self.rerun_failed_tests()
  612. self.finalize()
  613. self.save_xml_result()
  614. if self.bad:
  615. sys.exit(2)
  616. if self.interrupted:
  617. sys.exit(130)
  618. if self.ns.fail_env_changed and self.environment_changed:
  619. sys.exit(3)
  620. sys.exit(0)
  621. def main(tests=None, **kwargs):
  622. """Run the Python suite."""
  623. Regrtest().main(tests=tests, **kwargs)