blob: 211d1b53b5844bd6674ab8ce581667631facd6d2 [file] [log] [blame]
Victor Stinnerd2aff602017-05-09 13:57:20 +02001"""
2Tests of regrtest.py.
3
4Note: test_regrtest cannot be run twice in parallel.
5"""
6from __future__ import print_function
7
8import collections
Victor Stinner453a6852017-05-09 17:06:34 +02009import errno
Victor Stinnerd2aff602017-05-09 13:57:20 +020010import os.path
11import platform
12import re
13import subprocess
14import sys
15import sysconfig
16import tempfile
17import textwrap
18import unittest
19from test import support
20
21
22Py_DEBUG = hasattr(sys, 'getobjects')
23ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..')
24ROOT_DIR = os.path.abspath(os.path.normpath(ROOT_DIR))
25
26TEST_INTERRUPTED = textwrap.dedent("""
27 from signal import SIGINT
28 try:
29 from _testcapi import raise_signal
30 raise_signal(SIGINT)
31 except ImportError:
32 import os
33 os.kill(os.getpid(), SIGINT)
34 """)
35
36
Victor Stinner453a6852017-05-09 17:06:34 +020037SubprocessRun = collections.namedtuple('SubprocessRun',
38 'returncode stdout stderr')
Victor Stinnerd2aff602017-05-09 13:57:20 +020039
40
41class BaseTestCase(unittest.TestCase):
42 TEST_UNIQUE_ID = 1
43 TESTNAME_PREFIX = 'test_regrtest_'
44 TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+'
45
46 def setUp(self):
47 self.testdir = os.path.realpath(os.path.dirname(__file__))
48
49 self.tmptestdir = tempfile.mkdtemp()
50 self.addCleanup(support.rmtree, self.tmptestdir)
51
52 def create_test(self, name=None, code=''):
53 if not name:
54 name = 'noop%s' % BaseTestCase.TEST_UNIQUE_ID
55 BaseTestCase.TEST_UNIQUE_ID += 1
56
57 # test_regrtest cannot be run twice in parallel because
58 # of setUp() and create_test()
59 name = self.TESTNAME_PREFIX + name
60 path = os.path.join(self.tmptestdir, name + '.py')
61
62 self.addCleanup(support.unlink, path)
Victor Stinner453a6852017-05-09 17:06:34 +020063 # Use O_EXCL to ensure that we do not override existing tests
Victor Stinnerd2aff602017-05-09 13:57:20 +020064 try:
65 fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
Victor Stinner453a6852017-05-09 17:06:34 +020066 except OSError as exc:
67 if (exc.errno in (errno.EACCES, errno.EPERM)
68 and not sysconfig.is_python_build()):
Victor Stinnerd2aff602017-05-09 13:57:20 +020069 self.skipTest("cannot write %s: %s" % (path, exc))
Victor Stinner453a6852017-05-09 17:06:34 +020070 else:
71 raise
Victor Stinnerd2aff602017-05-09 13:57:20 +020072 else:
73 with os.fdopen(fd, 'w') as fp:
74 fp.write(code)
75 return name
76
77 def regex_search(self, regex, output):
78 match = re.search(regex, output, re.MULTILINE)
79 if not match:
80 self.fail("%r not found in %r" % (regex, output))
81 return match
82
83 def check_line(self, output, regex):
84 regex = re.compile(r'^' + regex, re.MULTILINE)
85 self.assertRegexpMatches(output, regex)
86
87 def parse_executed_tests(self, output):
Victor Stinner453a6852017-05-09 17:06:34 +020088 regex = (r'^[0-9]+:[0-9]+:[0-9]+ \[ *[0-9]+(?:/ *[0-9]+)*\] (%s)'
Victor Stinnerd2aff602017-05-09 13:57:20 +020089 % self.TESTNAME_REGEX)
90 parser = re.finditer(regex, output, re.MULTILINE)
91 return list(match.group(1) for match in parser)
92
93 def check_executed_tests(self, output, tests, skipped=(), failed=(),
94 omitted=(), randomize=False, interrupted=False):
95 if isinstance(tests, str):
96 tests = [tests]
97 if isinstance(skipped, str):
98 skipped = [skipped]
99 if isinstance(failed, str):
100 failed = [failed]
101 if isinstance(omitted, str):
102 omitted = [omitted]
103 ntest = len(tests)
104 nskipped = len(skipped)
105 nfailed = len(failed)
106 nomitted = len(omitted)
107
108 executed = self.parse_executed_tests(output)
109 if randomize:
110 self.assertEqual(set(executed), set(tests), output)
111 else:
112 self.assertEqual(executed, tests, (executed, tests, output))
113
114 def plural(count):
115 return 's' if count != 1 else ''
116
117 def list_regex(line_format, tests):
118 count = len(tests)
119 names = ' '.join(sorted(tests))
120 regex = line_format % (count, plural(count))
121 regex = r'%s:\n %s$' % (regex, names)
122 return regex
123
124 if skipped:
125 regex = list_regex('%s test%s skipped', skipped)
126 self.check_line(output, regex)
127
128 if failed:
129 regex = list_regex('%s test%s failed', failed)
130 self.check_line(output, regex)
131
132 if omitted:
133 regex = list_regex('%s test%s omitted', omitted)
134 self.check_line(output, regex)
135
136 good = ntest - nskipped - nfailed - nomitted
137 if good:
138 regex = r'%s test%s OK\.$' % (good, plural(good))
139 if not skipped and not failed and good > 1:
140 regex = 'All %s' % regex
141 self.check_line(output, regex)
142
143 if interrupted:
144 self.check_line(output, 'Test suite interrupted by signal SIGINT.')
145
Victor Stinner453a6852017-05-09 17:06:34 +0200146 if nfailed:
147 result = 'FAILURE'
148 elif interrupted:
149 result = 'INTERRUPTED'
150 else:
151 result = 'SUCCESS'
152 self.check_line(output, 'Tests result: %s' % result)
153
Victor Stinnerd2aff602017-05-09 13:57:20 +0200154 def parse_random_seed(self, output):
155 match = self.regex_search(r'Using random seed ([0-9]+)', output)
156 randseed = int(match.group(1))
157 self.assertTrue(0 <= randseed <= 10000000, randseed)
158 return randseed
159
160 def run_command(self, args, input=None, exitcode=0, **kw):
161 if not input:
162 input = ''
163 if 'stderr' not in kw:
164 kw['stderr'] = subprocess.PIPE
165 proc = subprocess.Popen(args,
166 universal_newlines=True,
167 stdout=subprocess.PIPE,
168 **kw)
169 stdout, stderr = proc.communicate(input=input)
170 if proc.returncode != exitcode:
171 msg = ("Command %s failed with exit code %s\n"
172 "\n"
173 "stdout:\n"
174 "---\n"
175 "%s\n"
176 "---\n"
177 % (str(args), proc.returncode, stdout))
178 if proc.stderr:
179 msg += ("\n"
180 "stderr:\n"
181 "---\n"
182 "%s"
183 "---\n"
184 % stderr)
185 self.fail(msg)
Victor Stinner453a6852017-05-09 17:06:34 +0200186 return SubprocessRun(proc.returncode, stdout, stderr)
Victor Stinnerd2aff602017-05-09 13:57:20 +0200187
188 def run_python(self, args, **kw):
189 args = [sys.executable] + list(args)
190 proc = self.run_command(args, **kw)
191 return proc.stdout
192
193
194class ProgramsTestCase(BaseTestCase):
195 """
196 Test various ways to run the Python test suite. Use options close
197 to options used on the buildbot.
198 """
199
200 NTEST = 4
201
202 def setUp(self):
203 super(ProgramsTestCase, self).setUp()
204
205 # Create NTEST tests doing nothing
206 self.tests = [self.create_test() for index in range(self.NTEST)]
207
Victor Stinner453a6852017-05-09 17:06:34 +0200208 self.python_args = ['-Wd', '-3', '-E', '-bb', '-tt']
Victor Stinnerd2aff602017-05-09 13:57:20 +0200209 self.regrtest_args = ['-uall', '-rwW',
210 '--testdir=%s' % self.tmptestdir]
211
212 def check_output(self, output):
213 self.parse_random_seed(output)
214 self.check_executed_tests(output, self.tests, randomize=True)
215
216 def run_tests(self, args):
217 output = self.run_python(args)
218 self.check_output(output)
219
220 def test_script_regrtest(self):
221 # Lib/test/regrtest.py
222 script = os.path.join(self.testdir, 'regrtest.py')
223
224 args = self.python_args + [script] + self.regrtest_args + self.tests
225 self.run_tests(args)
226
227 def test_module_test(self):
228 # -m test
229 args = self.python_args + ['-m', 'test'] + self.regrtest_args + self.tests
230 self.run_tests(args)
231
232 def test_module_regrtest(self):
233 # -m test.regrtest
234 args = self.python_args + ['-m', 'test.regrtest'] + self.regrtest_args + self.tests
235 self.run_tests(args)
236
237 def test_module_autotest(self):
238 # -m test.autotest
239 args = self.python_args + ['-m', 'test.autotest'] + self.regrtest_args + self.tests
240 self.run_tests(args)
241
242 def test_module_from_test_autotest(self):
243 # from test import autotest
244 code = 'from test import autotest'
245 args = self.python_args + ['-c', code] + self.regrtest_args + self.tests
246 self.run_tests(args)
247
248 def test_script_autotest(self):
249 # Lib/test/autotest.py
250 script = os.path.join(self.testdir, 'autotest.py')
251 args = self.python_args + [script] + self.regrtest_args + self.tests
252 self.run_tests(args)
253
254 def run_batch(self, *args):
255 proc = self.run_command(args)
256 self.check_output(proc.stdout)
257
258 @unittest.skipUnless(sysconfig.is_python_build(),
259 'test.bat script is not installed')
260 @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
261 def test_tools_buildbot_test(self):
262 # Tools\buildbot\test.bat
263 script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat')
264 test_args = ['--testdir=%s' % self.tmptestdir]
265 if platform.architecture()[0] == '64bit':
266 test_args.append('-x64') # 64-bit build
267 if not Py_DEBUG:
268 test_args.append('+d') # Release build, use python.exe
269
270 args = [script] + test_args + self.tests
271 self.run_batch(*args)
272
273 @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
274 def test_pcbuild_rt(self):
275 # PCbuild\rt.bat
276 script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat')
277 rt_args = ["-q"] # Quick, don't run tests twice
278 if platform.architecture()[0] == '64bit':
279 rt_args.append('-x64') # 64-bit build
280 if Py_DEBUG:
281 rt_args.append('-d') # Debug build, use python_d.exe
282 args = [script] + rt_args + self.regrtest_args + self.tests
283 self.run_batch(*args)
284
285
286class ArgsTestCase(BaseTestCase):
287 """
288 Test arguments of the Python test suite.
289 """
290
291 def run_tests(self, *testargs, **kw):
292 cmdargs = ('-m', 'test', '--testdir=%s' % self.tmptestdir) + testargs
293 return self.run_python(cmdargs, **kw)
294
295 def test_failing_test(self):
296 # test a failing test
297 code = textwrap.dedent("""
298 import unittest
299 from test import support
300
301 class FailingTest(unittest.TestCase):
302 def test_failing(self):
303 self.fail("bug")
304
305 def test_main():
306 support.run_unittest(FailingTest)
307 """)
308 test_ok = self.create_test('ok')
309 test_failing = self.create_test('failing', code=code)
310 tests = [test_ok, test_failing]
311
312 output = self.run_tests(*tests, exitcode=1)
313 self.check_executed_tests(output, tests, failed=test_failing)
314
315 def test_resources(self):
316 # test -u command line option
317 tests = {}
318 for resource in ('audio', 'network'):
319 code = 'from test import support\nsupport.requires(%r)' % resource
320 tests[resource] = self.create_test(resource, code)
321 test_names = sorted(tests.values())
322
323 # -u all: 2 resources enabled
324 output = self.run_tests('-u', 'all', *test_names)
325 self.check_executed_tests(output, test_names)
326
327 # -u audio: 1 resource enabled
328 output = self.run_tests('-uaudio', *test_names)
329 self.check_executed_tests(output, test_names,
330 skipped=tests['network'])
331
332 # no option: 0 resources enabled
333 output = self.run_tests(*test_names)
334 self.check_executed_tests(output, test_names,
335 skipped=test_names)
336
337 def test_random(self):
338 # test -r and --randseed command line option
339 code = textwrap.dedent("""
340 import random
341 print("TESTRANDOM: %s" % random.randint(1, 1000))
342 """)
343 test = self.create_test('random', code)
344
345 # first run to get the output with the random seed
346 output = self.run_tests('-r', '-v', test)
347 randseed = self.parse_random_seed(output)
348 match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
349 test_random = int(match.group(1))
350
351 # try to reproduce with the random seed
352 output = self.run_tests('-r', '-v', '--randseed=%s' % randseed, test)
353 randseed2 = self.parse_random_seed(output)
354 self.assertEqual(randseed2, randseed)
355
356 match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
357 test_random2 = int(match.group(1))
358 self.assertEqual(test_random2, test_random)
359
360 def test_fromfile(self):
361 # test --fromfile
362 tests = [self.create_test() for index in range(5)]
363
364 # Write the list of files using a format similar to regrtest output:
365 # [1/2] test_1
366 # [2/2] test_2
367 filename = support.TESTFN
368 self.addCleanup(support.unlink, filename)
369
370 # test format 'test_opcodes'
371 with open(filename, "w") as fp:
372 for name in tests:
373 print(name, file=fp)
374
375 output = self.run_tests('--fromfile', filename)
376 self.check_executed_tests(output, tests)
377
378 def test_interrupted(self):
379 code = TEST_INTERRUPTED
380 test = self.create_test('sigint', code=code)
381 output = self.run_tests(test, exitcode=1)
382 self.check_executed_tests(output, test, omitted=test,
383 interrupted=True)
384
Victor Stinner453a6852017-05-09 17:06:34 +0200385 def test_slowest(self):
Victor Stinnerd2aff602017-05-09 13:57:20 +0200386 # test --slow
387 tests = [self.create_test() for index in range(3)]
Victor Stinner453a6852017-05-09 17:06:34 +0200388 output = self.run_tests("--slowest", *tests)
Victor Stinnerd2aff602017-05-09 13:57:20 +0200389 self.check_executed_tests(output, tests)
390 regex = ('10 slowest tests:\n'
Victor Stinner453a6852017-05-09 17:06:34 +0200391 '(?:- %s: .*\n){%s}'
Victor Stinnerd2aff602017-05-09 13:57:20 +0200392 % (self.TESTNAME_REGEX, len(tests)))
393 self.check_line(output, regex)
394
395 def test_forever(self):
396 # test --forever
397 code = textwrap.dedent("""
398 import __builtin__
399 import unittest
400 from test import support
401
402 class ForeverTester(unittest.TestCase):
403 def test_run(self):
404 # Store the state in the __builtin__ module, because the test
405 # module is reload at each run
406 if 'RUN' in __builtin__.__dict__:
407 __builtin__.__dict__['RUN'] += 1
408 if __builtin__.__dict__['RUN'] >= 3:
409 self.fail("fail at the 3rd runs")
410 else:
411 __builtin__.__dict__['RUN'] = 1
412
413 def test_main():
414 support.run_unittest(ForeverTester)
415 """)
416 test = self.create_test('forever', code=code)
417 output = self.run_tests('--forever', test, exitcode=1)
418 self.check_executed_tests(output, [test]*3, failed=test)
419
Victor Stinner453a6852017-05-09 17:06:34 +0200420 def test_list_tests(self):
421 # test --list-tests
422 tests = [self.create_test() for i in range(5)]
423 output = self.run_tests('--list-tests', *tests)
424 self.assertEqual(output.rstrip().splitlines(),
425 tests)
426
Victor Stinnerd2aff602017-05-09 13:57:20 +0200427 def test_crashed(self):
428 # Any code which causes a crash
429 code = 'import ctypes; ctypes.string_at(0)'
430 crash_test = self.create_test(name="crash", code=code)
431 ok_test = self.create_test(name="ok")
432
433 tests = [crash_test, ok_test]
434 output = self.run_tests("-j2", *tests, exitcode=1)
435 self.check_executed_tests(output, tests, failed=crash_test,
436 randomize=True)
437
438
439def test_main():
440 support.run_unittest(ProgramsTestCase, ArgsTestCase)
441
442
443if __name__ == "__main__":
444 test_main()