/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/__init__.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2020-02-14 03:16:54 UTC
  • mfrom: (7479.2.3 no-more-python2)
  • Revision ID: breezy.the.bot@gmail.com-20200214031654-bp1xtv2jr9nmhto3
Drop python2 support.

Merged from https://code.launchpad.net/~jelmer/brz/no-more-python2/+merge/378694

Show diffs side-by-side

added added

removed removed

Lines of Context:
94
94
except ImportError:
95
95
    # lsprof not available
96
96
    pass
97
 
from ..sixish import (
98
 
    int2byte,
99
 
    PY3,
100
 
    string_types,
101
 
    text_type,
102
 
    )
103
97
from ..bzr.smart import client, request
104
98
from ..transport import (
105
99
    memory,
1331
1325
            return
1332
1326
        if message is None:
1333
1327
            message = "texts not equal:\n"
1334
 
        if a + ('\n' if isinstance(a, text_type) else b'\n') == b:
 
1328
        if a + ('\n' if isinstance(a, str) else b'\n') == b:
1335
1329
            message = 'first string is missing a final newline.\n'
1336
 
        if a == b + ('\n' if isinstance(b, text_type) else b'\n'):
 
1330
        if a == b + ('\n' if isinstance(b, str) else b'\n'):
1337
1331
            message = 'second string is missing a final newline.\n'
1338
1332
        raise AssertionError(message
1339
1333
                             + self._ndiff_strings(
1340
 
                                 a if isinstance(a, text_type) else a.decode(),
1341
 
                                 b if isinstance(b, text_type) else b.decode()))
 
1334
                                 a if isinstance(a, str) else a.decode(),
 
1335
                                 b if isinstance(b, str) else b.decode()))
1342
1336
 
1343
1337
    def assertEqualMode(self, mode, mode_test):
