Debian Codegraph @

Lib/test/test_regrtest.py

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