]> granicus.if.org Git - python/commitdiff
Issue #19527: Fixed tests with defined COUNT_ALLOCS.
authorSerhiy Storchaka <storchaka@gmail.com>
Sun, 3 Jul 2016 19:30:49 +0000 (22:30 +0300)
committerSerhiy Storchaka <storchaka@gmail.com>
Sun, 3 Jul 2016 19:30:49 +0000 (22:30 +0300)
1  2 
Lib/test/support/__init__.py
Lib/test/test_gc.py
Lib/test/test_io.py
Lib/test/test_logging.py
Lib/test/test_regrtest.py
Lib/test/test_threading.py
Lib/test/test_traceback.py
Lib/test/test_warnings/__init__.py

Simple merge
Simple merge
Simple merge
Simple merge
index c11408df7feacf6767e919a8bc20fcd1a6b1746c,a398a4f836eeadccdd0db07dd7a44024f8a3158f..32edff856f67fdea348d0732fefcb87ede9044ea
@@@ -300,478 -271,5 +300,481 @@@ class ParseArgsTestCase(unittest.TestCa
          self.assertEqual(ns.args, ['foo'])
  
  
 +class BaseTestCase(unittest.TestCase):
 +    TEST_UNIQUE_ID = 1
 +    TESTNAME_PREFIX = 'test_regrtest_'
 +    TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+'
 +
 +    def setUp(self):
 +        self.testdir = os.path.realpath(os.path.dirname(__file__))
 +
 +        self.tmptestdir = tempfile.mkdtemp()
 +        self.addCleanup(support.rmtree, self.tmptestdir)
 +
 +    def create_test(self, name=None, code=''):
 +        if not name:
 +            name = 'noop%s' % BaseTestCase.TEST_UNIQUE_ID
 +            BaseTestCase.TEST_UNIQUE_ID += 1
 +
 +        # test_regrtest cannot be run twice in parallel because
 +        # of setUp() and create_test()
 +        name = self.TESTNAME_PREFIX + name
 +        path = os.path.join(self.tmptestdir, name + '.py')
 +
 +        self.addCleanup(support.unlink, path)
 +        # Use 'x' mode to ensure that we do not override existing tests
 +        try:
 +            with open(path, 'x', encoding='utf-8') as fp:
 +                fp.write(code)
 +        except PermissionError as exc:
 +            if not sysconfig.is_python_build():
 +                self.skipTest("cannot write %s: %s" % (path, exc))
 +            raise
 +        return name
 +
 +    def regex_search(self, regex, output):
 +        match = re.search(regex, output, re.MULTILINE)
 +        if not match:
 +            self.fail("%r not found in %r" % (regex, output))
 +        return match
 +
 +    def check_line(self, output, regex):
 +        regex = re.compile(r'^' + regex, re.MULTILINE)
 +        self.assertRegex(output, regex)
 +
 +    def parse_executed_tests(self, output):
 +        regex = (r'^[0-9]+:[0-9]+:[0-9]+ \[ *[0-9]+(?:/ *[0-9]+)?\] (%s)'
 +                 % self.TESTNAME_REGEX)
 +        parser = re.finditer(regex, output, re.MULTILINE)
 +        return list(match.group(1) for match in parser)
 +
 +    def check_executed_tests(self, output, tests, skipped=(), failed=(),
 +                             omitted=(), randomize=False):
 +        if isinstance(tests, str):
 +            tests = [tests]
 +        if isinstance(skipped, str):
 +            skipped = [skipped]
 +        if isinstance(failed, str):
 +            failed = [failed]
 +        if isinstance(omitted, str):
 +            omitted = [omitted]
 +        ntest = len(tests)
 +        nskipped = len(skipped)
 +        nfailed = len(failed)
 +        nomitted = len(omitted)
 +
 +        executed = self.parse_executed_tests(output)
 +        if randomize:
 +            self.assertEqual(set(executed), set(tests), output)
 +        else:
 +            self.assertEqual(executed, tests, output)
 +
 +        def plural(count):
 +            return 's' if count != 1 else ''
 +
 +        def list_regex(line_format, tests):
 +            count = len(tests)
 +            names = ' '.join(sorted(tests))
 +            regex = line_format % (count, plural(count))
 +            regex = r'%s:\n    %s$' % (regex, names)
 +            return regex
 +
 +        if skipped:
 +            regex = list_regex('%s test%s skipped', skipped)
 +            self.check_line(output, regex)
 +
 +        if failed:
 +            regex = list_regex('%s test%s failed', failed)
 +            self.check_line(output, regex)
 +
 +        if omitted:
 +            regex = list_regex('%s test%s omitted', omitted)
 +            self.check_line(output, regex)
 +
 +        good = ntest - nskipped - nfailed - nomitted
 +        if good:
 +            regex = r'%s test%s OK\.$' % (good, plural(good))
 +            if not skipped and not failed and good > 1:
 +                regex = 'All %s' % regex
 +            self.check_line(output, regex)
 +
 +    def parse_random_seed(self, output):
 +        match = self.regex_search(r'Using random seed ([0-9]+)', output)
 +        randseed = int(match.group(1))
 +        self.assertTrue(0 <= randseed <= 10000000, randseed)
 +        return randseed
 +
 +    def run_command(self, args, input=None, exitcode=0, **kw):
 +        if not input:
 +            input = ''
 +        if 'stderr' not in kw:
 +            kw['stderr'] = subprocess.PIPE
 +        proc = subprocess.run(args,
 +                              universal_newlines=True,
 +                              input=input,
 +                              stdout=subprocess.PIPE,
 +                              **kw)
 +        if proc.returncode != exitcode:
 +            msg = ("Command %s failed with exit code %s\n"
 +                   "\n"
 +                   "stdout:\n"
 +                   "---\n"
 +                   "%s\n"
 +                   "---\n"
 +                   % (str(args), proc.returncode, proc.stdout))
 +            if proc.stderr:
 +                msg += ("\n"
 +                        "stderr:\n"
 +                        "---\n"
 +                        "%s"
 +                        "---\n"
 +                        % proc.stderr)
 +            self.fail(msg)
 +        return proc
 +
 +
 +    def run_python(self, args, **kw):
 +        args = [sys.executable, '-X', 'faulthandler', '-I', *args]
 +        proc = self.run_command(args, **kw)
 +        return proc.stdout
 +
 +
 +class ProgramsTestCase(BaseTestCase):
 +    """
 +    Test various ways to run the Python test suite. Use options close
 +    to options used on the buildbot.
 +    """
 +
 +    NTEST = 4
 +
 +    def setUp(self):
 +        super().setUp()
 +
 +        # Create NTEST tests doing nothing
 +        self.tests = [self.create_test() for index in range(self.NTEST)]
 +
 +        self.python_args = ['-Wd', '-E', '-bb']
 +        self.regrtest_args = ['-uall', '-rwW',
 +                              '--testdir=%s' % self.tmptestdir]
 +        if hasattr(faulthandler, 'dump_traceback_later'):
 +            self.regrtest_args.extend(('--timeout', '3600', '-j4'))
 +        if sys.platform == 'win32':
 +            self.regrtest_args.append('-n')
 +
 +    def check_output(self, output):
 +        self.parse_random_seed(output)
 +        self.check_executed_tests(output, self.tests, randomize=True)
 +
 +    def run_tests(self, args):
 +        output = self.run_python(args)
 +        self.check_output(output)
 +
 +    def test_script_regrtest(self):
 +        # Lib/test/regrtest.py
 +        script = os.path.join(self.testdir, 'regrtest.py')
 +
 +        args = [*self.python_args, script, *self.regrtest_args, *self.tests]
 +        self.run_tests(args)
 +
 +    def test_module_test(self):
 +        # -m test
 +        args = [*self.python_args, '-m', 'test',
 +                *self.regrtest_args, *self.tests]
 +        self.run_tests(args)
 +
 +    def test_module_regrtest(self):
 +        # -m test.regrtest
 +        args = [*self.python_args, '-m', 'test.regrtest',
 +                *self.regrtest_args, *self.tests]
 +        self.run_tests(args)
 +
 +    def test_module_autotest(self):
 +        # -m test.autotest
 +        args = [*self.python_args, '-m', 'test.autotest',
 +                *self.regrtest_args, *self.tests]
 +        self.run_tests(args)
 +
 +    def test_module_from_test_autotest(self):
 +        # from test import autotest
 +        code = 'from test import autotest'
 +        args = [*self.python_args, '-c', code,
 +                *self.regrtest_args, *self.tests]
 +        self.run_tests(args)
 +
 +    def test_script_autotest(self):
 +        # Lib/test/autotest.py
 +        script = os.path.join(self.testdir, 'autotest.py')
 +        args = [*self.python_args, script, *self.regrtest_args, *self.tests]
 +        self.run_tests(args)
 +
 +    @unittest.skipUnless(sysconfig.is_python_build(),
 +                         'run_tests.py script is not installed')
 +    def test_tools_script_run_tests(self):
 +        # Tools/scripts/run_tests.py
 +        script = os.path.join(ROOT_DIR, 'Tools', 'scripts', 'run_tests.py')
 +        args = [script, *self.regrtest_args, *self.tests]
 +        self.run_tests(args)
 +
 +    def run_batch(self, *args):
 +        proc = self.run_command(args)
 +        self.check_output(proc.stdout)
 +
 +    @unittest.skipUnless(sysconfig.is_python_build(),
 +                         'test.bat script is not installed')
 +    @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
 +    def test_tools_buildbot_test(self):
 +        # Tools\buildbot\test.bat
 +        script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat')
 +        test_args = ['--testdir=%s' % self.tmptestdir]
 +        if platform.architecture()[0] == '64bit':
 +            test_args.append('-x64')   # 64-bit build
 +        if not Py_DEBUG:
 +            test_args.append('+d')     # Release build, use python.exe
 +        self.run_batch(script, *test_args, *self.tests)
 +
 +    @unittest.skipUnless(sys.platform == 'win32', 'Windows only')
 +    def test_pcbuild_rt(self):
 +        # PCbuild\rt.bat
 +        script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat')
 +        rt_args = ["-q"]             # Quick, don't run tests twice
 +        if platform.architecture()[0] == '64bit':
 +            rt_args.append('-x64')   # 64-bit build
 +        if Py_DEBUG:
 +            rt_args.append('-d')     # Debug build, use python_d.exe
 +        self.run_batch(script, *rt_args, *self.regrtest_args, *self.tests)
 +
 +
 +class ArgsTestCase(BaseTestCase):
 +    """
 +    Test arguments of the Python test suite.
 +    """
 +
 +    def run_tests(self, *testargs, **kw):
 +        cmdargs = ['-m', 'test', '--testdir=%s' % self.tmptestdir, *testargs]
 +        return self.run_python(cmdargs, **kw)
 +
 +    def test_failing_test(self):
 +        # test a failing test
 +        code = textwrap.dedent("""
 +            import unittest
 +
 +            class FailingTest(unittest.TestCase):
 +                def test_failing(self):
 +                    self.fail("bug")
 +        """)
 +        test_ok = self.create_test('ok')
 +        test_failing = self.create_test('failing', code=code)
 +        tests = [test_ok, test_failing]
 +
 +        output = self.run_tests(*tests, exitcode=1)
 +        self.check_executed_tests(output, tests, failed=test_failing)
 +
 +    def test_resources(self):
 +        # test -u command line option
 +        tests = {}
 +        for resource in ('audio', 'network'):
 +            code = 'from test import support\nsupport.requires(%r)' % resource
 +            tests[resource] = self.create_test(resource, code)
 +        test_names = sorted(tests.values())
 +
 +        # -u all: 2 resources enabled
 +        output = self.run_tests('-u', 'all', *test_names)
 +        self.check_executed_tests(output, test_names)
 +
 +        # -u audio: 1 resource enabled
 +        output = self.run_tests('-uaudio', *test_names)
 +        self.check_executed_tests(output, test_names,
 +                                  skipped=tests['network'])
 +
 +        # no option: 0 resources enabled
 +        output = self.run_tests(*test_names)
 +        self.check_executed_tests(output, test_names,
 +                                  skipped=test_names)
 +
 +    def test_random(self):
 +        # test -r and --randseed command line option
 +        code = textwrap.dedent("""
 +            import random
 +            print("TESTRANDOM: %s" % random.randint(1, 1000))
 +        """)
 +        test = self.create_test('random', code)
 +
 +        # first run to get the output with the random seed
 +        output = self.run_tests('-r', test)
 +        randseed = self.parse_random_seed(output)
 +        match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
 +        test_random = int(match.group(1))
 +
 +        # try to reproduce with the random seed
 +        output = self.run_tests('-r', '--randseed=%s' % randseed, test)
 +        randseed2 = self.parse_random_seed(output)
 +        self.assertEqual(randseed2, randseed)
 +
 +        match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output)
 +        test_random2 = int(match.group(1))
 +        self.assertEqual(test_random2, test_random)
 +
 +    def test_fromfile(self):
 +        # test --fromfile
 +        tests = [self.create_test() for index in range(5)]
 +
 +        # Write the list of files using a format similar to regrtest output:
 +        # [1/2] test_1
 +        # [2/2] test_2
 +        filename = support.TESTFN
 +        self.addCleanup(support.unlink, filename)
 +
 +        # test format '0:00:00 [2/7] test_opcodes -- test_grammar took 0 sec'
 +        with open(filename, "w") as fp:
 +            previous = None
 +            for index, name in enumerate(tests, 1):
 +                line = ("00:00:%02i [%s/%s] %s"
 +                        % (index, index, len(tests), name))
 +                if previous:
 +                    line += " -- %s took 0 sec" % previous
 +                print(line, file=fp)
 +                previous = name
 +
 +        output = self.run_tests('--fromfile', filename)
 +        self.check_executed_tests(output, tests)
 +
 +        # test format '[2/7] test_opcodes'
 +        with open(filename, "w") as fp:
 +            for index, name in enumerate(tests, 1):
 +                print("[%s/%s] %s" % (index, len(tests), name), file=fp)
 +
 +        output = self.run_tests('--fromfile', filename)
 +        self.check_executed_tests(output, tests)
 +
 +        # test format 'test_opcodes'
 +        with open(filename, "w") as fp:
 +            for name in tests:
 +                print(name, file=fp)
 +
 +        output = self.run_tests('--fromfile', filename)
 +        self.check_executed_tests(output, tests)
 +
 +    def test_interrupted(self):
 +        code = TEST_INTERRUPTED
 +        test = self.create_test('sigint', code=code)
 +        output = self.run_tests(test, exitcode=1)
 +        self.check_executed_tests(output, test, omitted=test)
 +
 +    def test_slow(self):
 +        # test --slow
 +        tests = [self.create_test() for index in range(3)]
 +        output = self.run_tests("--slow", *tests)
 +        self.check_executed_tests(output, tests)
 +        regex = ('10 slowest tests:\n'
 +                 '(?:%s: [0-9]+\.[0-9]+s\n){%s}'
 +                 % (self.TESTNAME_REGEX, len(tests)))
 +        self.check_line(output, regex)
 +
 +    def test_slow_interrupted(self):
 +        # Issue #25373: test --slow with an interrupted test
 +        code = TEST_INTERRUPTED
 +        test = self.create_test("sigint", code=code)
 +
 +        for multiprocessing in (False, True):
 +            if multiprocessing:
 +                args = ("--slow", "-j2", test)
 +            else:
 +                args = ("--slow", test)
 +            output = self.run_tests(*args, exitcode=1)
 +            self.check_executed_tests(output, test, omitted=test)
 +            regex = ('10 slowest tests:\n')
 +            self.check_line(output, regex)
 +            self.check_line(output, 'Test suite interrupted by signal SIGINT.')
 +
 +    def test_coverage(self):
 +        # test --coverage
 +        test = self.create_test('coverage')
 +        output = self.run_tests("--coverage", test)
 +        self.check_executed_tests(output, [test])
 +        regex = ('lines +cov% +module +\(path\)\n'
 +                 '(?: *[0-9]+ *[0-9]{1,2}% *[^ ]+ +\([^)]+\)+)+')
 +        self.check_line(output, regex)
 +
 +    def test_wait(self):
 +        # test --wait
 +        test = self.create_test('wait')
 +        output = self.run_tests("--wait", test, input='key')
 +        self.check_line(output, 'Press any key to continue')
 +
 +    def test_forever(self):
 +        # test --forever
 +        code = textwrap.dedent("""
 +            import builtins
 +            import unittest
 +
 +            class ForeverTester(unittest.TestCase):
 +                def test_run(self):
 +                    # Store the state in the builtins module, because the test
 +                    # module is reload at each run
 +                    if 'RUN' in builtins.__dict__:
 +                        builtins.__dict__['RUN'] += 1
 +                        if builtins.__dict__['RUN'] >= 3:
 +                            self.fail("fail at the 3rd runs")
 +                    else:
 +                        builtins.__dict__['RUN'] = 1
 +        """)
 +        test = self.create_test('forever', code=code)
 +        output = self.run_tests('--forever', test, exitcode=1)
 +        self.check_executed_tests(output, [test]*3, failed=test)
 +
 +    @unittest.skipUnless(Py_DEBUG, 'need a debug build')
 +    def test_huntrleaks_fd_leak(self):
 +        # test --huntrleaks for file descriptor leak
 +        code = textwrap.dedent("""
 +            import os
 +            import unittest
 +
 +            # Issue #25306: Disable popups and logs to stderr on assertion
 +            # failures in MSCRT
 +            try:
 +                import msvcrt
 +                msvcrt.CrtSetReportMode
 +            except (ImportError, AttributeError):
 +                # no Windows, o release build
 +                pass
 +            else:
 +                for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
 +                    msvcrt.CrtSetReportMode(m, 0)
 +
 +            class FDLeakTest(unittest.TestCase):
 +                def test_leak(self):
 +                    fd = os.open(__file__, os.O_RDONLY)
 +                    # bug: never cloes the file descriptor
 +        """)
 +        test = self.create_test('huntrleaks', code=code)
 +
 +        filename = 'reflog.txt'
 +        self.addCleanup(support.unlink, filename)
 +        output = self.run_tests('--huntrleaks', '3:3:', test,
 +                                exitcode=1,
 +                                stderr=subprocess.STDOUT)
 +        self.check_executed_tests(output, [test], failed=test)
 +
 +        line = 'beginning 6 repetitions\n123456\n......\n'
 +        self.check_line(output, re.escape(line))
 +
 +        line2 = '%s leaked [1, 1, 1] file descriptors, sum=3\n' % test
 +        self.check_line(output, re.escape(line2))
 +
 +        with open(filename) as fp:
 +            reflog = fp.read()