1344
1338
        self.assertEqual(mode, mode_test,
1556
1550
    def assertPathExists(self, path):
1557
1551
        """Fail unless path or paths, which may be abs or relative, exist."""
1558
1552
        # TODO(jelmer): Clean this up for pad.lv/1696545
1559
 
        if not isinstance(path, (bytes, str, text_type)):
 
1553
        if not isinstance(path, (bytes, str)):
1560
1554
            for p in path:
1561
1555
                self.assertPathExists(p)
1562
1556
        else:
1565
1559
 
1566
1560
    def assertPathDoesNotExist(self, path):
1567
1561
        """Fail if path or paths, which may be abs or relative, exist."""
1568
 
        if not isinstance(path, (str, text_type)):
 
1562
        if not isinstance(path, (str, str)):
1569
1563
            for p in path:
1570
1564
                self.assertPathDoesNotExist(p)
1571
1565
        else:
1940
1934
 
1941
1935
        self.log('run brz: %r', args)
1942
1936
 
1943
 
        if PY3:
1944
 
            self._last_cmd_stdout = stdout
1945
 
            self._last_cmd_stderr = stderr
1946
 
        else:
1947
 
            self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
1948
 
            self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
 
1937
        self._last_cmd_stdout = stdout
 
1938
        self._last_cmd_stderr = stderr
1949
1939
 
1950
1940
        old_ui_factory = ui.ui_factory
1951
1941
        ui.ui_factory = ui_testing.TestUIFactory(
2005
1995
        :keyword error_regexes: A list of expected error messages.  If
2006
1996
            specified they must be seen in the error output of the command.
2007
1997
        """
2008
 
        if isinstance(args, string_types):
 
1998
        if isinstance(args, str):
2009
1999
            args = shlex.split(args)
2010
2000
 
2011
2001
        if encoding is None:
2012
2002
            encoding = osutils.get_user_encoding()
2013
2003
 
2014
 
        if sys.version_info[0] == 2:
2015
 
            wrapped_stdout = stdout = ui_testing.BytesIOWithEncoding()
2016
 
            wrapped_stderr = stderr = ui_testing.BytesIOWithEncoding()
2017
 
            stdout.encoding = stderr.encoding = encoding
2018
 
 
2019
 
            # FIXME: don't call into logging here
2020
 
            handler = trace.EncodedStreamHandler(
2021
 
                stderr, errors="replace")
2022
 
        else:
2023
 
            stdout = BytesIO()
2024
 
            stderr = BytesIO()
2025
 
            wrapped_stdout = TextIOWrapper(stdout, encoding)
2026
 
            wrapped_stderr = TextIOWrapper(stderr, encoding)
2027
 
            handler = logging.StreamHandler(wrapped_stderr)
 
2004
        stdout = BytesIO()
 
2005
        stderr = BytesIO()
 
2006
        wrapped_stdout = TextIOWrapper(stdout, encoding)
 
2007
        wrapped_stderr = TextIOWrapper(stderr, encoding)
 
2008
        handler = logging.StreamHandler(wrapped_stderr)
2028
2009
        handler.setLevel(logging.INFO)
2029
2010
 
2030
2011
        logger = logging.getLogger('')
2037
2018
        finally:
2038
2019
            logger.removeHandler(handler)
2039
2020
 
2040
 
        if PY3:
2041
 
            wrapped_stdout.flush()
2042
 
            wrapped_stderr.flush()
 
2021
        wrapped_stdout.flush()
 
2022
        wrapped_stderr.flush()
2043
2023
 
2044
2024
        out = stdout.getvalue()
2045
2025
        err = stderr.getvalue()
2088
2068
        :keyword error_regexes: A list of expected error messages.  If
2089
2069
            specified they must be seen in the error output of the command.
2090
2070
        """
2091
 
        if isinstance(args, string_types):
 
2071
        if isinstance(args, str):
2092
2072
            args = shlex.split(args)
2093
2073
 
2094
2074
        if encoding is None:
2095
2075
            encoding = osutils.get_user_encoding()
2096
2076
 
2097
 
        if sys.version_info[0] == 2:
2098
 
            stdout = ui_testing.BytesIOWithEncoding()
2099
 
            stderr = ui_testing.BytesIOWithEncoding()
2100
 
            stdout.encoding = stderr.encoding = encoding
2101
 
            # FIXME: don't call into logging here
2102
 
            handler = trace.EncodedStreamHandler(
2103
 
                stderr, errors="replace")
2104
 
        else:
2105
 
            stdout = ui_testing.StringIOWithEncoding()
2106
 
            stderr = ui_testing.StringIOWithEncoding()
2107
 
            stdout.encoding = stderr.encoding = encoding
2108
 
            handler = logging.StreamHandler(stream=stderr)
 
2077
        stdout = ui_testing.StringIOWithEncoding()
 
2078
        stderr = ui_testing.StringIOWithEncoding()
 
2079
        stdout.encoding = stderr.encoding = encoding
 
2080
        handler = logging.StreamHandler(stream=stderr)
2109
2081
        handler.setLevel(logging.INFO)
2110
2082
 
2111
2083
        logger = logging.getLogger('')
2190
2162
        if len(args) == 1:
2191
2163
            if isinstance(args[0], list):
2192
2164
                args = args[0]
2193
 
            elif isinstance(args[0], (str, text_type)):
 
2165
            elif isinstance(args[0], str):
2194
2166
                args = list(shlex.split(args[0]))
2195
2167
        else:
2196
2168
            raise ValueError("passing varargs to run_bzr_subprocess")
2395
2367
            if getattr(self, "_log_file", None) is not None:
2396
2368
                stdout = self._log_file
2397
2369
            else:
2398
 
                if sys.version_info[0] == 2:
2399
 
                    stdout = BytesIO()
2400
 
                else:
2401
 
                    stdout = StringIO()
 
2370
                stdout = StringIO()
2402
2371
        if stderr is None:
2403
2372
            if getattr(self, "_log_file", None is not None):
2404
2373
                stderr = self._log_file
2405
2374
            else:
2406
 
                if sys.version_info[0] == 2:
2407
 
                    stderr = BytesIO()
2408
 
                else:
2409
 
                    stderr = StringIO()
 
2375
                stderr = StringIO()
2410
2376
        real_stdin = sys.stdin
2411
2377
        real_stdout = sys.stdout
2412
2378
        real_stderr = sys.stderr
2818
2784
 
2819
2785
    def overrideEnvironmentForTesting(self):
2820
2786
        test_home_dir = self.test_home_dir
2821
 
        if not PY3 and isinstance(test_home_dir, text_type):
2822
 
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2823
2787
        self.overrideEnv('HOME', test_home_dir)
2824
2788
        self.overrideEnv('BRZ_HOME', test_home_dir)
2825
2789
        self.overrideEnv('GNUPGHOME', os.path.join(test_home_dir, '.gnupg'))
2960
2924
        if transport is None or transport.is_readonly():
2961
2925
            transport = _mod_transport.get_transport_from_path(".")
2962
2926
        for name in shape:
2963
 
            self.assertIsInstance(name, (str, text_type))
 
2927
            self.assertIsInstance(name, str)
2964
2928
            if name[-1] == '/':
2965
2929
                transport.mkdir(urlutils.escape(name[:-1]))
2966
2930
            else:
2980
2944
        """Assert whether path or paths are in the WorkingTree"""
2981
2945
        if tree is None:
2982
2946
            tree = workingtree.WorkingTree.open(root_path)
2983
 
        if not isinstance(path, (str, text_type)):
 
2947
        if not isinstance(path, str):
2984
2948
            for p in path:
2985
2949
                self.assertInWorkingTree(p, tree=tree)
2986
2950
        else:
2991
2955
        """Assert whether path or paths are not in the WorkingTree"""
2992
2956
        if tree is None:
2993
2957
            tree = workingtree.WorkingTree.open(root_path)
2994
 
        if not isinstance(path, (str, text_type)):
 
2958
        if not isinstance(path, str):
2995
2959
            for p in path:
2996
2960
                self.assertNotInWorkingTree(p, tree=tree)
2997
2961
        else:
3637
3601
                # The traceback is formatted to a string and written in one go
3638
3602
                # to avoid interleaving lines from multiple failing children.
3639
3603
                tb = traceback.format_exc()
3640
 
                if isinstance(tb, text_type):
 
3604
                if isinstance(tb, str):
3641
3605
                    tb = tb.encode('utf-8')
3642
3606
                try:
3643
3607
                    stream.write(tb)
4074
4038
        'breezy.tests.test_chk_serializer',
4075
4039
        'breezy.tests.test_chunk_writer',
4076
4040
        'breezy.tests.test_clean_tree',
4077
 
        'breezy.tests.test_cleanup',
4078
4041
        'breezy.tests.test_cmdline',
4079
4042
        'breezy.tests.test_commands',
4080
4043
        'breezy.tests.test_commit',
4310
4273
    # modules building their suite with loadTestsFromModuleNames
4311
4274
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
4312
4275
 
4313
 
    if not PY3:
4314
 
        suite.addTest(loader.loadTestsFromModuleNames(['breezy.doc']))
 
4276
    suite.addTest(loader.loadTestsFromModuleNames(['breezy.doc']))
4315
4277
 
4316
 
        # It's pretty much impossible to write readable doctests that work on
4317
 
        # both Python 2 and Python 3 because of their overreliance on
4318
 
        # consistent repr() return values.
4319
 
        # For now, just run doctests on Python 2 so we now they haven't broken.
4320
 
        for mod in _test_suite_modules_to_doctest():
4321
 
            if not interesting_module(mod):
4322
 
                # No tests to keep here, move along
4323
 
                continue
4324
 
            try:
4325
 
                # note that this really does mean "report only" -- doctest
4326
 
                # still runs the rest of the examples
4327
 
                doc_suite = IsolatedDocTestSuite(
4328
 
                    mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
4329
 
            except ValueError as e:
4330
 
                print('**failed to get doctest for: %s\n%s' % (mod, e))
4331
 
                raise
4332
 
            if len(doc_suite._tests) == 0:
4333
 
                raise errors.BzrError("no doctests found in %s" % (mod,))
4334
 
            suite.addTest(doc_suite)
 
4278
    for mod in _test_suite_modules_to_doctest():
 
4279
        if not interesting_module(mod):
 
4280
            # No tests to keep here, move along
 
4281
            continue
 
4282
        try:
 
4283
            # note that this really does mean "report only" -- doctest
 
4284
            # still runs the rest of the examples
 
4285
            doc_suite = IsolatedDocTestSuite(
 
4286
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4287
        except ValueError as e:
 
4288
            print('**failed to get doctest for: %s\n%s' % (mod, e))
 
4289
            raise
 
4290
        if len(doc_suite._tests) == 0:
 
4291
            raise errors.BzrError("no doctests found in %s" % (mod,))
 
4292
        suite.addTest(doc_suite)
4335
4293
 
4336
4294
    default_encoding = sys.getdefaultencoding()
4337
4295
    for name, plugin in _mod_plugin.plugins().items():
4493
4451
    return new_test
4494
4452
 
4495
4453
 
 
4454
 
4496
4455
def permute_tests_for_extension(standard_tests, loader, py_module_name,
4497
4456
                                ext_module_name):
4498
4457
    """Helper for permutating tests against an extension module.
4526
4485
    if feature.available():
4527
4486
        scenarios.append(('C', {'module': feature.module}))
4528
4487
    else:
4529
 
        # the compiled module isn't available, so we add a failing test
4530
4488
        class FailWithoutFeature(TestCase):
 
4489
            def id(self):
 
4490
                return ext_module_name + '.' + super(FailWithoutFeature, self).id()
4531
4491
            def test_fail(self):
4532
4492
                self.requireFeature(feature)
 
4493
        # the compiled module isn't available, so we add a failing test
4533
4494
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
4534
4495
    result = multiply_tests(standard_tests, scenarios, suite)
4535
4496
    return result, feature
4588
4549
    for given encoding.
4589
4550
    """
4590
4551
    for i in range(128, 256):
4591
 
        char = int2byte(i)
 
4552
        char = bytes([i])
4592
4553
        try:
4593
4554
            char.decode(encoding)
4594
4555
        except UnicodeDecodeError: