Debian Codegraph @

lib-python/3/test/test_regrtest.py

raw symbols SCIP
1 """
2 Tests of regrtest.py.
3
4 Note: test_regrtest cannot be run twice in parallel.
5 """
6
7 import contextlib
8 import dataclasses
9 import glob
10 import io
11 import locale
12 import os.path
13 import platform
14 import random
15 import re
16 import shlex
17 import signal
18 import subprocess
19 import sys
20 import sysconfig
21 import tempfile
22 import textwrap
23 import unittest
24 from test import support
25 from test.support import os_helper
26 from test.libregrtest import cmdline
27 from test.libregrtest import main
28 from test.libregrtest import setup
29 from test.libregrtest import utils
30 from test.libregrtest.filter import get_match_tests, set_match_tests, match_test
31 from test.libregrtest.result import TestStats
32 from test.libregrtest.utils import normalize_test_name
33
34 if not support.has_subprocess_support:
35 raise unittest.SkipTest("test module requires subprocess")
36
37 ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..')
38 ROOT_DIR = os.path.abspath(os.path.normpath(ROOT_DIR))
39 LOG_PREFIX = r'[0-9]+:[0-9]+:[0-9]+ (?:load avg: [0-9]+\.[0-9]{2} )?'
40
41 EXITCODE_BAD_TEST = 2
42 EXITCODE_ENV_CHANGED = 3
43 EXITCODE_NO_TESTS_RAN = 4
44 EXITCODE_RERUN_FAIL = 5
45 EXITCODE_INTERRUPTED = 130
46
47 TEST_INTERRUPTED = textwrap.dedent("""
48 from signal import SIGINT, raise_signal
49 try:
50 raise_signal(SIGINT)
51 except ImportError:
52 import os
53 os.kill(os.getpid(), SIGINT)
54 """)
55
56
57 class ParseArgsTestCase(unittest.TestCase):
58 """
59 Test regrtest's argument parsing, function _parse_args().
60 """
61
62 @staticmethod
63 def parse_args(args):
64 return cmdline._parse_args(args)
65
66 def checkError(self, args, msg):
67 with support.captured_stderr() as err, self.assertRaises(SystemExit):
68 self.parse_args(args)
69 self.assertIn(msg, err.getvalue())
70
71 def test_help(self):
72 for opt in '-h', '--help':
73 with self.subTest(opt=opt):
74 with support.captured_stdout() as out, \
75 self.assertRaises(SystemExit):
76 self.parse_args([opt])
77 self.assertIn('Run Python regression tests.', out.getvalue())
78
79 def test_timeout(self):
80 ns = self.parse_args(['--timeout', '4.2'])
81 self.assertEqual(ns.timeout, 4.2)
82
83 # negative, zero and empty string are treated as "no timeout"
84 for value in ('-1', '0', ''):
85 with self.subTest(value=value):
86 ns = self.parse_args([f'--timeout={value}'])
87 self.assertEqual(ns.timeout, None)
88
89 self.checkError(['--timeout'], 'expected one argument')
90 self.checkError(['--timeout', 'foo'], 'invalid timeout value:')
91
92 def test_wait(self):
93 ns = self.parse_args(['--wait'])
94 self.assertTrue(ns.wait)
95
96 def test_start(self):
97 for opt in '-S', '--start':
98 with self.subTest(opt=opt):
99 ns = self.parse_args([opt, 'foo'])
100 self.assertEqual(ns.start, 'foo')
101 self.checkError([opt], 'expected one argument')
102
103 def test_verbose(self):
104 ns = self.parse_args(['-v'])
105 self.assertEqual(ns.verbose, 1)
106 ns = self.parse_args(['-vvv'])
107 self.assertEqual(ns.verbose, 3)
108 ns = self.parse_args(['--verbose'])
109 self.assertEqual(ns.verbose, 1)
110 ns = self.parse_args(['--verbose'] * 3)
111 self.assertEqual(ns.verbose, 3)
112 ns = self.parse_args([])
113 self.assertEqual(ns.verbose, 0)
114
115 def test_rerun(self):
116 for opt in '-w', '--rerun', '--verbose2':
117 with self.subTest(opt=opt):
118 ns = self.parse_args([opt])
119 self.assertTrue(ns.rerun)
120
121 def test_verbose3(self):
122 for opt in '-W', '--verbose3':
123 with self.subTest(opt=opt):
124 ns = self.parse_args([opt])
125 self.assertTrue(ns.verbose3)
126
127 def test_quiet(self):
128 for opt in '-q', '--quiet':
129 with self.subTest(opt=opt):
130 ns = self.parse_args([opt])
131 self.assertTrue(ns.quiet)
132 self.assertEqual(ns.verbose, 0)
133
134 def test_slowest(self):
135 for opt in '-o', '--slowest':
136 with self.subTest(opt=opt):
137 ns = self.parse_args([opt])
138 self.assertTrue(ns.print_slow)
139
140 def test_header(self):
141 ns = self.parse_args(['--header'])
142 self.assertTrue(ns.header)
143
144 ns = self.parse_args(['--verbose'])
145 self.assertTrue(ns.header)
146
147 def test_randomize(self):
148 for opt in ('-r', '--randomize'):
149 with self.subTest(opt=opt):
150 ns = self.parse_args([opt])
151 self.assertTrue(ns.randomize)
152
153 with os_helper.EnvironmentVarGuard() as env:
154 # with SOURCE_DATE_EPOCH
155 env['SOURCE_DATE_EPOCH'] = '1697839080'
156 ns = self.parse_args(['--randomize'])
157 regrtest = main.Regrtest(ns)
158 self.assertFalse(regrtest.randomize)
159 self.assertIsInstance(regrtest.random_seed, str)
160 self.assertEqual(regrtest.random_seed, '1697839080')
161
162 # without SOURCE_DATE_EPOCH
163 del env['SOURCE_DATE_EPOCH']
164 ns = self.parse_args(['--randomize'])
165 regrtest = main.Regrtest(ns)
166 self.assertTrue(regrtest.randomize)
167 self.assertIsInstance(regrtest.random_seed, int)
168
169 def test_randseed(self):
170 ns = self.parse_args(['--randseed', '12345'])
171 self.assertEqual(ns.random_seed, 12345)
172 self.assertTrue(ns.randomize)
173 self.checkError(['--randseed'], 'expected one argument')
174 self.checkError(['--randseed', 'foo'], 'invalid int value')
175
176 def test_fromfile(self):
177 for opt in '-f', '--fromfile':
178 with self.subTest(opt=opt):
179 ns = self.parse_args([opt, 'foo'])
180 self.assertEqual(ns.fromfile, 'foo')
181 self.checkError([opt], 'expected one argument')
182 self.checkError([opt, 'foo', '-s'], "don't go together")
183
184 def test_exclude(self):
185 for opt in '-x', '--exclude':
186 with self.subTest(opt=opt):
187 ns = self.parse_args([opt])
188 self.assertTrue(ns.exclude)
189
190 def test_single(self):
191 for opt in '-s', '--single':
192 with self.subTest(opt=opt):
193 ns = self.parse_args([opt])
194 self.assertTrue(ns.single)
195 self.checkError([opt, '-f', 'foo'], "don't go together")
196
197 def test_match(self):
198 for opt in '-m', '--match':
199 with self.subTest(opt=opt):
200 ns = self.parse_args([opt, 'pattern'])
201 self.assertEqual(ns.match_tests, [('pattern', True)])
202 self.checkError([opt], 'expected one argument')
203
204 for opt in '-i', '--ignore':
205 with self.subTest(opt=opt):
206 ns = self.parse_args([opt, 'pattern'])
207 self.assertEqual(ns.match_tests, [('pattern', False)])
208 self.checkError([opt], 'expected one argument')
209
210 ns = self.parse_args(['-m', 'pattern1', '-m', 'pattern2'])
211 self.assertEqual(ns.match_tests, [('pattern1', True), ('pattern2', True)])
212
213 ns = self.parse_args(['-m', 'pattern1', '-i', 'pattern2'])
214 self.assertEqual(ns.match_tests, [('pattern1', True), ('pattern2', False)])
215
216 ns = self.parse_args(['-i', 'pattern1', '-m', 'pattern2'])
217 self.assertEqual(ns.match_tests, [('pattern1', False), ('pattern2', True)])
218
219 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
220 with open(os_helper.TESTFN, "w") as fp:
221 print('matchfile1', file=fp)
222 print('matchfile2', file=fp)
223
224 filename = os.path.abspath(os_helper.TESTFN)
225 ns = self.parse_args(['-m', 'match', '--matchfile', filename])
226 self.assertEqual(ns.match_tests,
227 [('match', True), ('matchfile1', True), ('matchfile2', True)])
228
229 ns = self.parse_args(['-i', 'match', '--ignorefile', filename])
230 self.assertEqual(ns.match_tests,
231 [('match', False), ('matchfile1', False), ('matchfile2', False)])
232
233 def test_failfast(self):
234 for opt in '-G', '--failfast':
235 with self.subTest(opt=opt):
236 ns = self.parse_args([opt, '-v'])
237 self.assertTrue(ns.failfast)
238 ns = self.parse_args([opt, '-W'])
239 self.assertTrue(ns.failfast)
240 self.checkError([opt], '-G/--failfast needs either -v or -W')
241
242 def test_use(self):
243 for opt in '-u', '--use':
244 with self.subTest(opt=opt):
245 ns = self.parse_args([opt, 'gui,network'])
246 self.assertEqual(ns.use_resources, ['gui', 'network'])
247
248 ns = self.parse_args([opt, 'gui,none,network'])
249 self.assertEqual(ns.use_resources, ['network'])
250
251 expected = list(cmdline.ALL_RESOURCES)
252 expected.remove('gui')
253 ns = self.parse_args([opt, 'all,-gui'])
254 self.assertEqual(ns.use_resources, expected)
255 self.checkError([opt], 'expected one argument')
256 self.checkError([opt, 'foo'], 'invalid resource')
257
258 # all + a resource not part of "all"
259 ns = self.parse_args([opt, 'all,tzdata'])
260 self.assertEqual(ns.use_resources,
261 list(cmdline.ALL_RESOURCES) + ['tzdata'])
262
263 # test another resource which is not part of "all"
264 ns = self.parse_args([opt, 'extralargefile'])
265 self.assertEqual(ns.use_resources, ['extralargefile'])
266
267 def test_memlimit(self):
268 for opt in '-M', '--memlimit':
269 with self.subTest(opt=opt):
270 ns = self.parse_args([opt, '4G'])
271 self.assertEqual(ns.memlimit, '4G')
272 self.checkError([opt], 'expected one argument')
273
274 def test_testdir(self):
275 ns = self.parse_args(['--testdir', 'foo'])
276 self.assertEqual(ns.testdir, os.path.join(os_helper.SAVEDCWD, 'foo'))
277 self.checkError(['--testdir'], 'expected one argument')
278
279 def test_runleaks(self):
280 for opt in '-L', '--runleaks':
281 with self.subTest(opt=opt):
282 ns = self.parse_args([opt])
283 self.assertTrue(ns.runleaks)
284
285 def test_huntrleaks(self):
286 for opt in '-R', '--huntrleaks':
287 with self.subTest(opt=opt):
288 ns = self.parse_args([opt, ':'])
289 self.assertEqual(ns.huntrleaks, (5, 4, 'reflog.txt'))
290 ns = self.parse_args([opt, '6:'])
291 self.assertEqual(ns.huntrleaks, (6, 4, 'reflog.txt'))
292 ns = self.parse_args([opt, ':3'])
293 self.assertEqual(ns.huntrleaks, (5, 3, 'reflog.txt'))
294 ns = self.parse_args([opt, '6:3:leaks.log'])
295 self.assertEqual(ns.huntrleaks, (6, 3, 'leaks.log'))
296 self.checkError([opt], 'expected one argument')
297 self.checkError([opt, '6'],
298 'needs 2 or 3 colon-separated arguments')
299 self.checkError([opt, 'foo:'], 'invalid huntrleaks value')
300 self.checkError([opt, '6:foo'], 'invalid huntrleaks value')
301
302 def test_multiprocess(self):
303 for opt in '-j', '--multiprocess':
304 with self.subTest(opt=opt):
305 ns = self.parse_args([opt, '2'])
306 self.assertEqual(ns.use_mp, 2)
307 self.checkError([opt], 'expected one argument')
308 self.checkError([opt, 'foo'], 'invalid int value')
309 self.checkError([opt, '2', '-T'], "don't go together")
310 self.checkError([opt, '0', '-T'], "don't go together")
311
312 def test_coverage(self):
313 for opt in '-T', '--coverage':
314 with self.subTest(opt=opt):
315 ns = self.parse_args([opt])
316 self.assertTrue(ns.trace)
317
318 def test_coverdir(self):
319 for opt in '-D', '--coverdir':
320 with self.subTest(opt=opt):
321 ns = self.parse_args([opt, 'foo'])
322 self.assertEqual(ns.coverdir,
323 os.path.join(os_helper.SAVEDCWD, 'foo'))
324 self.checkError([opt], 'expected one argument')
325
326 def test_nocoverdir(self):
327 for opt in '-N', '--nocoverdir':
328 with self.subTest(opt=opt):
329 ns = self.parse_args([opt])
330 self.assertIsNone(ns.coverdir)
331
332 def test_threshold(self):
333 for opt in '-t', '--threshold':
334 with self.subTest(opt=opt):
335 ns = self.parse_args([opt, '1000'])
336 self.assertEqual(ns.threshold, 1000)
337 self.checkError([opt], 'expected one argument')
338 self.checkError([opt, 'foo'], 'invalid int value')
339
340 def test_nowindows(self):
341 for opt in '-n', '--nowindows':
342 with self.subTest(opt=opt):
343 with contextlib.redirect_stderr(io.StringIO()) as stderr:
344 ns = self.parse_args([opt])
345 self.assertTrue(ns.nowindows)
346 err = stderr.getvalue()
347 self.assertIn('the --nowindows (-n) option is deprecated', err)
348
349 def test_forever(self):
350 for opt in '-F', '--forever':
351 with self.subTest(opt=opt):
352 ns = self.parse_args([opt])
353 self.assertTrue(ns.forever)
354
355 def test_unrecognized_argument(self):
356 self.checkError(['--xxx'], 'usage:')
357
358 def test_long_option__partial(self):
359 ns = self.parse_args(['--qui'])
360 self.assertTrue(ns.quiet)
361 self.assertEqual(ns.verbose, 0)
362
363 def test_two_options(self):
364 ns = self.parse_args(['--quiet', '--exclude'])
365 self.assertTrue(ns.quiet)
366 self.assertEqual(ns.verbose, 0)
367 self.assertTrue(ns.exclude)
368
369 def test_option_with_empty_string_value(self):
370 ns = self.parse_args(['--start', ''])
371 self.assertEqual(ns.start, '')
372
373 def test_arg(self):
374 ns = self.parse_args(['foo'])
375 self.assertEqual(ns.args, ['foo'])
376
377 def test_option_and_arg(self):
378 ns = self.parse_args(['--quiet', 'foo'])
379 self.assertTrue(ns.quiet)
380 self.assertEqual(ns.verbose, 0)
381 self.assertEqual(ns.args, ['foo'])
382
383 def test_arg_option_arg(self):
384 ns = self.parse_args(['test_unaryop', '-v', 'test_binop'])
385 self.assertEqual(ns.verbose, 1)
386 self.assertEqual(ns.args, ['test_unaryop', 'test_binop'])
387
388 def test_unknown_option(self):
389 self.checkError(['--unknown-option'],
390 'unrecognized arguments: --unknown-option')
391
392 def create_regrtest(self, args):
393 ns = cmdline._parse_args(args)
394
395 # Check Regrtest attributes which are more reliable than Namespace
396 # which has an unclear API
397 with os_helper.EnvironmentVarGuard() as env:
398 # Ignore SOURCE_DATE_EPOCH env var if it's set
399 if 'SOURCE_DATE_EPOCH' in env:
400 del env['SOURCE_DATE_EPOCH']
401
402 regrtest = main.Regrtest(ns)
403
404 return regrtest
405
406 def check_ci_mode(self, args, use_resources, rerun=True):
407 regrtest = self.create_regrtest(args)
408 self.assertEqual(regrtest.num_workers, -1)
409 self.assertEqual(regrtest.want_rerun, rerun)
410 self.assertTrue(regrtest.randomize)
411 self.assertIsInstance(regrtest.random_seed, int)
412 self.assertTrue(regrtest.fail_env_changed)
413 self.assertTrue(regrtest.fail_rerun)
414 self.assertTrue(regrtest.print_slowest)
415 self.assertTrue(regrtest.output_on_failure)
416 self.assertEqual(sorted(regrtest.use_resources), sorted(use_resources))
417 return regrtest
418
419 def test_fast_ci(self):
420 args = ['--fast-ci']
421 use_resources = sorted(cmdline.ALL_RESOURCES)
422 use_resources.remove('cpu')
423 regrtest = self.check_ci_mode(args, use_resources)
424 self.assertEqual(regrtest.timeout, 10 * 60)
425
426 def test_fast_ci_python_cmd(self):
427 args = ['--fast-ci', '--python', 'python -X dev']
428 use_resources = sorted(cmdline.ALL_RESOURCES)
429 use_resources.remove('cpu')
430 regrtest = self.check_ci_mode(args, use_resources, rerun=False)
431 self.assertEqual(regrtest.timeout, 10 * 60)
432 self.assertEqual(regrtest.python_cmd, ('python', '-X', 'dev'))
433
434 def test_fast_ci_resource(self):
435 # it should be possible to override resources individually
436 args = ['--fast-ci', '-u-network']
437 use_resources = sorted(cmdline.ALL_RESOURCES)
438 use_resources.remove('cpu')
439 use_resources.remove('network')
440 self.check_ci_mode(args, use_resources)
441
442 def test_slow_ci(self):
443 args = ['--slow-ci']
444 use_resources = sorted(cmdline.ALL_RESOURCES)
445 regrtest = self.check_ci_mode(args, use_resources)
446 self.assertEqual(regrtest.timeout, 20 * 60)
447
448 def test_dont_add_python_opts(self):
449 args = ['--dont-add-python-opts']
450 ns = cmdline._parse_args(args)
451 self.assertFalse(ns._add_python_opts)
452
453 def test_bisect(self):
454 args = ['--bisect']
455 regrtest = self.create_regrtest(args)
456 self.assertTrue(regrtest.want_bisect)
457
458 def test_verbose3_huntrleaks(self):
459 args = ['-R', '3:10', '--verbose3']
460 with support.captured_stderr():
461 regrtest = self.create_regrtest(args)
462 self.assertIsNotNone(regrtest.hunt_refleak)
463 self.assertEqual(regrtest.hunt_refleak.warmups, 3)
464 self.assertEqual(regrtest.hunt_refleak.runs, 10)
465 self.assertFalse(regrtest.output_on_failure)
466
467 def test_xml_huntrleaks(self):
468 args = ['-R', '3:12', '--junit-xml', 'output.xml']
469 with support.captured_stderr():
470 regrtest = self.create_regrtest(args)
471 self.assertIsNotNone(regrtest.hunt_refleak)
472 self.assertEqual(regrtest.hunt_refleak.warmups, 3)
473 self.assertEqual(regrtest.hunt_refleak.runs, 12)
474 self.assertIsNone(regrtest.junit_filename)
475
476
477 @dataclasses.dataclass(slots=True)
478 class Rerun:
479 name: str
480 match: str | None
481 success: bool
482
483
484 class BaseTestCase(unittest.TestCase):
485 TEST_UNIQUE_ID = 1
486 TESTNAME_PREFIX = 'test_regrtest_'
487 TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+'
488
489 def setUp(self):
490 self.testdir = os.path.realpath(os.path.dirname(__file__))
491
492 self.tmptestdir = tempfile.mkdtemp()
493 self.addCleanup(os_helper.rmtree, self.tmptestdir)
494
495 def create_test(self, name=None, code=None):
496 if not name:
497 name = 'noop%s' % BaseTestCase.TEST_UNIQUE_ID
498 BaseTestCase.TEST_UNIQUE_ID += 1
499
500 if code is None:
501 code = textwrap.dedent("""
502 import unittest
503
504 class Tests(unittest.TestCase):
505 def test_empty_test(self):
506 pass
507 """)
508
509 # test_regrtest cannot be run twice in parallel because
510 # of setUp() and create_test()
511 name = self.TESTNAME_PREFIX + name
512 path = os.path.join(self.tmptestdir, name + '.py')
513
514 self.addCleanup(os_helper.unlink, path)
515 # Use 'x' mode to ensure that we do not override existing tests
516 try:
517 with open(path, 'x', encoding='utf-8') as fp:
518 fp.write(code)
519 except PermissionError as exc:
520 if not sysconfig.is_python_build():
521 self.skipTest("cannot write %s: %s" % (path, exc))
522 raise
523 return name
524
525 def regex_search(self, regex, output):
526 match = re.search(regex, output, re.MULTILINE)
527 if not match:
528 self.fail("%r not found in %r" % (regex, output))
529 return match
530
531 def check_line(self, output, pattern, full=False, regex=True):
532 if not regex:
533 pattern = re.escape(pattern)
534 if full:
535 pattern += '\n'
536 regex = re.compile(r'^' + pattern, re.MULTILINE)
537 self.assertRegex(output, regex)
538
539 def parse_executed_tests(self, output):
540 regex = (r'^%s\[ *[0-9]+(?:/ *[0-9]+)*\] (%s)'
541 % (LOG_PREFIX, self.TESTNAME_REGEX))
542 parser = re.finditer(regex, output, re.MULTILINE)
543 return list(match.group(1) for match in parser)
544
545 def check_executed_tests(self, output, tests, *, stats,
546 skipped=(), failed=(),
547 env_changed=(), omitted=(),
548 rerun=None, run_no_tests=(),
549 resource_denied=(),
550 randomize=False, parallel=False, interrupted=False,
551 fail_env_changed=False,
552 forever=False, filtered=False):
553 if isinstance(tests, str):
554 tests = [tests]
555 if isinstance(skipped, str):
556 skipped = [skipped]
557 if isinstance(resource_denied, str):
558 resource_denied = [resource_denied]
559 if isinstance(failed, str):
560 failed = [failed]
561 if isinstance(env_changed, str):
562 env_changed = [env_changed]
563 if isinstance(omitted, str):
564 omitted = [omitted]
565 if isinstance(run_no_tests, str):
566 run_no_tests = [run_no_tests]
567 if isinstance(stats, int):
568 stats = TestStats(stats)
569 if parallel:
570 randomize = True
571
572 rerun_failed = []
573 if rerun is not None and not env_changed:
574 failed = [rerun.name]
575 if not rerun.success:
576 rerun_failed.append(rerun.name)
577
578 executed = self.parse_executed_tests(output)
579 total_tests = list(tests)
580 if rerun is not None:
581 total_tests.append(rerun.name)
582 if randomize:
583 self.assertEqual(set(executed), set(total_tests), output)
584 else:
585 self.assertEqual(executed, total_tests, output)
586
587 def plural(count):
588 return 's' if count != 1 else ''
589
590 def list_regex(line_format, tests):
591 count = len(tests)
592 names = ' '.join(sorted(tests))
593 regex = line_format % (count, plural(count))
594 regex = r'%s:\n %s$' % (regex, names)
595 return regex
596
597 if skipped:
598 regex = list_regex('%s test%s skipped', skipped)
599 self.check_line(output, regex)
600
601 if resource_denied:
602 regex = list_regex(r'%s test%s skipped \(resource denied\)', resource_denied)
603 self.check_line(output, regex)
604
605 if failed:
606 regex = list_regex('%s test%s failed', failed)
607 self.check_line(output, regex)
608
609 if env_changed:
610 regex = list_regex(r'%s test%s altered the execution environment '
611 r'\(env changed\)',
612 env_changed)
613 self.check_line(output, regex)
614
615 if omitted:
616 regex = list_regex('%s test%s omitted', omitted)
617 self.check_line(output, regex)
618
619 if rerun is not None:
620 regex = list_regex('%s re-run test%s', [rerun.name])
621 self.check_line(output, regex)
622 regex = LOG_PREFIX + r"Re-running 1 failed tests in verbose mode"
623 self.check_line(output, regex)
624 regex = fr"Re-running {rerun.name} in verbose mode"
625 if rerun.match:
626 regex = fr"{regex} \(matching: {rerun.match}\)"
627 self.check_line(output, regex)
628
629 if run_no_tests:
630 regex = list_regex('%s test%s run no tests', run_no_tests)
631 self.check_line(output, regex)
632
633 good = (len(tests) - len(skipped) - len(resource_denied) - len(failed)
634 - len(omitted) - len(env_changed) - len(run_no_tests))
635 if good:
636 regex = r'%s test%s OK\.' % (good, plural(good))
637 if not skipped and not failed and (rerun is None or rerun.success) and good > 1:
638 regex = 'All %s' % regex
639 self.check_line(output, regex, full=True)
640
641 if interrupted:
642 self.check_line(output, 'Test suite interrupted by signal SIGINT.')
643
644 # Total tests
645 text = f'run={stats.tests_run:,}'
646 if filtered:
647 text = fr'{text} \(filtered\)'
648 parts = [text]
649 if stats.failures:
650 parts.append(f'failures={stats.failures:,}')
651 if stats.skipped:
652 parts.append(f'skipped={stats.skipped:,}')
653 line = fr'Total tests: {" ".join(parts)}'
654 self.check_line(output, line, full=True)
655
656 # Total test files
657 run = len(total_tests) - len(resource_denied)
658 if rerun is not None:
659 total_failed = len(rerun_failed)
660 total_rerun = 1
661 else:
662 total_failed = len(failed)
663 total_rerun = 0
664 if interrupted:
665 run = 0
666 text = f'run={run}'
667 if not forever:
668 text = f'{text}/{len(tests)}'
669 if filtered:
670 text = fr'{text} \(filtered\)'
671 report = [text]
672 for name, ntest in (
673 ('failed', total_failed),
674 ('env_changed', len(env_changed)),
675 ('skipped', len(skipped)),
676 ('resource_denied', len(resource_denied)),
677 ('rerun', total_rerun),
678 ('run_no_tests', len(run_no_tests)),
679 ):
680 if ntest:
681 report.append(f'{name}={ntest}')
682 line = fr'Total test files: {" ".join(report)}'
683 self.check_line(output, line, full=True)
684
685 # Result
686 state = []
687 if failed:
688 state.append('FAILURE')
689 elif fail_env_changed and env_changed:
690 state.append('ENV CHANGED')
691 if interrupted:
692 state.append('INTERRUPTED')
693 if not any((good, failed, interrupted, skipped,
694 env_changed, fail_env_changed)):
695 state.append("NO TESTS RAN")
696 elif not state:
697 state.append('SUCCESS')
698 state = ', '.join(state)
699 if rerun is not None:
700 new_state = 'SUCCESS' if rerun.success else 'FAILURE'
701 state = f'{state} then {new_state}'
702 self.check_line(output, f'Result: {state}', full=True)
703
704 def parse_random_seed(self, output: str) -> str:
705 match = self.regex_search(r'Using random seed: (.*)', output)
706 return match.group(1)
707
708 def run_command(self, args, input=None, exitcode=0, **kw):
709 if not input:
710 input = ''
711 if 'stderr' not in kw:
712 kw['stderr'] = subprocess.STDOUT
713
714 env = kw.pop('env', None)
715 if env is None:
716 env = dict(os.environ)
717 env.pop('SOURCE_DATE_EPOCH', None)
718
719 proc = subprocess.run(args,
720 text=True,
721 input=input,
722 stdout=subprocess.PIPE,
723 env=env,
724 **kw)
725 if proc.returncode != exitcode:
726 msg = ("Command %s failed with exit code %s, but exit code %s expected!\n"
727 "\n"
728 "stdout:\n"
729 "---\n"
730 "%s\n"
731 "---\n"
732 % (str(args), proc.returncode, exitcode, proc.stdout))
733 if proc.stderr:
734 msg += ("\n"
735 "stderr:\n"
736 "---\n"
737 "%s"
738 "---\n"
739 % proc.stderr)
740 self.fail(msg)
741 return proc
742
743 def run_python(self, args, **kw):
744 extraargs = []
745 if 'uops' in sys._xoptions:
746 # Pass -X uops along
747 extraargs.extend(['-X', 'uops'])
748 args = [sys.executable, *extraargs, '-X', 'faulthandler', '-I', *args]
749 proc = self.run_command(args, **kw)
750 return proc.stdout
751
752
753 class CheckActualTests(BaseTestCase):
754 def test_finds_expected_number_of_tests(self):
755 """
756 Check that regrtest appears to find the expected set of tests.
757 """
758 args = ['-Wd', '-E', '-bb', '-m', 'test.regrtest', '--list-tests']
759 output = self.run_python(args)
760 rough_number_of_tests_found = len(output.splitlines())
761 actual_testsuite_glob = os.path.join(glob.escape(os.path.dirname(__file__)),
762 'test*.py')
763 rough_counted_test_py_files = len(glob.glob(actual_testsuite_glob))
764 # We're not trying to duplicate test finding logic in here,
765 # just give a rough estimate of how many there should be and
766 # be near that. This is a regression test to prevent mishaps
767 # such as https://bugs.python.org/issue37667 in the future.
768 # If you need to change the values in here during some
769 # mythical future test suite reorganization, don't go
770 # overboard with logic and keep that goal in mind.
771 self.assertGreater(rough_number_of_tests_found,
772 rough_counted_test_py_files*9//10,
773 msg='Unexpectedly low number of tests found in:\n'
774 f'{", ".join(output.splitlines())}')
775
776
777 class ProgramsTestCase(BaseTestCase):
778 """
779 Test various ways to run the Python test suite. Use options close
780 to options used on the buildbot.
781 """
782
783 NTEST = 4
784
785 def setUp(self):
786 super().setUp()
787
788 # Create NTEST tests doing nothing
789 self.tests = [self.create_test() for index in range(self.NTEST)]
790
791 self.python_args = ['-Wd', '-E', '-bb']
792 self.regrtest_args = ['-uall', '-rwW',
793 '--testdir=%s' % self.tmptestdir]
794 self.regrtest_args.extend(('--timeout', '3600', '-j4'))
795 if sys.platform == 'win32':
796 self.regrtest_args.append('-n')
797
798 def check_output(self, output):
799 randseed = self.parse_random_seed(output)
800 self.assertTrue(randseed.isdigit(), randseed)
801
802 self.check_executed_tests(output, self.tests,
803 randomize=True, stats=len(self.tests))
804
805 def run_tests(self, args, env=None):
806 output = self.run_python(args, env=env)
807 self.check_output(output)
808
809 def test_script_regrtest(self):
810 # Lib/test/regrtest.py
811 script = os.path.join(self.testdir, 'regrtest.py')
812
813 args = [*self.python_args, script, *self.regrtest_args, *self.tests]
814 self.run_tests(args)
815
816 def test_module_test(self):
817 # -m test
818 args = [*self.python_args, '-m', 'test',
819 *self.regrtest_args, *self.tests]
820 self.run_tests(args)
821
822 def test_module_regrtest(self):
823 # -m test.regrtest
824 args = [*self.python_args, '-m', 'test.regrtest',
825 *self.regrtest_args, *self.tests]
826 self.run_tests(args)
827
828 def test_module_autotest(self):
829 # -m test.autotest
830 args = [*self.python_args, '-m', 'test.autotest',
831 *self.regrtest_args, *self.tests]
832 self.run_tests(args)
833
834 def test_module_from_test_autotest(self):
835 # from test import autotest
836 code = 'from test import autotest'
837 args = [*self.python_args, '-c', code,
838 *self.regrtest_args, *self.tests]
839 self.run_tests(args)
840
841 def test_script_autotest(self):
842 # Lib/test/autotest.py
843 script = os.path.join(self.testdir, 'autotest.py')
844 args = [*self.python_args, script, *self.regrtest_args, *self.tests]
845 self.run_tests(args)
846
847 def run_batch(self, *args):
848 proc = self.run_command(args)
849 self.check_output(proc.stdout)
850
851 @unittest.skipUnless(sysconfig.is_python_build(),
852 'test.bat script is not installed')
853 @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
854 def test_tools_buildbot_test(self):
855 # Tools\buildbot\test.bat
856 script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat')
857 test_args = ['--testdir=%s' % self.tmptestdir]
858 if platform.machine() == 'ARM64':
859 test_args.append('-arm64') # ARM 64-bit build
860 elif platform.machine() == 'ARM':
861 test_args.append('-arm32') # 32-bit ARM build
862 elif platform.architecture()[0] == '64bit':
863 test_args.append('-x64') # 64-bit build
864 if not support.Py_DEBUG:
865 test_args.append('+d') # Release build, use python.exe
866 self.run_batch(script, *test_args, *self.tests)
867
868 @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
869 def test_pcbuild_rt(self):
870 # PCbuild\rt.bat
871 script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat')
872 if not os.path.isfile(script):
873 self.skipTest(f'File "{script}" does not exist')
874 rt_args = ["-q"] # Quick, don't run tests twice
875 if platform.machine() == 'ARM64':
876 rt_args.append('-arm64') # ARM 64-bit build
877 elif platform.machine() == 'ARM':
878 rt_args.append('-arm32') # 32-bit ARM build
879 elif platform.architecture()[0] == '64bit':
880 rt_args.append('-x64') # 64-bit build
881 if support.Py_DEBUG:
882 rt_args.append('-d') # Debug build, use python_d.exe
883 self.run_batch(script, *rt_args, *self.regrtest_args, *self.tests)
884
885
886 class ArgsTestCase(BaseTestCase):
887 """
888 Test arguments of the Python test suite.
889 """
890
891 def run_tests(self, *testargs, **kw):
892 cmdargs = ['-m', 'test', '--testdir=%s' % self.tmptestdir, *testargs]
893 return self.run_python(cmdargs, **kw)
894
895 def test_success(self):
896 code = textwrap.dedent("""
897 import unittest
898
899 class PassingTests(unittest.TestCase):
900 def test_test1(self):
901 pass
902
903 def test_test2(self):
904 pass
905
906 def test_test3(self):
907 pass
908 """)
909 tests = [self.create_test(f'ok{i}', code=code) for i in range(1, 6)]
910
911 output = self.run_tests(*tests)
912 self.check_executed_tests(output, tests,
913 stats=3 * len(tests))
914
915 def test_skip(self):
916 code = textwrap.dedent("""
917 import unittest
918 raise unittest.SkipTest("nope")
919 """)
920 test_ok = self.create_test('ok')
921 test_skip = self.create_test('skip', code=code)
922 tests = [test_ok, test_skip]
923
924 output = self.run_tests(*tests)
925 self.check_executed_tests(output, tests,
926 skipped=[test_skip],
927 stats=1)
928
929 def test_failing_test(self):
930 # test a failing test
931 code = textwrap.dedent("""
932 import unittest
933
934 class FailingTest(unittest.TestCase):
935 def test_failing(self):
936 self.fail("bug")
937 """)
938 test_ok = self.create_test('ok')
939 test_failing = self.create_test('failing', code=code)
940 tests = [test_ok, test_failing]
941
942 output = self.run_tests(*tests, exitcode=EXITCODE_BAD_TEST)
943 self.check_executed_tests(output, tests, failed=test_failing,
944 stats=TestStats(2, 1))
945
946 def test_resources(self):
947 # test -u command line option
948 tests = {}
949 for resource in ('audio', 'network'):
950 code = textwrap.dedent("""
951 from test import support; support.requires(%r)
952 import unittest
953 class PassingTest(unittest.TestCase):
954 def test_pass(self):
955 pass
956 """ % resource)
957
958 tests[resource] = self.create_test(resource, code)
959 test_names = sorted(tests.values())
960
961 # -u all: 2 resources enabled
962 output = self.run_tests('-u', 'all', *test_names)
963 self.check_executed_tests(output, test_names, stats=2)
964
965 # -u audio: 1 resource enabled
966 output = self.run_tests('-uaudio', *test_names)
967 self.check_executed_tests(output, test_names,
968 resource_denied=tests['network'],
969 stats=1)
970
971 # no option: 0 resources enabled
972 output = self.run_tests(*test_names, exitcode=EXITCODE_NO_TESTS_RAN)
973 self.check_executed_tests(output, test_names,
974 resource_denied=test_names,
975 stats=0)
976
977 def test_random(self):
978 # test -r and --randseed command line option
979 code = textwrap.dedent("""
980 import random
981 print("TESTRANDOM: %s" % random.randint(1, 1000))
982 """)
983 test = self.create_test('random', code)
984
985 # first run to get the output with the random seed
986 output = self.run_tests('-r', test, exitcode=EXITCODE_NO_TESTS_RAN)
987 randseed = self.parse_random_seed(output)
988 match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
989 test_random = int(match.group(1))
990
991 # try to reproduce with the random seed
992 output = self.run_tests('-r', f'--randseed={randseed}', test,
993 exitcode=EXITCODE_NO_TESTS_RAN)
994 randseed2 = self.parse_random_seed(output)
995 self.assertEqual(randseed2, randseed)
996
997 match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
998 test_random2 = int(match.group(1))
999 self.assertEqual(test_random2, test_random)
1000
1001 # check that random.seed is used by default
1002 output = self.run_tests(test, exitcode=EXITCODE_NO_TESTS_RAN)
1003 randseed = self.parse_random_seed(output)
1004 self.assertTrue(randseed.isdigit(), randseed)
1005
1006 # check SOURCE_DATE_EPOCH (integer)
1007 timestamp = '1697839080'
1008 env = dict(os.environ, SOURCE_DATE_EPOCH=timestamp)
1009 output = self.run_tests('-r', test, exitcode=EXITCODE_NO_TESTS_RAN,
1010 env=env)
1011 randseed = self.parse_random_seed(output)
1012 self.assertEqual(randseed, timestamp)
1013 self.check_line(output, 'TESTRANDOM: 520')
1014
1015 # check SOURCE_DATE_EPOCH (string)
1016 env = dict(os.environ, SOURCE_DATE_EPOCH='XYZ')
1017 output = self.run_tests('-r', test, exitcode=EXITCODE_NO_TESTS_RAN,
1018 env=env)
1019 randseed = self.parse_random_seed(output)
1020 self.assertEqual(randseed, 'XYZ')
1021 self.check_line(output, 'TESTRANDOM: 22')
1022
1023 # check SOURCE_DATE_EPOCH (empty string): ignore the env var
1024 env = dict(os.environ, SOURCE_DATE_EPOCH='')
1025 output = self.run_tests('-r', test, exitcode=EXITCODE_NO_TESTS_RAN,
1026 env=env)
1027 randseed = self.parse_random_seed(output)
1028 self.assertTrue(randseed.isdigit(), randseed)
1029
1030 def test_fromfile(self):
1031 # test --fromfile
1032 tests = [self.create_test() for index in range(5)]
1033
1034 # Write the list of files using a format similar to regrtest output:
1035 # [1/2] test_1
1036 # [2/2] test_2
1037 filename = os_helper.TESTFN
1038 self.addCleanup(os_helper.unlink, filename)
1039
1040 # test format '0:00:00 [2/7] test_opcodes -- test_grammar took 0 sec'
1041 with open(filename, "w") as fp:
1042 previous = None
1043 for index, name in enumerate(tests, 1):
1044 line = ("00:00:%02i [%s/%s] %s"
1045 % (index, index, len(tests), name))
1046 if previous:
1047 line += " -- %s took 0 sec" % previous
1048 print(line, file=fp)
1049 previous = name
1050
1051 output = self.run_tests('--fromfile', filename)
1052 stats = len(tests)
1053 self.check_executed_tests(output, tests, stats=stats)
1054
1055 # test format '[2/7] test_opcodes'
1056 with open(filename, "w") as fp:
1057 for index, name in enumerate(tests, 1):
1058 print("[%s/%s] %s" % (index, len(tests), name), file=fp)
1059
1060 output = self.run_tests('--fromfile', filename)
1061 self.check_executed_tests(output, tests, stats=stats)
1062
1063 # test format 'test_opcodes'
1064 with open(filename, "w") as fp:
1065 for name in tests:
1066 print(name, file=fp)
1067
1068 output = self.run_tests('--fromfile', filename)
1069 self.check_executed_tests(output, tests, stats=stats)
1070
1071 # test format 'Lib/test/test_opcodes.py'
1072 with open(filename, "w") as fp:
1073 for name in tests:
1074 print('Lib/test/%s.py' % name, file=fp)
1075
1076 output = self.run_tests('--fromfile', filename)
1077 self.check_executed_tests(output, tests, stats=stats)
1078
1079 def test_interrupted(self):
1080 code = TEST_INTERRUPTED
1081 test = self.create_test('sigint', code=code)
1082 output = self.run_tests(test, exitcode=EXITCODE_INTERRUPTED)
1083 self.check_executed_tests(output, test, omitted=test,
1084 interrupted=True, stats=0)
1085
1086 def test_slowest(self):
1087 # test --slowest
1088 tests = [self.create_test() for index in range(3)]
1089 output = self.run_tests("--slowest", *tests)
1090 self.check_executed_tests(output, tests, stats=len(tests))
1091 regex = ('10 slowest tests:\n'
1092 '(?:- %s: .*\n){%s}'
1093 % (self.TESTNAME_REGEX, len(tests)))
1094 self.check_line(output, regex)
1095
1096 def test_slowest_interrupted(self):
1097 # Issue #25373: test --slowest with an interrupted test
1098 code = TEST_INTERRUPTED
1099 test = self.create_test("sigint", code=code)
1100
1101 for multiprocessing in (False, True):
1102 with self.subTest(multiprocessing=multiprocessing):
1103 if multiprocessing:
1104 args = ("--slowest", "-j2", test)
1105 else:
1106 args = ("--slowest", test)
1107 output = self.run_tests(*args, exitcode=EXITCODE_INTERRUPTED)
1108 self.check_executed_tests(output, test,
1109 omitted=test, interrupted=True,
1110 stats=0)
1111
1112 regex = ('10 slowest tests:\n')
1113 self.check_line(output, regex)
1114
1115 def test_coverage(self):
1116 # test --coverage
1117 test = self.create_test('coverage')
1118 output = self.run_tests("--coverage", test)
1119 self.check_executed_tests(output, [test], stats=1)
1120 regex = (r'lines +cov% +module +\(path\)\n'
1121 r'(?: *[0-9]+ *[0-9]{1,2}% *[^ ]+ +\([^)]+\)+)+')
1122 self.check_line(output, regex)
1123
1124 def test_wait(self):
1125 # test --wait
1126 test = self.create_test('wait')
1127 output = self.run_tests("--wait", test, input='key')
1128 self.check_line(output, 'Press any key to continue')
1129
1130 def test_forever(self):
1131 # test --forever
1132 code = textwrap.dedent("""
1133 import builtins
1134 import unittest
1135
1136 class ForeverTester(unittest.TestCase):
1137 def test_run(self):
1138 # Store the state in the builtins module, because the test
1139 # module is reload at each run
1140 if 'RUN' in builtins.__dict__:
1141 builtins.__dict__['RUN'] += 1
1142 if builtins.__dict__['RUN'] >= 3:
1143 self.fail("fail at the 3rd runs")
1144 else:
1145 builtins.__dict__['RUN'] = 1
1146 """)
1147 test = self.create_test('forever', code=code)
1148
1149 # --forever
1150 output = self.run_tests('--forever', test, exitcode=EXITCODE_BAD_TEST)
1151 self.check_executed_tests(output, [test]*3, failed=test,
1152 stats=TestStats(3, 1),
1153 forever=True)
1154
1155 # --forever --rerun
1156 output = self.run_tests('--forever', '--rerun', test, exitcode=0)
1157 self.check_executed_tests(output, [test]*3,
1158 rerun=Rerun(test,
1159 match='test_run',
1160 success=True),
1161 stats=TestStats(4, 1),
1162 forever=True)
1163
1164 def check_leak(self, code, what, *, run_workers=False):
1165 test = self.create_test('huntrleaks', code=code)
1166
1167 filename = 'reflog.txt'
1168 self.addCleanup(os_helper.unlink, filename)
1169 cmd = ['--huntrleaks', '3:3:']
1170 if run_workers:
1171 cmd.append('-j1')
1172 cmd.append(test)
1173 output = self.run_tests(*cmd,
1174 exitcode=EXITCODE_BAD_TEST,
1175 stderr=subprocess.STDOUT)
1176 self.check_executed_tests(output, [test], failed=test, stats=1)
1177
1178 line = r'beginning 6 repetitions. .*\n123:456\n[.0-9X]{3} 111\n'
1179 self.check_line(output, line)
1180
1181 line2 = '%s leaked [1, 1, 1] %s, sum=3\n' % (test, what)
1182 self.assertIn(line2, output)
1183
1184 with open(filename) as fp:
1185 reflog = fp.read()
1186 self.assertIn(line2, reflog)
1187
1188 @unittest.skipUnless(support.Py_DEBUG, 'need a debug build')
1189 def check_huntrleaks(self, *, run_workers: bool):
1190 # test --huntrleaks
1191 code = textwrap.dedent("""
1192 import unittest
1193
1194 GLOBAL_LIST = []
1195
1196 class RefLeakTest(unittest.TestCase):
1197 def test_leak(self):
1198 GLOBAL_LIST.append(object())
1199 """)
1200 self.check_leak(code, 'references', run_workers=run_workers)
1201
1202 def test_huntrleaks(self):
1203 self.check_huntrleaks(run_workers=False)
1204
1205 def test_huntrleaks_mp(self):
1206 self.check_huntrleaks(run_workers=True)
1207
1208 @unittest.skipUnless(support.Py_DEBUG, 'need a debug build')
1209 def test_huntrleaks_bisect(self):
1210 # test --huntrleaks --bisect
1211 code = textwrap.dedent("""
1212 import unittest
1213
1214 GLOBAL_LIST = []
1215
1216 class RefLeakTest(unittest.TestCase):
1217 def test1(self):
1218 pass
1219
1220 def test2(self):
1221 pass
1222
1223 def test3(self):
1224 GLOBAL_LIST.append(object())
1225
1226 def test4(self):
1227 pass
1228 """)
1229
1230 test = self.create_test('huntrleaks', code=code)
1231
1232 filename = 'reflog.txt'
1233 self.addCleanup(os_helper.unlink, filename)
1234 cmd = ['--huntrleaks', '3:3:', '--bisect', test]
1235 output = self.run_tests(*cmd,
1236 exitcode=EXITCODE_BAD_TEST,
1237 stderr=subprocess.STDOUT)
1238
1239 self.assertIn(f"Bisect {test}", output)
1240 self.assertIn(f"Bisect {test}: exit code 0", output)
1241
1242 # test3 is the one which leaks
1243 self.assertIn("Bisection completed in", output)
1244 self.assertIn(
1245 "Tests (1):\n"
1246 f"* {test}.RefLeakTest.test3\n",
1247 output)
1248
1249 @unittest.skipUnless(support.Py_DEBUG, 'need a debug build')
1250 def test_huntrleaks_fd_leak(self):
1251 # test --huntrleaks for file descriptor leak
1252 code = textwrap.dedent("""
1253 import os
1254 import unittest
1255
1256 class FDLeakTest(unittest.TestCase):
1257 def test_leak(self):
1258 fd = os.open(__file__, os.O_RDONLY)
1259 # bug: never close the file descriptor
1260 """)
1261 self.check_leak(code, 'file descriptors')
1262
1263 def test_list_tests(self):
1264 # test --list-tests
1265 tests = [self.create_test() for i in range(5)]
1266 output = self.run_tests('--list-tests', *tests)
1267 self.assertEqual(output.rstrip().splitlines(),
1268 tests)
1269
1270 def test_list_cases(self):
1271 # test --list-cases
1272 code = textwrap.dedent("""
1273 import unittest
1274
1275 class Tests(unittest.TestCase):
1276 def test_method1(self):
1277 pass
1278 def test_method2(self):
1279 pass
1280 """)
1281 testname = self.create_test(code=code)
1282
1283 # Test --list-cases
1284 all_methods = ['%s.Tests.test_method1' % testname,
1285 '%s.Tests.test_method2' % testname]
1286 output = self.run_tests('--list-cases', testname)
1287 self.assertEqual(output.splitlines(), all_methods)
1288
1289 # Test --list-cases with --match
1290 all_methods = ['%s.Tests.test_method1' % testname]
1291 output = self.run_tests('--list-cases',
1292 '-m', 'test_method1',
1293 testname)
1294 self.assertEqual(output.splitlines(), all_methods)
1295
1296 @support.cpython_only
1297 def test_crashed(self):
1298 # Any code which causes a crash
1299 code = 'import faulthandler; faulthandler._sigsegv()'
1300 crash_test = self.create_test(name="crash", code=code)
1301
1302 tests = [crash_test]
1303 output = self.run_tests("-j2", *tests, exitcode=EXITCODE_BAD_TEST)
1304 self.check_executed_tests(output, tests, failed=crash_test,
1305 parallel=True, stats=0)
1306
1307 def parse_methods(self, output):
1308 regex = re.compile("^(test[^ ]+).*ok$", flags=re.MULTILINE)
1309 return [match.group(1) for match in regex.finditer(output)]
1310
1311 def test_ignorefile(self):
1312 code = textwrap.dedent("""
1313 import unittest
1314
1315 class Tests(unittest.TestCase):
1316 def test_method1(self):
1317 pass
1318 def test_method2(self):
1319 pass
1320 def test_method3(self):
1321 pass
1322 def test_method4(self):
1323 pass
1324 """)
1325 testname = self.create_test(code=code)
1326
1327 # only run a subset
1328 filename = os_helper.TESTFN
1329 self.addCleanup(os_helper.unlink, filename)
1330
1331 subset = [
1332 # only ignore the method name
1333 'test_method1',
1334 # ignore the full identifier
1335 '%s.Tests.test_method3' % testname]
1336 with open(filename, "w") as fp:
1337 for name in subset:
1338 print(name, file=fp)
1339
1340 output = self.run_tests("-v", "--ignorefile", filename, testname)
1341 methods = self.parse_methods(output)
1342 subset = ['test_method2', 'test_method4']
1343 self.assertEqual(methods, subset)
1344
1345 def test_matchfile(self):
1346 code = textwrap.dedent("""
1347 import unittest
1348
1349 class Tests(unittest.TestCase):
1350 def test_method1(self):
1351 pass
1352 def test_method2(self):
1353 pass
1354 def test_method3(self):
1355 pass
1356 def test_method4(self):
1357 pass
1358 """)
1359 all_methods = ['test_method1', 'test_method2',
1360 'test_method3', 'test_method4']
1361 testname = self.create_test(code=code)
1362
1363 # by default, all methods should be run
1364 output = self.run_tests("-v", testname)
1365 methods = self.parse_methods(output)
1366 self.assertEqual(methods, all_methods)
1367
1368 # only run a subset
1369 filename = os_helper.TESTFN
1370 self.addCleanup(os_helper.unlink, filename)
1371
1372 subset = [
1373 # only match the method name
1374 'test_method1',
1375 # match the full identifier
1376 '%s.Tests.test_method3' % testname]
1377 with open(filename, "w") as fp:
1378 for name in subset:
1379 print(name, file=fp)
1380
1381 output = self.run_tests("-v", "--matchfile", filename, testname)
1382 methods = self.parse_methods(output)
1383 subset = ['test_method1', 'test_method3']
1384 self.assertEqual(methods, subset)
1385
1386 def test_env_changed(self):
1387 code = textwrap.dedent("""
1388 import unittest
1389
1390 class Tests(unittest.TestCase):
1391 def test_env_changed(self):
1392 open("env_changed", "w").close()
1393 """)
1394 testname = self.create_test(code=code)
1395
1396 # don't fail by default
1397 output = self.run_tests(testname)
1398 self.check_executed_tests(output, [testname],
1399 env_changed=testname, stats=1)
1400
1401 # fail with --fail-env-changed
1402 output = self.run_tests("--fail-env-changed", testname,
1403 exitcode=EXITCODE_ENV_CHANGED)
1404 self.check_executed_tests(output, [testname], env_changed=testname,
1405 fail_env_changed=True, stats=1)
1406
1407 # rerun
1408 output = self.run_tests("--rerun", testname)
1409 self.check_executed_tests(output, [testname],
1410 env_changed=testname,
1411 rerun=Rerun(testname,
1412 match=None,
1413 success=True),
1414 stats=2)
1415
1416 def test_rerun_fail(self):
1417 # FAILURE then FAILURE
1418 code = textwrap.dedent("""
1419 import unittest
1420
1421 class Tests(unittest.TestCase):
1422 def test_succeed(self):
1423 return
1424
1425 def test_fail_always(self):
1426 # test that always fails
1427 self.fail("bug")
1428 """)
1429 testname = self.create_test(code=code)
1430
1431 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1432 self.check_executed_tests(output, [testname],
1433 rerun=Rerun(testname,
1434 "test_fail_always",
1435 success=False),
1436 stats=TestStats(3, 2))
1437
1438 def test_rerun_success(self):
1439 # FAILURE then SUCCESS
1440 marker_filename = os.path.abspath("regrtest_marker_filename")
1441 self.addCleanup(os_helper.unlink, marker_filename)
1442 self.assertFalse(os.path.exists(marker_filename))
1443
1444 code = textwrap.dedent(f"""
1445 import os.path
1446 import unittest
1447
1448 marker_filename = {marker_filename!r}
1449
1450 class Tests(unittest.TestCase):
1451 def test_succeed(self):
1452 return
1453
1454 def test_fail_once(self):
1455 if not os.path.exists(marker_filename):
1456 open(marker_filename, "w").close()
1457 self.fail("bug")
1458 """)
1459 testname = self.create_test(code=code)
1460
1461 # FAILURE then SUCCESS => exit code 0
1462 output = self.run_tests("--rerun", testname, exitcode=0)
1463 self.check_executed_tests(output, [testname],
1464 rerun=Rerun(testname,
1465 match="test_fail_once",
1466 success=True),
1467 stats=TestStats(3, 1))
1468 os_helper.unlink(marker_filename)
1469
1470 # with --fail-rerun, exit code EXITCODE_RERUN_FAIL
1471 # on "FAILURE then SUCCESS" state.
1472 output = self.run_tests("--rerun", "--fail-rerun", testname,
1473 exitcode=EXITCODE_RERUN_FAIL)
1474 self.check_executed_tests(output, [testname],
1475 rerun=Rerun(testname,
1476 match="test_fail_once",
1477 success=True),
1478 stats=TestStats(3, 1))
1479 os_helper.unlink(marker_filename)
1480
1481 def test_rerun_setup_class_hook_failure(self):
1482 # FAILURE then FAILURE
1483 code = textwrap.dedent("""
1484 import unittest
1485
1486 class ExampleTests(unittest.TestCase):
1487 @classmethod
1488 def setUpClass(self):
1489 raise RuntimeError('Fail')
1490
1491 def test_success(self):
1492 return
1493 """)
1494 testname = self.create_test(code=code)
1495
1496 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1497 self.check_executed_tests(output, testname,
1498 failed=[testname],
1499 rerun=Rerun(testname,
1500 match="ExampleTests",
1501 success=False),
1502 stats=0)
1503
1504 def test_rerun_teardown_class_hook_failure(self):
1505 # FAILURE then FAILURE
1506 code = textwrap.dedent("""
1507 import unittest
1508
1509 class ExampleTests(unittest.TestCase):
1510 @classmethod
1511 def tearDownClass(self):
1512 raise RuntimeError('Fail')
1513
1514 def test_success(self):
1515 return
1516 """)
1517 testname = self.create_test(code=code)
1518
1519 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1520 self.check_executed_tests(output, testname,
1521 failed=[testname],
1522 rerun=Rerun(testname,
1523 match="ExampleTests",
1524 success=False),
1525 stats=2)
1526
1527 def test_rerun_setup_module_hook_failure(self):
1528 # FAILURE then FAILURE
1529 code = textwrap.dedent("""
1530 import unittest
1531
1532 def setUpModule():
1533 raise RuntimeError('Fail')
1534
1535 class ExampleTests(unittest.TestCase):
1536 def test_success(self):
1537 return
1538 """)
1539 testname = self.create_test(code=code)
1540
1541 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1542 self.check_executed_tests(output, testname,
1543 failed=[testname],
1544 rerun=Rerun(testname,
1545 match=None,
1546 success=False),
1547 stats=0)
1548
1549 def test_rerun_teardown_module_hook_failure(self):
1550 # FAILURE then FAILURE
1551 code = textwrap.dedent("""
1552 import unittest
1553
1554 def tearDownModule():
1555 raise RuntimeError('Fail')
1556
1557 class ExampleTests(unittest.TestCase):
1558 def test_success(self):
1559 return
1560 """)
1561 testname = self.create_test(code=code)
1562
1563 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1564 self.check_executed_tests(output, [testname],
1565 failed=[testname],
1566 rerun=Rerun(testname,
1567 match=None,
1568 success=False),
1569 stats=2)
1570
1571 def test_rerun_setup_hook_failure(self):
1572 # FAILURE then FAILURE
1573 code = textwrap.dedent("""
1574 import unittest
1575
1576 class ExampleTests(unittest.TestCase):
1577 def setUp(self):
1578 raise RuntimeError('Fail')
1579
1580 def test_success(self):
1581 return
1582 """)
1583 testname = self.create_test(code=code)
1584
1585 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1586 self.check_executed_tests(output, testname,
1587 failed=[testname],
1588 rerun=Rerun(testname,
1589 match="test_success",
1590 success=False),
1591 stats=2)
1592
1593 def test_rerun_teardown_hook_failure(self):
1594 # FAILURE then FAILURE
1595 code = textwrap.dedent("""
1596 import unittest
1597
1598 class ExampleTests(unittest.TestCase):
1599 def tearDown(self):
1600 raise RuntimeError('Fail')
1601
1602 def test_success(self):
1603 return
1604 """)
1605 testname = self.create_test(code=code)
1606
1607 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1608 self.check_executed_tests(output, testname,
1609 failed=[testname],
1610 rerun=Rerun(testname,
1611 match="test_success",
1612 success=False),
1613 stats=2)
1614
1615 def test_rerun_async_setup_hook_failure(self):
1616 # FAILURE then FAILURE
1617 code = textwrap.dedent("""
1618 import unittest
1619
1620 class ExampleTests(unittest.IsolatedAsyncioTestCase):
1621 async def asyncSetUp(self):
1622 raise RuntimeError('Fail')
1623
1624 async def test_success(self):
1625 return
1626 """)
1627 testname = self.create_test(code=code)
1628
1629 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1630 self.check_executed_tests(output, testname,
1631 rerun=Rerun(testname,
1632 match="test_success",
1633 success=False),
1634 stats=2)
1635
1636 def test_rerun_async_teardown_hook_failure(self):
1637 # FAILURE then FAILURE
1638 code = textwrap.dedent("""
1639 import unittest
1640
1641 class ExampleTests(unittest.IsolatedAsyncioTestCase):
1642 async def asyncTearDown(self):
1643 raise RuntimeError('Fail')
1644
1645 async def test_success(self):
1646 return
1647 """)
1648 testname = self.create_test(code=code)
1649
1650 output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST)
1651 self.check_executed_tests(output, testname,
1652 failed=[testname],
1653 rerun=Rerun(testname,
1654 match="test_success",
1655 success=False),
1656 stats=2)
1657
1658 def test_no_tests_ran(self):
1659 code = textwrap.dedent("""
1660 import unittest
1661
1662 class Tests(unittest.TestCase):
1663 def test_bug(self):
1664 pass
1665 """)
1666 testname = self.create_test(code=code)
1667
1668 output = self.run_tests(testname, "-m", "nosuchtest",
1669 exitcode=EXITCODE_NO_TESTS_RAN)
1670 self.check_executed_tests(output, [testname],
1671 run_no_tests=testname,
1672 stats=0, filtered=True)
1673
1674 def test_no_tests_ran_skip(self):
1675 code = textwrap.dedent("""
1676 import unittest
1677
1678 class Tests(unittest.TestCase):
1679 def test_skipped(self):
1680 self.skipTest("because")
1681 """)
1682 testname = self.create_test(code=code)
1683
1684 output = self.run_tests(testname)
1685 self.check_executed_tests(output, [testname],
1686 stats=TestStats(1, skipped=1))
1687
1688 def test_no_tests_ran_multiple_tests_nonexistent(self):
1689 code = textwrap.dedent("""
1690 import unittest
1691
1692 class Tests(unittest.TestCase):
1693 def test_bug(self):
1694 pass
1695 """)
1696 testname = self.create_test(code=code)
1697 testname2 = self.create_test(code=code)
1698
1699 output = self.run_tests(testname, testname2, "-m", "nosuchtest",
1700 exitcode=EXITCODE_NO_TESTS_RAN)
1701 self.check_executed_tests(output, [testname, testname2],
1702 run_no_tests=[testname, testname2],
1703 stats=0, filtered=True)
1704
1705 def test_no_test_ran_some_test_exist_some_not(self):
1706 code = textwrap.dedent("""
1707 import unittest
1708
1709 class Tests(unittest.TestCase):
1710 def test_bug(self):
1711 pass
1712 """)
1713 testname = self.create_test(code=code)
1714 other_code = textwrap.dedent("""
1715 import unittest
1716
1717 class Tests(unittest.TestCase):
1718 def test_other_bug(self):
1719 pass
1720 """)
1721 testname2 = self.create_test(code=other_code)
1722
1723 output = self.run_tests(testname, testname2, "-m", "nosuchtest",
1724 "-m", "test_other_bug", exitcode=0)
1725 self.check_executed_tests(output, [testname, testname2],
1726 run_no_tests=[testname],
1727 stats=1, filtered=True)
1728
1729 @support.cpython_only
1730 def test_uncollectable(self):
1731 code = textwrap.dedent(r"""
1732 import _testcapi
1733 import gc
1734 import unittest
1735
1736 @_testcapi.with_tp_del
1737 class Garbage:
1738 def __tp_del__(self):
1739 pass
1740
1741 class Tests(unittest.TestCase):
1742 def test_garbage(self):
1743 # create an uncollectable object
1744 obj = Garbage()
1745 obj.ref_cycle = obj
1746 obj = None
1747 """)
1748 testname = self.create_test(code=code)
1749
1750 output = self.run_tests("--fail-env-changed", testname,
1751 exitcode=EXITCODE_ENV_CHANGED)
1752 self.check_executed_tests(output, [testname],
1753 env_changed=[testname],
1754 fail_env_changed=True,
1755 stats=1)
1756
1757 def test_multiprocessing_timeout(self):
1758 code = textwrap.dedent(r"""
1759 import time
1760 import unittest
1761 try:
1762 import faulthandler
1763 except ImportError:
1764 faulthandler = None
1765
1766 class Tests(unittest.TestCase):
1767 # test hangs and so should be stopped by the timeout
1768 def test_sleep(self):
1769 # we want to test regrtest multiprocessing timeout,
1770 # not faulthandler timeout
1771 if faulthandler is not None:
1772 faulthandler.cancel_dump_traceback_later()
1773
1774 time.sleep(60 * 5)
1775 """)
1776 testname = self.create_test(code=code)
1777
1778 output = self.run_tests("-j2", "--timeout=1.0", testname,
1779 exitcode=EXITCODE_BAD_TEST)
1780 self.check_executed_tests(output, [testname],
1781 failed=testname, stats=0)
1782 self.assertRegex(output,
1783 re.compile('%s timed out' % testname, re.MULTILINE))
1784
1785 def test_unraisable_exc(self):
1786 # --fail-env-changed must catch unraisable exception.
1787 # The exception must be displayed even if sys.stderr is redirected.
1788 code = textwrap.dedent(r"""
1789 import gc
1790 import unittest
1791 import weakref
1792 from test.support import captured_stderr
1793
1794 class MyObject:
1795 pass
1796
1797 def weakref_callback(obj):
1798 raise Exception("weakref callback bug")
1799
1800 class Tests(unittest.TestCase):
1801 def test_unraisable_exc(self):
1802 obj = MyObject()
1803 ref = weakref.ref(obj, weakref_callback)
1804 with captured_stderr() as stderr:
1805 # call weakref_callback() which logs
1806 # an unraisable exception
1807 obj = None
1808 gc.collect()
1809 self.assertEqual(stderr.getvalue(), '')
1810 """)
1811 testname = self.create_test(code=code)
1812
1813 output = self.run_tests("--fail-env-changed", "-v", testname,
1814 exitcode=EXITCODE_ENV_CHANGED)
1815 self.check_executed_tests(output, [testname],
1816 env_changed=[testname],
1817 fail_env_changed=True,
1818 stats=1)
1819 self.assertIn("Warning -- Unraisable exception", output)
1820 self.assertIn("Exception: weakref callback bug", output)
1821
1822 def test_threading_excepthook(self):
1823 # --fail-env-changed must catch uncaught thread exception.
1824 # The exception must be displayed even if sys.stderr is redirected.
1825 code = textwrap.dedent(r"""
1826 import threading
1827 import unittest
1828 from test.support import captured_stderr
1829
1830 class MyObject:
1831 pass
1832
1833 def func_bug():
1834 raise Exception("bug in thread")
1835
1836 class Tests(unittest.TestCase):
1837 def test_threading_excepthook(self):
1838 with captured_stderr() as stderr:
1839 thread = threading.Thread(target=func_bug)
1840 thread.start()
1841 thread.join()
1842 self.assertEqual(stderr.getvalue(), '')
1843 """)
1844 testname = self.create_test(code=code)
1845
1846 output = self.run_tests("--fail-env-changed", "-v", testname,
1847 exitcode=EXITCODE_ENV_CHANGED)
1848 self.check_executed_tests(output, [testname],
1849 env_changed=[testname],
1850 fail_env_changed=True,
1851 stats=1)
1852 self.assertIn("Warning -- Uncaught thread exception", output)
1853 self.assertIn("Exception: bug in thread", output)
1854
1855 def test_print_warning(self):
1856 # bpo-45410: The order of messages must be preserved when -W and
1857 # support.print_warning() are used.
1858 code = textwrap.dedent(r"""
1859 import sys
1860 import unittest
1861 from test import support
1862
1863 class MyObject:
1864 pass
1865
1866 def func_bug():
1867 raise Exception("bug in thread")
1868
1869 class Tests(unittest.TestCase):
1870 def test_print_warning(self):
1871 print("msg1: stdout")
1872 support.print_warning("msg2: print_warning")
1873 # Fail with ENV CHANGED to see print_warning() log
1874 support.environment_altered = True
1875 """)
1876 testname = self.create_test(code=code)
1877
1878 # Expect an output like:
1879 #
1880 # test_threading_excepthook (test.test_x.Tests) ... msg1: stdout
1881 # Warning -- msg2: print_warning
1882 # ok
1883 regex = (r"test_print_warning.*msg1: stdout\n"
1884 r"Warning -- msg2: print_warning\n"
1885 r"ok\n")
1886 for option in ("-v", "-W"):
1887 with self.subTest(option=option):
1888 cmd = ["--fail-env-changed", option, testname]
1889 output = self.run_tests(*cmd, exitcode=EXITCODE_ENV_CHANGED)
1890 self.check_executed_tests(output, [testname],
1891 env_changed=[testname],
1892 fail_env_changed=True,
1893 stats=1)
1894 self.assertRegex(output, regex)
1895
1896 def test_unicode_guard_env(self):
1897 guard = os.environ.get(setup.UNICODE_GUARD_ENV)
1898 self.assertIsNotNone(guard, f"{setup.UNICODE_GUARD_ENV} not set")
1899 if guard.isascii():
1900 # Skip to signify that the env var value was changed by the user;
1901 # possibly to something ASCII to work around Unicode issues.
1902 self.skipTest("Modified guard")
1903
1904 def test_cleanup(self):
1905 dirname = os.path.join(self.tmptestdir, "test_python_123")
1906 os.mkdir(dirname)
1907 filename = os.path.join(self.tmptestdir, "test_python_456")
1908 open(filename, "wb").close()
1909 names = [dirname, filename]
1910
1911 cmdargs = ['-m', 'test',
1912 '--tempdir=%s' % self.tmptestdir,
1913 '--cleanup']
1914 self.run_python(cmdargs)
1915
1916 for name in names:
1917 self.assertFalse(os.path.exists(name), name)
1918
1919 @unittest.skipIf(support.is_wasi,
1920 'checking temp files is not implemented on WASI')
1921 def test_leak_tmp_file(self):
1922 code = textwrap.dedent(r"""
1923 import os.path
1924 import tempfile
1925 import unittest
1926
1927 class FileTests(unittest.TestCase):
1928 def test_leak_tmp_file(self):
1929 filename = os.path.join(tempfile.gettempdir(), 'mytmpfile')
1930 with open(filename, "wb") as fp:
1931 fp.write(b'content')
1932 """)
1933 testnames = [self.create_test(code=code) for _ in range(3)]
1934
1935 output = self.run_tests("--fail-env-changed", "-v", "-j2", *testnames,
1936 exitcode=EXITCODE_ENV_CHANGED)
1937 self.check_executed_tests(output, testnames,
1938 env_changed=testnames,
1939 fail_env_changed=True,
1940 parallel=True,
1941 stats=len(testnames))
1942 for testname in testnames:
1943 self.assertIn(f"Warning -- {testname} leaked temporary "
1944 f"files (1): mytmpfile",
1945 output)
1946
1947 def test_worker_decode_error(self):
1948 # gh-109425: Use "backslashreplace" error handler to decode stdout.
1949 if sys.platform == 'win32':
1950 encoding = locale.getencoding()
1951 else:
1952 encoding = sys.stdout.encoding
1953 if encoding is None:
1954 encoding = sys.__stdout__.encoding
1955 if encoding is None:
1956 self.skipTest("cannot get regrtest worker encoding")
1957
1958 nonascii = bytes(ch for ch in range(128, 256))
1959 corrupted_output = b"nonascii:%s\n" % (nonascii,)
1960 # gh-108989: On Windows, assertion errors are written in UTF-16: when
1961 # decoded each letter is follow by a NUL character.
1962 assertion_failed = 'Assertion failed: tstate_is_alive(tstate)\n'
1963 corrupted_output += assertion_failed.encode('utf-16-le')
1964 try:
1965 corrupted_output.decode(encoding)
1966 except UnicodeDecodeError:
1967 pass
1968 else:
1969 self.skipTest(f"{encoding} can decode non-ASCII bytes")
1970
1971 expected_line = corrupted_output.decode(encoding, 'backslashreplace')
1972
1973 code = textwrap.dedent(fr"""
1974 import sys
1975 import unittest
1976
1977 class Tests(unittest.TestCase):
1978 def test_pass(self):
1979 pass
1980
1981 # bytes which cannot be decoded from UTF-8
1982 corrupted_output = {corrupted_output!a}
1983 sys.stdout.buffer.write(corrupted_output)
1984 sys.stdout.buffer.flush()
1985 """)
1986 testname = self.create_test(code=code)
1987
1988 output = self.run_tests("--fail-env-changed", "-v", "-j1", testname)
1989 self.check_executed_tests(output, [testname],
1990 parallel=True,
1991 stats=1)
1992 self.check_line(output, expected_line, regex=False)
1993
1994 def test_doctest(self):
1995 code = textwrap.dedent(r'''
1996 import doctest
1997 import sys
1998 from test import support
1999
2000 def my_function():
2001 """
2002 Pass:
2003
2004 >>> 1 + 1
2005 2
2006
2007 Failure:
2008
2009 >>> 2 + 3
2010 23
2011 >>> 1 + 1
2012 11
2013
2014 Skipped test (ignored):
2015
2016 >>> id(1.0) # doctest: +SKIP
2017 7948648
2018 """
2019
2020 def load_tests(loader, tests, pattern):
2021 tests.addTest(doctest.DocTestSuite())
2022 return tests
2023 ''')
2024 testname = self.create_test(code=code)
2025
2026 output = self.run_tests("--fail-env-changed", "-v", "-j1", testname,
2027 exitcode=EXITCODE_BAD_TEST)
2028 self.check_executed_tests(output, [testname],
2029 failed=[testname],
2030 parallel=True,
2031 stats=TestStats(1, 1, 0))
2032
2033 def _check_random_seed(self, run_workers: bool):
2034 # gh-109276: When -r/--randomize is used, random.seed() is called
2035 # with the same random seed before running each test file.
2036 code = textwrap.dedent(r'''
2037 import random
2038 import unittest
2039
2040 class RandomSeedTest(unittest.TestCase):
2041 def test_randint(self):
2042 numbers = [random.randint(0, 1000) for _ in range(10)]
2043 print(f"Random numbers: {numbers}")
2044 ''')
2045 tests = [self.create_test(name=f'test_random{i}', code=code)
2046 for i in range(1, 3+1)]
2047
2048 random_seed = 856_656_202
2049 cmd = ["--randomize", f"--randseed={random_seed}"]
2050 if run_workers:
2051 # run as many worker processes than the number of tests
2052 cmd.append(f'-j{len(tests)}')
2053 cmd.extend(tests)
2054 output = self.run_tests(*cmd)
2055
2056 random.seed(random_seed)
2057 # Make the assumption that nothing consume entropy between libregrest
2058 # setup_tests() which calls random.seed() and RandomSeedTest calling
2059 # random.randint().
2060 numbers = [random.randint(0, 1000) for _ in range(10)]
2061 expected = f"Random numbers: {numbers}"
2062
2063 regex = r'^Random numbers: .*$'
2064 matches = re.findall(regex, output, flags=re.MULTILINE)
2065 self.assertEqual(matches, [expected] * len(tests))
2066
2067 def test_random_seed(self):
2068 self._check_random_seed(run_workers=False)
2069
2070 def test_random_seed_workers(self):
2071 self._check_random_seed(run_workers=True)
2072
2073 def test_python_command(self):
2074 code = textwrap.dedent(r"""
2075 import sys
2076 import unittest
2077
2078 class WorkerTests(unittest.TestCase):
2079 def test_dev_mode(self):
2080 self.assertTrue(sys.flags.dev_mode)
2081 """)
2082 tests = [self.create_test(code=code) for _ in range(3)]
2083
2084 # Custom Python command: "python -X dev"
2085 python_cmd = [sys.executable, '-X', 'dev']
2086 # test.libregrtest.cmdline uses shlex.split() to parse the Python
2087 # command line string
2088 python_cmd = shlex.join(python_cmd)
2089
2090 output = self.run_tests("--python", python_cmd, "-j0", *tests)
2091 self.check_executed_tests(output, tests,
2092 stats=len(tests), parallel=True)
2093
2094 def test_unload_tests(self):
2095 # Test that unloading test modules does not break tests
2096 # that import from other tests.
2097 # The test execution order matters for this test.
2098 # Both test_regrtest_a and test_regrtest_c which are executed before
2099 # and after test_regrtest_b import a submodule from the test_regrtest_b
2100 # package and use it in testing. test_regrtest_b itself does not import
2101 # that submodule.
2102 # Previously test_regrtest_c failed because test_regrtest_b.util in
2103 # sys.modules was left after test_regrtest_a (making the import
2104 # statement no-op), but new test_regrtest_b without the util attribute
2105 # was imported for test_regrtest_b.
2106 testdir = os.path.join(os.path.dirname(__file__),
2107 'regrtestdata', 'import_from_tests')
2108 tests = [f'test_regrtest_{name}' for name in ('a', 'b', 'c')]
2109 args = ['-Wd', '-E', '-bb', '-m', 'test', '--testdir=%s' % testdir, *tests]
2110 output = self.run_python(args)
2111 self.check_executed_tests(output, tests, stats=3)
2112
2113 def check_add_python_opts(self, option):
2114 # --fast-ci and --slow-ci add "-u -W default -bb -E" options to Python
2115 code = textwrap.dedent(r"""
2116 import sys
2117 import unittest
2118 from test import support
2119 try:
2120 from _testinternalcapi import get_config
2121 except ImportError:
2122 get_config = None
2123
2124 # WASI/WASM buildbots don't use -E option
2125 use_environment = (support.is_emscripten or support.is_wasi)
2126
2127 class WorkerTests(unittest.TestCase):
2128 @unittest.skipUnless(get_config is not None, 'need get_config()')
2129 def test_config(self):
2130 config = get_config()['config']
2131 # -u option
2132 self.assertEqual(config['buffered_stdio'], 0)
2133 # -W default option
2134 self.assertTrue(config['warnoptions'], ['default'])
2135 # -bb option
2136 self.assertTrue(config['bytes_warning'], 2)
2137 # -E option
2138 self.assertTrue(config['use_environment'], use_environment)
2139
2140 def test_python_opts(self):
2141 # -u option
2142 self.assertTrue(sys.__stdout__.write_through)
2143 self.assertTrue(sys.__stderr__.write_through)
2144
2145 # -W default option
2146 self.assertTrue(sys.warnoptions, ['default'])
2147
2148 # -bb option
2149 self.assertEqual(sys.flags.bytes_warning, 2)
2150
2151 # -E option
2152 self.assertEqual(not sys.flags.ignore_environment,
2153 use_environment)
2154 """)
2155 testname = self.create_test(code=code)
2156
2157 # Use directly subprocess to control the exact command line
2158 cmd = [sys.executable,
2159 "-m", "test", option,
2160 f'--testdir={self.tmptestdir}',
2161 testname]
2162 proc = subprocess.run(cmd,
2163 stdout=subprocess.PIPE,
2164 stderr=subprocess.STDOUT,
2165 text=True)
2166 self.assertEqual(proc.returncode, 0, proc)
2167
2168 def test_add_python_opts(self):
2169 for opt in ("--fast-ci", "--slow-ci"):
2170 with self.subTest(opt=opt):
2171 self.check_add_python_opts(opt)
2172
2173 # gh-76319: Raising SIGSEGV on Android may not cause a crash.
2174 @unittest.skipIf(support.is_android,
2175 'raising SIGSEGV on Android is unreliable')
2176 def test_worker_output_on_failure(self):
2177 try:
2178 from faulthandler import _sigsegv
2179 except ImportError:
2180 self.skipTest("need faulthandler._sigsegv")
2181
2182 code = textwrap.dedent(r"""
2183 import faulthandler
2184 import unittest
2185 from test import support
2186
2187 class CrashTests(unittest.TestCase):
2188 def test_crash(self):
2189 print("just before crash!", flush=True)
2190
2191 with support.SuppressCrashReport():
2192 faulthandler._sigsegv(True)
2193 """)
2194 testname = self.create_test(code=code)
2195
2196 # Sanitizers must not handle SIGSEGV (ex: for test_enable_fd())
2197 env = dict(os.environ)
2198 option = 'handle_segv=0'
2199 support.set_sanitizer_env_var(env, option)
2200
2201 output = self.run_tests("-j1", testname,
2202 exitcode=EXITCODE_BAD_TEST,
2203 env=env)
2204 self.check_executed_tests(output, testname,
2205 failed=[testname],
2206 stats=0, parallel=True)
2207 if not support.MS_WINDOWS:
2208 exitcode = -int(signal.SIGSEGV)
2209 self.assertIn(f"Exit code {exitcode} (SIGSEGV)", output)
2210 self.check_line(output, "just before crash!", full=True, regex=False)
2211
2212 def test_verbose3(self):
2213 code = textwrap.dedent(r"""
2214 import unittest
2215 from test import support
2216
2217 class VerboseTests(unittest.TestCase):
2218 def test_pass(self):
2219 print("SPAM SPAM SPAM")
2220 """)
2221 testname = self.create_test(code=code)
2222
2223 # Run sequentially
2224 output = self.run_tests("--verbose3", testname)
2225 self.check_executed_tests(output, testname, stats=1)
2226 self.assertNotIn('SPAM SPAM SPAM', output)
2227
2228 # -R option needs a debug build
2229 if support.Py_DEBUG:
2230 # Check for reference leaks, run in parallel
2231 output = self.run_tests("-R", "3:3", "-j1", "--verbose3", testname)
2232 self.check_executed_tests(output, testname, stats=1, parallel=True)
2233 self.assertNotIn('SPAM SPAM SPAM', output)
2234
2235
2236 class TestUtils(unittest.TestCase):
2237 def test_format_duration(self):
2238 self.assertEqual(utils.format_duration(0),
2239 '0 ms')
2240 self.assertEqual(utils.format_duration(1e-9),
2241 '1 ms')
2242 self.assertEqual(utils.format_duration(10e-3),
2243 '10 ms')
2244 self.assertEqual(utils.format_duration(1.5),
2245 '1.5 sec')
2246 self.assertEqual(utils.format_duration(1),
2247 '1.0 sec')
2248 self.assertEqual(utils.format_duration(2 * 60),
2249 '2 min')
2250 self.assertEqual(utils.format_duration(2 * 60 + 1),
2251 '2 min 1 sec')
2252 self.assertEqual(utils.format_duration(3 * 3600),
2253 '3 hour')
2254 self.assertEqual(utils.format_duration(3 * 3600 + 2 * 60 + 1),
2255 '3 hour 2 min')
2256 self.assertEqual(utils.format_duration(3 * 3600 + 1),
2257 '3 hour 1 sec')
2258
2259 def test_normalize_test_name(self):
2260 normalize = normalize_test_name
2261 self.assertEqual(normalize('test_access (test.test_os.FileTests.test_access)'),
2262 'test_access')
2263 self.assertEqual(normalize('setUpClass (test.test_os.ChownFileTests)', is_error=True),
2264 'ChownFileTests')
2265 self.assertEqual(normalize('test_success (test.test_bug.ExampleTests.test_success)', is_error=True),
2266 'test_success')
2267 self.assertIsNone(normalize('setUpModule (test.test_x)', is_error=True))
2268 self.assertIsNone(normalize('tearDownModule (test.test_module)', is_error=True))
2269
2270 def test_get_signal_name(self):
2271 for exitcode, expected in (
2272 (-int(signal.SIGINT), 'SIGINT'),
2273 (-int(signal.SIGSEGV), 'SIGSEGV'),
2274 (3221225477, "STATUS_ACCESS_VIOLATION"),
2275 (0xC00000FD, "STATUS_STACK_OVERFLOW"),
2276 ):
2277 self.assertEqual(utils.get_signal_name(exitcode), expected, exitcode)
2278
2279 def test_format_resources(self):
2280 format_resources = utils.format_resources
2281 ALL_RESOURCES = utils.ALL_RESOURCES
2282 self.assertEqual(
2283 format_resources(("network",)),
2284 'resources (1): network')
2285 self.assertEqual(
2286 format_resources(("audio", "decimal", "network")),
2287 'resources (3): audio,decimal,network')
2288 self.assertEqual(
2289 format_resources(ALL_RESOURCES),
2290 'resources: all')
2291 self.assertEqual(
2292 format_resources(tuple(name for name in ALL_RESOURCES
2293 if name != "cpu")),
2294 'resources: all,-cpu')
2295 self.assertEqual(
2296 format_resources((*ALL_RESOURCES, "tzdata")),
2297 'resources: all,tzdata')
2298
2299 def test_match_test(self):
2300 class Test:
2301 def __init__(self, test_id):
2302 self.test_id = test_id
2303
2304 def id(self):
2305 return self.test_id
2306
2307 # Restore patterns once the test completes
2308 patterns = get_match_tests()
2309 self.addCleanup(set_match_tests, patterns)
2310
2311 test_access = Test('test.test_os.FileTests.test_access')
2312 test_chdir = Test('test.test_os.Win32ErrorTests.test_chdir')
2313 test_copy = Test('test.test_shutil.TestCopy.test_copy')
2314
2315 # Test acceptance
2316 with support.swap_attr(support, '_test_matchers', ()):
2317 # match all
2318 set_match_tests([])
2319 self.assertTrue(match_test(test_access))
2320 self.assertTrue(match_test(test_chdir))
2321
2322 # match all using None
2323 set_match_tests(None)
2324 self.assertTrue(match_test(test_access))
2325 self.assertTrue(match_test(test_chdir))
2326
2327 # match the full test identifier
2328 set_match_tests([(test_access.id(), True)])
2329 self.assertTrue(match_test(test_access))
2330 self.assertFalse(match_test(test_chdir))
2331
2332 # match the module name
2333 set_match_tests([('test_os', True)])
2334 self.assertTrue(match_test(test_access))
2335 self.assertTrue(match_test(test_chdir))
2336 self.assertFalse(match_test(test_copy))
2337
2338 # Test '*' pattern
2339 set_match_tests([('test_*', True)])
2340 self.assertTrue(match_test(test_access))
2341 self.assertTrue(match_test(test_chdir))
2342
2343 # Test case sensitivity
2344 set_match_tests([('filetests', True)])
2345 self.assertFalse(match_test(test_access))
2346 set_match_tests([('FileTests', True)])
2347 self.assertTrue(match_test(test_access))
2348
2349 # Test pattern containing '.' and a '*' metacharacter
2350 set_match_tests([('*test_os.*.test_*', True)])
2351 self.assertTrue(match_test(test_access))
2352 self.assertTrue(match_test(test_chdir))
2353 self.assertFalse(match_test(test_copy))
2354
2355 # Multiple patterns
2356 set_match_tests([(test_access.id(), True), (test_chdir.id(), True)])
2357 self.assertTrue(match_test(test_access))
2358 self.assertTrue(match_test(test_chdir))
2359 self.assertFalse(match_test(test_copy))
2360
2361 set_match_tests([('test_access', True), ('DONTMATCH', True)])
2362 self.assertTrue(match_test(test_access))
2363 self.assertFalse(match_test(test_chdir))
2364
2365 # Test rejection
2366 with support.swap_attr(support, '_test_matchers', ()):
2367 # match the full test identifier
2368 set_match_tests([(test_access.id(), False)])
2369 self.assertFalse(match_test(test_access))
2370 self.assertTrue(match_test(test_chdir))
2371
2372 # match the module name
2373 set_match_tests([('test_os', False)])
2374 self.assertFalse(match_test(test_access))
2375 self.assertFalse(match_test(test_chdir))
2376 self.assertTrue(match_test(test_copy))
2377
2378 # Test '*' pattern
2379 set_match_tests([('test_*', False)])
2380 self.assertFalse(match_test(test_access))
2381 self.assertFalse(match_test(test_chdir))
2382
2383 # Test case sensitivity
2384 set_match_tests([('filetests', False)])
2385 self.assertTrue(match_test(test_access))
2386 set_match_tests([('FileTests', False)])
2387 self.assertFalse(match_test(test_access))
2388
2389 # Test pattern containing '.' and a '*' metacharacter
2390 set_match_tests([('*test_os.*.test_*', False)])
2391 self.assertFalse(match_test(test_access))
2392 self.assertFalse(match_test(test_chdir))
2393 self.assertTrue(match_test(test_copy))
2394
2395 # Multiple patterns
2396 set_match_tests([(test_access.id(), False), (test_chdir.id(), False)])
2397 self.assertFalse(match_test(test_access))
2398 self.assertFalse(match_test(test_chdir))
2399 self.assertTrue(match_test(test_copy))
2400
2401 set_match_tests([('test_access', False), ('DONTMATCH', False)])
2402 self.assertFalse(match_test(test_access))
2403 self.assertTrue(match_test(test_chdir))
2404
2405 # Test mixed filters
2406 with support.swap_attr(support, '_test_matchers', ()):
2407 set_match_tests([('*test_os', False), ('test_access', True)])
2408 self.assertTrue(match_test(test_access))
2409 self.assertFalse(match_test(test_chdir))
2410 self.assertTrue(match_test(test_copy))
2411
2412 set_match_tests([('*test_os', True), ('test_access', False)])
2413 self.assertFalse(match_test(test_access))
2414 self.assertTrue(match_test(test_chdir))
2415 self.assertFalse(match_test(test_copy))
2416
2417
2418 if __name__ == '__main__':
2419 unittest.main()