++            if hasattr(sys, 'getcounts'):
++                # Types are immportal if COUNT_ALLOCS is defined
++                reflog = reflog.splitlines(True)[-1]
 +            self.assertEqual(reflog, line2)
 +
 +    def test_list_tests(self):
 +        # test --list-tests
 +        tests = [self.create_test() for i in range(5)]
 +        output = self.run_tests('--list-tests', *tests)
 +        self.assertEqual(output.rstrip().splitlines(),
 +                         tests)
 +
 +
  if __name__ == '__main__':
      unittest.main()
Simple merge
index 5e4b6a27e5f72afb550fbd4f456425a23d4f20b6,549d8d1e9701837d8d0b66505ba503ec284940d8..787409c5feb40afaa07641fc9e59229064dc3c42
@@@ -175,9 -175,10 +175,10 @@@ class SyntaxTracebackCases(unittest.Tes
                      text, charset, 5)
              do_test(" \t\f\n# coding: {0}\n".format(charset),
                      text, charset, 5)
 -        # Issue #18960: coding spec should has no effect
 -        do_test("0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5)
 +        # Issue #18960: coding spec should have no effect
 +        do_test("x=0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5)
  
+     @support.requires_type_collecting
      def test_print_traceback_at_exit(self):
          # Issue #22599: Ensure that it is possible to use the traceback module
          # to display an exception at Python exit
Simple merge