Debian Codegraph @

cpython27/Lib/test/test_regrtest.py

raw symbols SCIP
1 """
2 Tests of regrtest.py.
3
4 Note: test_regrtest cannot be run twice in parallel.
5 """
6 from __future__ import print_function
7
8 import collections
9 import errno
10 import os.path
11 import platform
12 import re
13 import subprocess
14 import sys
15 import sysconfig
16 import tempfile
17 import textwrap
18 import unittest
19 from test import support
20 # Use utils alias to use the same code for TestUtils in master and 2.7 branches
21 import regrtest as utils
22
23
24 Py_DEBUG = hasattr(sys, 'getobjects')
25 ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..')
26 ROOT_DIR = os.path.abspath(os.path.normpath(ROOT_DIR))
27
28 TEST_INTERRUPTED = textwrap.dedent("""
29 from signal import SIGINT
30 try:
31 from _testcapi import raise_signal
32 raise_signal(SIGINT)
33 except ImportError:
34 import os
35 os.kill(os.getpid(), SIGINT)
36 """)
37
38
39 SubprocessRun = collections.namedtuple('SubprocessRun',
40 'returncode stdout stderr')
41
42
43 class BaseTestCase(unittest.TestCase):
44 TEST_UNIQUE_ID = 1
45 TESTNAME_PREFIX = 'test_regrtest_'
46 TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+'
47
48 def setUp(self):
49 self.testdir = os.path.realpath(os.path.dirname(__file__))
50
51 self.tmptestdir = tempfile.mkdtemp()
52 self.addCleanup(support.rmtree, self.tmptestdir)
53
54 def create_test(self, name=None, code=None):
55 if not name:
56 name = 'noop%s' % BaseTestCase.TEST_UNIQUE_ID
57 BaseTestCase.TEST_UNIQUE_ID += 1
58
59 if code is None:
60 code = textwrap.dedent("""
61 import unittest
62 from test import support
63
64 class Tests(unittest.TestCase):
65 def test_empty_test(self):
66 pass
67
68 def test_main():
69 support.run_unittest(Tests)
70 """)
71
72 # test_regrtest cannot be run twice in parallel because
73 # of setUp() and create_test()
74 name = self.TESTNAME_PREFIX + name
75 path = os.path.join(self.tmptestdir, name + '.py')
76
77 self.addCleanup(support.unlink, path)
78 # Use O_EXCL to ensure that we do not override existing tests
79 try:
80 fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
81 except OSError as exc:
82 if (exc.errno in (errno.EACCES, errno.EPERM)
83 and not sysconfig.is_python_build()):
84 self.skipTest("cannot write %s: %s" % (path, exc))
85 else:
86 raise
87 else:
88 with os.fdopen(fd, 'w') as fp:
89 fp.write(code)
90 return name
91
92 def regex_search(self, regex, output):
93 match = re.search(regex, output, re.MULTILINE)
94 if not match:
95 self.fail("%r not found in %r" % (regex, output))
96 return match
97
98 def check_line(self, output, regex):
99 regex = re.compile(r'^' + regex, re.MULTILINE)
100 self.assertRegexpMatches(output, regex)
101
102 def parse_executed_tests(self, output):
103 regex = (r'^[0-9]+:[0-9]+:[0-9]+ (?:load avg: [0-9]+\.[0-9]{2} )?\[ *[0-9]+(?:/ *[0-9]+)*\] (%s)'
104 % self.TESTNAME_REGEX)
105 parser = re.finditer(regex, output, re.MULTILINE)
106 return list(match.group(1) for match in parser)
107
108 def check_executed_tests(self, output, tests, skipped=(), failed=(),
109 env_changed=(), omitted=(),
110 rerun=(), no_test_ran=(),
111 randomize=False, interrupted=False,
112 fail_env_changed=False):
113 if isinstance(tests, str):
114 tests = [tests]
115 if isinstance(skipped, str):
116 skipped = [skipped]
117 if isinstance(failed, str):
118 failed = [failed]
119 if isinstance(env_changed, str):
120 env_changed = [env_changed]
121 if isinstance(omitted, str):
122 omitted = [omitted]
123 if isinstance(rerun, str):
124 rerun = [rerun]
125 if isinstance(no_test_ran, str):
126 no_test_ran = [no_test_ran]
127
128 executed = self.parse_executed_tests(output)
129 if randomize:
130 self.assertEqual(set(executed), set(tests), output)
131 else:
132 self.assertEqual(executed, tests, (executed, tests, output))
133
134 def plural(count):
135 return 's' if count != 1 else ''
136
137 def list_regex(line_format, tests):
138 count = len(tests)
139 names = ' '.join(sorted(tests))
140 regex = line_format % (count, plural(count))
141 regex = r'%s:\n %s$' % (regex, names)
142 return regex
143
144 if skipped:
145 regex = list_regex('%s test%s skipped', skipped)
146 self.check_line(output, regex)
147
148 if failed:
149 regex = list_regex('%s test%s failed', failed)
150 self.check_line(output, regex)
151
152 if env_changed:
153 regex = list_regex('%s test%s altered the execution environment',
154 env_changed)
155 self.check_line(output, regex)
156
157 if omitted:
158 regex = list_regex('%s test%s omitted', omitted)
159 self.check_line(output, regex)
160
161 if rerun:
162 regex = list_regex('%s re-run test%s', rerun)
163 self.check_line(output, regex)
164 self.check_line(output, "Re-running failed tests in verbose mode")
165 for name in rerun:
166 regex = "Re-running test %r in verbose mode" % name
167 self.check_line(output, regex)
168
169 good = (len(tests) - len(skipped) - len(failed)
170 - len(omitted) - len(env_changed) - len(no_test_ran))
171 if good:
172 regex = r'%s test%s OK\.$' % (good, plural(good))
173 if not skipped and not failed and good > 1:
174 regex = 'All %s' % regex
175 self.check_line(output, regex)
176
177 if interrupted:
178 self.check_line(output, 'Test suite interrupted by signal SIGINT.')
179
180 result = []
181 if failed:
182 result.append('FAILURE')
183 elif fail_env_changed and env_changed:
184 result.append('ENV CHANGED')
185 if interrupted:
186 result.append('INTERRUPTED')
187 if not any((good, result, failed, interrupted, skipped,
188 env_changed, fail_env_changed)):
189 result.append("NO TEST RUN")
190 elif not result:
191 result.append('SUCCESS')
192 result = ', '.join(result)
193 if rerun:
194 self.check_line(output, 'Tests result: %s' % result)
195 result = 'FAILURE then %s' % result
196
197 self.check_line(output, 'Tests result: %s' % result)
198
199 def parse_random_seed(self, output):
200 match = self.regex_search(r'Using random seed ([0-9]+)', output)
201 randseed = int(match.group(1))
202 self.assertTrue(0 <= randseed <= 10000000, randseed)
203 return randseed
204
205 def run_command(self, args, input=None, exitcode=0, **kw):
206 if not input:
207 input = ''
208 if 'stderr' not in kw:
209 kw['stderr'] = subprocess.PIPE
210 proc = subprocess.Popen(args,
211 universal_newlines=True,
212 stdout=subprocess.PIPE,
213 **kw)
214 stdout, stderr = proc.communicate(input=input)
215 if proc.returncode != exitcode:
216 msg = ("Command %s failed with exit code %s\n"
217 "\n"
218 "stdout:\n"
219 "---\n"
220 "%s\n"
221 "---\n"
222 % (str(args), proc.returncode, stdout))
223 if proc.stderr:
224 msg += ("\n"
225 "stderr:\n"
226 "---\n"
227 "%s"
228 "---\n"
229 % stderr)
230 self.fail(msg)
231 return SubprocessRun(proc.returncode, stdout, stderr)
232
233 def run_python(self, args, **kw):
234 args = [sys.executable] + list(args)
235 proc = self.run_command(args, **kw)
236 return proc.stdout
237
238
239 class ProgramsTestCase(BaseTestCase):
240 """
241 Test various ways to run the Python test suite. Use options close
242 to options used on the buildbot.
243 """
244
245 NTEST = 4
246
247 def setUp(self):
248 super(ProgramsTestCase, self).setUp()
249
250 # Create NTEST tests doing nothing
251 self.tests = [self.create_test() for index in range(self.NTEST)]
252
253 self.python_args = ['-Wd', '-3', '-E', '-bb', '-tt']
254 self.regrtest_args = ['-uall', '-rwW',
255 '--testdir=%s' % self.tmptestdir]
256
257 def check_output(self, output):
258 self.parse_random_seed(output)
259 self.check_executed_tests(output, self.tests, randomize=True)
260
261 def run_tests(self, args):
262 output = self.run_python(args)
263 self.check_output(output)
264
265 def test_script_regrtest(self):
266 # Lib/test/regrtest.py
267 script = os.path.join(self.testdir, 'regrtest.py')
268
269 args = self.python_args + [script] + self.regrtest_args + self.tests
270 self.run_tests(args)
271
272 def test_module_test(self):
273 # -m test
274 args = self.python_args + ['-m', 'test'] + self.regrtest_args + self.tests
275 self.run_tests(args)
276
277 def test_module_regrtest(self):
278 # -m test.regrtest
279 args = self.python_args + ['-m', 'test.regrtest'] + self.regrtest_args + self.tests
280 self.run_tests(args)
281
282 def test_module_autotest(self):
283 # -m test.autotest
284 args = self.python_args + ['-m', 'test.autotest'] + self.regrtest_args + self.tests
285 self.run_tests(args)
286
287 def test_module_from_test_autotest(self):
288 # from test import autotest
289 code = 'from test import autotest'
290 args = self.python_args + ['-c', code] + self.regrtest_args + self.tests
291 self.run_tests(args)
292
293 def test_script_autotest(self):
294 # Lib/test/autotest.py
295 script = os.path.join(self.testdir, 'autotest.py')
296 args = self.python_args + [script] + self.regrtest_args + self.tests
297 self.run_tests(args)
298
299 def run_batch(self, *args):
300 proc = self.run_command(args)
301 self.check_output(proc.stdout)
302
303 def need_pcbuild(self):
304 exe = os.path.normpath(os.path.abspath(sys.executable))
305 parts = exe.split(os.path.sep)
306 if len(parts) < 3:
307 # it's not a python build, python is likely to be installed
308 return
309
310 build_dir = parts[-3]
311 if build_dir.lower() != 'pcbuild':
312 self.skipTest("Tools/buildbot/test.bat requires PCbuild build, "
313 "found %s" % build_dir)
314
315 @unittest.skipUnless(sysconfig.is_python_build(),
316 'test.bat script is not installed')
317 @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
318 def test_tools_buildbot_test(self):
319 self.need_pcbuild()
320
321 # Tools\buildbot\test.bat
322 script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat')
323 test_args = ['--testdir=%s' % self.tmptestdir]
324 if platform.architecture()[0] == '64bit':
325 test_args.append('-x64') # 64-bit build
326 if not Py_DEBUG:
327 test_args.append('+d') # Release build, use python.exe
328
329 args = [script] + test_args + self.tests
330 self.run_batch(*args)
331
332 @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
333 def test_pcbuild_rt(self):
334 self.need_pcbuild()
335
336 # PCbuild\rt.bat
337 script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat')
338 rt_args = ["-q"] # Quick, don't run tests twice
339 if platform.architecture()[0] == '64bit':
340 rt_args.append('-x64') # 64-bit build
341 if Py_DEBUG:
342 rt_args.append('-d') # Debug build, use python_d.exe
343 args = [script] + rt_args + self.regrtest_args + self.tests
344 self.run_batch(*args)
345
346
347 class ArgsTestCase(BaseTestCase):
348 """
349 Test arguments of the Python test suite.
350 """
351
352 def run_tests(self, *testargs, **kw):
353 cmdargs = ('-m', 'test', '--testdir=%s' % self.tmptestdir) + testargs
354 return self.run_python(cmdargs, **kw)
355
356 def test_failing_test(self):
357 # test a failing test
358 code = textwrap.dedent("""
359 import unittest
360 from test import support
361
362 class FailingTest(unittest.TestCase):
363 def test_failing(self):
364 self.fail("bug")
365
366 def test_main():
367 support.run_unittest(FailingTest)
368 """)
369 test_ok = self.create_test('ok')
370 test_failing = self.create_test('failing', code=code)
371 tests = [test_ok, test_failing]
372
373 output = self.run_tests(*tests, exitcode=2)
374 self.check_executed_tests(output, tests, failed=test_failing)
375
376 def test_resources(self):
377 # test -u command line option
378 tests = {}
379 for resource in ('audio', 'network'):
380 code = textwrap.dedent("""
381 from test import support; support.requires(%r)
382 import unittest
383 class PassingTest(unittest.TestCase):
384 def test_pass(self):
385 pass
386
387 def test_main():
388 support.run_unittest(PassingTest)
389 """ % resource)
390
391 tests[resource] = self.create_test(resource, code)
392 test_names = sorted(tests.values())
393
394 # -u all: 2 resources enabled
395 output = self.run_tests('-u', 'all', *test_names)
396 self.check_executed_tests(output, test_names)
397
398 # -u audio: 1 resource enabled
399 output = self.run_tests('-uaudio', *test_names)
400 self.check_executed_tests(output, test_names,
401 skipped=tests['network'])
402
403 # no option: 0 resources enabled
404 output = self.run_tests(*test_names)
405 self.check_executed_tests(output, test_names,
406 skipped=test_names)
407
408 def test_random(self):
409 # test -r and --randseed command line option
410 code = textwrap.dedent("""
411 import random
412 print("TESTRANDOM: %s" % random.randint(1, 1000))
413 """)
414 test = self.create_test('random', code)
415
416 # first run to get the output with the random seed
417 output = self.run_tests('-r', '-v', test)
418 randseed = self.parse_random_seed(output)
419 match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
420 test_random = int(match.group(1))
421
422 # try to reproduce with the random seed
423 output = self.run_tests('-r', '-v', '--randseed=%s' % randseed, test)
424 randseed2 = self.parse_random_seed(output)
425 self.assertEqual(randseed2, randseed)
426
427 match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
428 test_random2 = int(match.group(1))
429 self.assertEqual(test_random2, test_random)
430
431 def test_fromfile(self):
432 # test --fromfile
433 tests = [self.create_test() for index in range(5)]
434
435 # Write the list of files using a format similar to regrtest output:
436 # [1/2] test_1
437 # [2/2] test_2
438 filename = support.TESTFN
439 self.addCleanup(support.unlink, filename)
440
441 # test format 'test_opcodes'
442 with open(filename, "w") as fp:
443 for name in tests:
444 print(name, file=fp)
445
446 output = self.run_tests('--fromfile', filename)
447 self.check_executed_tests(output, tests)
448
449 def test_interrupted(self):
450 code = TEST_INTERRUPTED
451 test = self.create_test('sigint', code=code)
452 output = self.run_tests(test, exitcode=130)
453 self.check_executed_tests(output, test, omitted=test,
454 interrupted=True)
455
456 def test_slowest(self):
457 # test --slow
458 tests = [self.create_test() for index in range(3)]
459 output = self.run_tests("--slowest", *tests)
460 self.check_executed_tests(output, tests)
461 regex = ('10 slowest tests:\n'
462 '(?:- %s: .*\n){%s}'
463 % (self.TESTNAME_REGEX, len(tests)))
464 self.check_line(output, regex)
465
466 def test_slow_interrupted(self):
467 # Issue #25373: test --slowest with an interrupted test
468 code = TEST_INTERRUPTED
469 test = self.create_test("sigint", code=code)
470
471 try:
472 import threading
473 tests = (False, True)
474 except ImportError:
475 tests = (False,)
476 for multiprocessing in tests:
477 if multiprocessing:
478 args = ("--slowest", "-j2", test)
479 else:
480 args = ("--slowest", test)
481 output = self.run_tests(*args, exitcode=130)
482 self.check_executed_tests(output, test,
483 omitted=test, interrupted=True)
484
485 regex = ('10 slowest tests:\n')
486 self.check_line(output, regex)
487
488 def test_coverage(self):
489 # test --coverage
490 test = self.create_test('coverage')
491 output = self.run_tests("--coverage", test)
492 self.check_executed_tests(output, [test])
493 regex = (r'lines +cov% +module +\(path\)\n'
494 r'(?: *[0-9]+ *[0-9]{1,2}% *[^ ]+ +\([^)]+\)+)+')
495 self.check_line(output, regex)
496
497 def test_forever(self):
498 # test --forever
499 code = textwrap.dedent("""
500 import __builtin__
501 import unittest
502 from test import support
503
504 class ForeverTester(unittest.TestCase):
505 def test_run(self):
506 # Store the state in the __builtin__ module, because the test
507 # module is reload at each run
508 if 'RUN' in __builtin__.__dict__:
509 __builtin__.__dict__['RUN'] += 1
510 if __builtin__.__dict__['RUN'] >= 3:
511 self.fail("fail at the 3rd runs")
512 else:
513 __builtin__.__dict__['RUN'] = 1
514
515 def test_main():
516 support.run_unittest(ForeverTester)
517 """)
518 test = self.create_test('forever', code=code)
519 output = self.run_tests('--forever', test, exitcode=2)
520 self.check_executed_tests(output, [test]*3, failed=test)
521
522 def check_leak(self, code, what):
523 test = self.create_test('huntrleaks', code=code)
524
525 filename = 'reflog.txt'
526 self.addCleanup(support.unlink, filename)
527 output = self.run_tests('--huntrleaks', '3:3:', test,
528 exitcode=2,
529 stderr=subprocess.STDOUT)
530 self.check_executed_tests(output, [test], failed=test)
531
532 line = 'beginning 6 repetitions\n123456\n......\n'
533 self.check_line(output, re.escape(line))
534
535 line2 = '%s leaked [1, 1, 1] %s, sum=3\n' % (test, what)
536 self.assertIn(line2, output)
537
538 with open(filename) as fp:
539 reflog = fp.read()
540 self.assertIn(line2, reflog)
541
542 @unittest.skipUnless(Py_DEBUG, 'need a debug build')
543 @support.requires_type_collecting
544 def test_huntrleaks(self):
545 # test --huntrleaks
546 code = textwrap.dedent("""
547 import unittest
548 from test import support
549
550 GLOBAL_LIST = []
551
552 class RefLeakTest(unittest.TestCase):
553 def test_leak(self):
554 GLOBAL_LIST.append(object())
555
556 def test_main():
557 support.run_unittest(RefLeakTest)
558 """)
559 self.check_leak(code, 'references')
560
561 @unittest.skipUnless(Py_DEBUG, 'need a debug build')
562 def test_huntrleaks_fd_leak(self):
563 # test --huntrleaks for file descriptor leak
564 code = textwrap.dedent("""
565 import os
566 import unittest
567 from test import support
568
569 class FDLeakTest(unittest.TestCase):
570 def test_leak(self):
571 fd = os.open(__file__, os.O_RDONLY)
572 # bug: never close the file descriptor
573
574 def test_main():
575 support.run_unittest(FDLeakTest)
576 """)
577 self.check_leak(code, 'file descriptors')
578
579 def test_list_tests(self):
580 # test --list-tests
581 tests = [self.create_test() for i in range(5)]
582 output = self.run_tests('--list-tests', *tests)
583 self.assertEqual(output.rstrip().splitlines(),
584 tests)
585
586 def test_list_cases(self):
587 # test --list-cases
588 code = textwrap.dedent("""
589 import unittest
590
591 class Tests(unittest.TestCase):
592 def test_method1(self):
593 pass
594 def test_method2(self):
595 pass
596 """)
597 testname = self.create_test(code=code)
598
599 # Test --list-cases
600 all_methods = ['%s.Tests.test_method1' % testname,
601 '%s.Tests.test_method2' % testname]
602 output = self.run_tests('--list-cases', testname)
603 self.assertEqual(output.splitlines(), all_methods)
604
605 # Test --list-cases with --match
606 all_methods = ['%s.Tests.test_method1' % testname]
607 output = self.run_tests('--list-cases',
608 '-m', 'test_method1',
609 testname)
610 self.assertEqual(output.splitlines(), all_methods)
611
612 @unittest.skipIf(sys.platform.startswith('aix'),
613 "support._crash_python() doesn't work on AIX")
614 def test_crashed(self):
615 # Any code which causes a crash
616 code = 'import test.support; test.support._crash_python()'
617 crash_test = self.create_test(name="crash", code=code)
618 ok_test = self.create_test(name="ok")
619
620 tests = [crash_test, ok_test]
621 output = self.run_tests("-j2", *tests, exitcode=2)
622 self.check_executed_tests(output, tests, failed=crash_test,
623 randomize=True)
624
625 def parse_methods(self, output):
626 regex = re.compile("^(test[^ ]+).*ok$", flags=re.MULTILINE)
627 return [match.group(1) for match in regex.finditer(output)]
628
629 def test_matchfile(self):
630 # Any code which causes a crash
631 code = textwrap.dedent("""
632 import unittest
633 from test import support
634
635 class Tests(unittest.TestCase):
636 def test_method1(self):
637 pass
638 def test_method2(self):
639 pass
640 def test_method3(self):
641 pass
642 def test_method4(self):
643 pass
644
645 def test_main():
646 support.run_unittest(Tests)
647 """)
648 all_methods = ['test_method1', 'test_method2',
649 'test_method3', 'test_method4']
650 testname = self.create_test(code=code)
651
652 # by default, all methods should be run
653 output = self.run_tests("-v", testname)
654 methods = self.parse_methods(output)
655 self.assertEqual(methods, all_methods)
656
657 # only run a subset
658 filename = support.TESTFN
659 self.addCleanup(support.unlink, filename)
660
661 subset = [
662 # only match the method name
663 'test_method1',
664 # match the full identifier
665 '%s.Tests.test_method3' % testname]
666 with open(filename, "w") as fp:
667 for name in subset:
668 print(name, file=fp)
669
670 output = self.run_tests("-v", "--matchfile", filename, testname)
671 methods = self.parse_methods(output)
672 subset = ['test_method1', 'test_method3']
673 self.assertEqual(methods, subset)
674
675 # bpo-34021: The test fails randomly for an unknown reason
676 # on "x86 Windows XP VS9.0 2.7" buildbot worker.
677 @unittest.skipIf(sys.platform == "win32", "test fails randomly on Windows")
678 def test_env_changed(self):
679 code = textwrap.dedent("""
680 import unittest
681 from test import support
682
683 class Tests(unittest.TestCase):
684 def test_env_changed(self):
685 open("env_changed", "w").close()
686
687 def test_main():
688 support.run_unittest(Tests)
689 """)
690 testname = self.create_test(code=code)
691
692 # don't fail by default
693 output = self.run_tests(testname)
694 self.check_executed_tests(output, [testname], env_changed=testname)
695
696 # fail with --fail-env-changed
697 output = self.run_tests("--fail-env-changed", testname, exitcode=3)
698 self.check_executed_tests(output, [testname], env_changed=testname,
699 fail_env_changed=True)
700
701 def test_rerun_fail(self):
702 code = textwrap.dedent("""
703 import unittest
704 from test import support
705
706 class Tests(unittest.TestCase):
707 def test_bug(self):
708 # test always fail
709 self.fail("bug")
710
711 def test_main():
712 support.run_unittest(Tests)
713 """)
714 testname = self.create_test(code=code)
715
716 output = self.run_tests("-w", testname, exitcode=2)
717 self.check_executed_tests(output, [testname],
718 failed=testname, rerun=testname)
719
720 def test_no_tests_ran(self):
721 code = textwrap.dedent("""
722 import unittest
723 from test import support
724
725 class Tests(unittest.TestCase):
726 def test_bug(self):
727 pass
728
729 def test_main():
730 support.run_unittest(Tests)
731 """)
732 testname = self.create_test(code=code)
733
734 output = self.run_tests("-m", "nosuchtest", testname, exitcode=0)
735 self.check_executed_tests(output, [testname], no_test_ran=testname)
736
737 def test_no_tests_ran_skip(self):
738 code = textwrap.dedent("""
739 import unittest
740
741 class Tests(unittest.TestCase):
742 def test_skipped(self):
743 self.skipTest("because")
744 """)
745 testname = self.create_test(code=code)
746
747 output = self.run_tests(testname, exitcode=0)
748 self.check_executed_tests(output, [testname])
749
750 def test_no_tests_ran_multiple_tests_nonexistent(self):
751 code = textwrap.dedent("""
752 import unittest
753 from test import support
754
755 class Tests(unittest.TestCase):
756 def test_bug(self):
757 pass
758
759 def test_main():
760 support.run_unittest(Tests)
761 """)
762 testname = self.create_test(code=code)
763 testname2 = self.create_test(code=code)
764
765 output = self.run_tests("-m", "nosuchtest",
766 testname, testname2,
767 exitcode=0)
768 self.check_executed_tests(output, [testname, testname2],
769 no_test_ran=[testname, testname2])
770
771 def test_no_test_ran_some_test_exist_some_not(self):
772 code = textwrap.dedent("""
773 import unittest
774 from test import support
775
776 class Tests(unittest.TestCase):
777 def test_bug(self):
778 pass
779
780 def test_main():
781 support.run_unittest(Tests)
782 """)
783 testname = self.create_test(code=code)
784 other_code = textwrap.dedent("""
785 import unittest
786 from test import support
787
788 class Tests(unittest.TestCase):
789 def test_other_bug(self):
790 pass
791
792 def test_main():
793 support.run_unittest(Tests)
794 """)
795 testname2 = self.create_test(code=other_code)
796
797 output = self.run_tests("-m", "nosuchtest", "-m", "test_other_bug",
798 testname, testname2,
799 exitcode=0)
800 self.check_executed_tests(output, [testname, testname2],
801 no_test_ran=[testname])
802
803
804 class TestUtils(unittest.TestCase):
805 def test_format_duration(self):
806 self.assertEqual(utils.format_duration(0),
807 '0 ms')
808 self.assertEqual(utils.format_duration(1e-9),
809 '1 ms')
810 self.assertEqual(utils.format_duration(10e-3),
811 '10 ms')
812 self.assertEqual(utils.format_duration(1.5),
813 '1 sec 500 ms')
814 self.assertEqual(utils.format_duration(1),
815 '1 sec')
816 self.assertEqual(utils.format_duration(2 * 60),
817 '2 min')
818 self.assertEqual(utils.format_duration(2 * 60 + 1),
819 '2 min 1 sec')
820 self.assertEqual(utils.format_duration(3 * 3600),
821 '3 hour')
822 self.assertEqual(utils.format_duration(3 * 3600 + 2 * 60 + 1),
823 '3 hour 2 min')
824 self.assertEqual(utils.format_duration(3 * 3600 + 1),
825 '3 hour 1 sec')
826
827
828 def test_main():
829 support.run_unittest(ProgramsTestCase, ArgsTestCase, TestUtils)
830
831
832 if __name__ == "__main__":
833 test_main()