/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

Support user.signingkey configuration variable in .git/config.

Merged from https://code.launchpad.net/~jelmer/brz/local-git-key/+merge/381000

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Testing framework extensions"""
18
18
 
 
19
from __future__ import absolute_import
 
20
 
19
21
# NOTE: Some classes in here use camelCaseNaming() rather than
20
22
# underscore_naming().  That's for consistency with unittest; it's not the
21
23
# general style of breezy.  Please continue that consistency when adding e.g.
92
94
except ImportError:
93
95
    # lsprof not available
94
96
    pass
 
97
from ..sixish import (
 
98
    int2byte,
 
99
    PY3,
 
100
    string_types,
 
101
    text_type,
 
102
    )
95
103
from ..bzr.smart import client, request
96
104
from ..transport import (
97
105
    memory,
1323
1331
            return
1324
1332
        if message is None:
1325
1333
            message = "texts not equal:\n"
1326
 
        if a + ('\n' if isinstance(a, str) else b'\n') == b:
 
1334
        if a + ('\n' if isinstance(a, text_type) else b'\n') == b:
1327
1335
            message = 'first string is missing a final newline.\n'
1328
 
        if a == b + ('\n' if isinstance(b, str) else b'\n'):
 
1336
        if a == b + ('\n' if isinstance(b, text_type) else b'\n'):
1329
1337
            message = 'second string is missing a final newline.\n'
1330
1338
        raise AssertionError(message
1331
1339
                             + self._ndiff_strings(
1332
 
                                 a if isinstance(a, str) else a.decode(),
1333
 
                                 b if isinstance(b, str) else b.decode()))
 
1340
                                 a if isinstance(a, text_type) else a.decode(),
 
1341
                                 b if isinstance(b, text_type) else b.decode()))
1334
1342
 
1335
1343
    def assertEqualMode(self, mode, mode_test):
1336
1344
        self.assertEqual(mode, mode_test,
1548
1556
    def assertPathExists(self, path):
1549
1557
        """Fail unless path or paths, which may be abs or relative, exist."""
1550
1558
        # TODO(jelmer): Clean this up for pad.lv/1696545
1551
 
        if not isinstance(path, (bytes, str)):
 
1559
        if not isinstance(path, (bytes, str, text_type)):
1552
1560
            for p in path:
1553
1561
                self.assertPathExists(p)
1554
1562
        else:
1557
1565
 
1558
1566
    def assertPathDoesNotExist(self, path):
1559
1567
        """Fail if path or paths, which may be abs or relative, exist."""
1560
 
        if not isinstance(path, (str, str)):
 
1568
        if not isinstance(path, (str, text_type)):
1561
1569
            for p in path:
1562
1570
                self.assertPathDoesNotExist(p)
1563
1571
        else:
1932
1940
 
1933
1941
        self.log('run brz: %r', args)
1934
1942
 
1935
 
        self._last_cmd_stdout = stdout
1936
 
        self._last_cmd_stderr = stderr
 
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
1949
 
1938
1950
        old_ui_factory = ui.ui_factory
1939
1951
        ui.ui_factory = ui_testing.TestUIFactory(
1993
2005
        :keyword error_regexes: A list of expected error messages.  If
1994
2006
            specified they must be seen in the error output of the command.
1995
2007
        """
1996
 
        if isinstance(args, str):
 
2008
        if isinstance(args, string_types):
1997
2009
            args = shlex.split(args)
1998
2010
 
1999
2011
        if encoding is None:
2000
2012
            encoding = osutils.get_user_encoding()
2001
2013
 
2002
 
        stdout = BytesIO()
2003
 
        stderr = BytesIO()
2004
 
        wrapped_stdout = TextIOWrapper(stdout, encoding)
2005
 
        wrapped_stderr = TextIOWrapper(stderr, encoding)
2006
 
        handler = logging.StreamHandler(wrapped_stderr)
 
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)
2007
2028
        handler.setLevel(logging.INFO)
2008
2029
 
2009
2030
        logger = logging.getLogger('')
2016
2037
        finally:
2017
2038
            logger.removeHandler(handler)
2018
2039
 
2019
 
        wrapped_stdout.flush()
2020
 
        wrapped_stderr.flush()
 
2040
        if PY3:
 
2041
            wrapped_stdout.flush()
 
2042
            wrapped_stderr.flush()
2021
2043
 
2022
2044
        out = stdout.getvalue()
2023
2045
        err = stderr.getvalue()
2066
2088
        :keyword error_regexes: A list of expected error messages.  If
2067
2089
            specified they must be seen in the error output of the command.
2068
2090
        """
2069
 
        if isinstance(args, str):
 
2091
        if isinstance(args, string_types):
2070
2092
            args = shlex.split(args)
2071
2093
 
2072
2094
        if encoding is None:
2073
2095
            encoding = osutils.get_user_encoding()
2074
2096
 
2075
 
        stdout = ui_testing.StringIOWithEncoding()
2076
 
        stderr = ui_testing.StringIOWithEncoding()
2077
 
        stdout.encoding = stderr.encoding = encoding
2078
 
        handler = logging.StreamHandler(stream=stderr)
 
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)
2079
2109
        handler.setLevel(logging.INFO)
2080
2110
 
2081
2111
        logger = logging.getLogger('')
2160
2190
        if len(args) == 1:
2161
2191
            if isinstance(args[0], list):
2162
2192
                args = args[0]
2163
 
            elif isinstance(args[0], str):
 
2193
            elif isinstance(args[0], (str, text_type)):
2164
2194
                args = list(shlex.split(args[0]))
2165
2195
        else:
2166
2196
            raise ValueError("passing varargs to run_bzr_subprocess")
2365
2395
            if getattr(self, "_log_file", None) is not None:
2366
2396
                stdout = self._log_file
2367
2397
            else:
2368
 
                stdout = StringIO()
 
2398
                if sys.version_info[0] == 2:
 
2399
                    stdout = BytesIO()
 
2400
                else:
 
2401
                    stdout = StringIO()
2369
2402
        if stderr is None:
2370
2403
            if getattr(self, "_log_file", None is not None):
2371
2404
                stderr = self._log_file
2372
2405
            else:
2373
 
                stderr = StringIO()
 
2406
                if sys.version_info[0] == 2:
 
2407
                    stderr = BytesIO()
 
2408
                else:
 
2409
                    stderr = StringIO()
2374
2410
        real_stdin = sys.stdin
2375
2411
        real_stdout = sys.stdout
2376
2412
        real_stderr = sys.stderr
2782
2818
 
2783
2819
    def overrideEnvironmentForTesting(self):
2784
2820
        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())
2785
2823
        self.overrideEnv('HOME', test_home_dir)
2786
2824
        self.overrideEnv('BRZ_HOME', test_home_dir)
2787
2825
        self.overrideEnv('GNUPGHOME', os.path.join(test_home_dir, '.gnupg'))
2922
2960
        if transport is None or transport.is_readonly():
2923
2961
            transport = _mod_transport.get_transport_from_path(".")
2924
2962
        for name in shape:
2925
 
            self.assertIsInstance(name, str)
 
2963
            self.assertIsInstance(name, (str, text_type))
2926
2964
            if name[-1] == '/':
2927
2965
                transport.mkdir(urlutils.escape(name[:-1]))
2928
2966
            else:
2942
2980
        """Assert whether path or paths are in the WorkingTree"""
2943
2981
        if tree is None:
2944
2982
            tree = workingtree.WorkingTree.open(root_path)
2945
 
        if not isinstance(path, str):
 
2983
        if not isinstance(path, (str, text_type)):
2946
2984
            for p in path:
2947
2985
                self.assertInWorkingTree(p, tree=tree)
2948
2986
        else:
2953
2991
        """Assert whether path or paths are not in the WorkingTree"""
2954
2992
        if tree is None:
2955
2993
            tree = workingtree.WorkingTree.open(root_path)
2956
 
        if not isinstance(path, str):
 
2994
        if not isinstance(path, (str, text_type)):
2957
2995
            for p in path:
2958
2996
                self.assertNotInWorkingTree(p, tree=tree)
2959
2997
        else:
3599
3637
                # The traceback is formatted to a string and written in one go
3600
3638
                # to avoid interleaving lines from multiple failing children.
3601
3639
                tb = traceback.format_exc()
3602
 
                if isinstance(tb, str):
 
3640
                if isinstance(tb, text_type):
3603
3641
                    tb = tb.encode('utf-8')
3604
3642
                try:
3605
3643
                    stream.write(tb)
4036
4074
        'breezy.tests.test_chk_serializer',
4037
4075
        'breezy.tests.test_chunk_writer',
4038
4076
        'breezy.tests.test_clean_tree',
 
4077
        'breezy.tests.test_cleanup',
4039
4078
        'breezy.tests.test_cmdline',
4040
4079
        'breezy.tests.test_commands',
4041
4080
        'breezy.tests.test_commit',
4271
4310
    # modules building their suite with loadTestsFromModuleNames
4272
4311
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
4273
4312
 
4274
 
    suite.addTest(loader.loadTestsFromModuleNames(['breezy.doc']))
 
4313
    if not PY3:
 
4314
        suite.addTest(loader.loadTestsFromModuleNames(['breezy.doc']))
4275
4315
 
4276
 
    for mod in _test_suite_modules_to_doctest():
4277
 
        if not interesting_module(mod):
4278
 
            # No tests to keep here, move along
4279
 
            continue
4280
 
        try:
4281
 
            # note that this really does mean "report only" -- doctest
4282
 
            # still runs the rest of the examples
4283
 
            doc_suite = IsolatedDocTestSuite(
4284
 
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
4285
 
        except ValueError as e:
4286
 
            print('**failed to get doctest for: %s\n%s' % (mod, e))
4287
 
            raise
4288
 
        if len(doc_suite._tests) == 0:
4289
 
            raise errors.BzrError("no doctests found in %s" % (mod,))
4290
 
        suite.addTest(doc_suite)
 
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)
4291
4335
 
4292
4336
    default_encoding = sys.getdefaultencoding()
4293
4337
    for name, plugin in _mod_plugin.plugins().items():
4449
4493
    return new_test
4450
4494
 
4451
4495
 
4452
 
 
4453
4496
def permute_tests_for_extension(standard_tests, loader, py_module_name,
4454
4497
                                ext_module_name):
4455
4498
    """Helper for permutating tests against an extension module.
4483
4526
    if feature.available():
4484
4527
        scenarios.append(('C', {'module': feature.module}))
4485
4528
    else:
 
4529
        # the compiled module isn't available, so we add a failing test
4486
4530
        class FailWithoutFeature(TestCase):
4487
 
            def id(self):
4488
 
                return ext_module_name + '.' + super(FailWithoutFeature, self).id()
4489
4531
            def test_fail(self):
4490
4532
                self.requireFeature(feature)
4491
 
        # the compiled module isn't available, so we add a failing test
4492
4533
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
4493
4534
    result = multiply_tests(standard_tests, scenarios, suite)
4494
4535
    return result, feature
4547
4588
    for given encoding.
4548
4589
    """
4549
4590
    for i in range(128, 256):
4550
 
        char = bytes([i])
 
4591
        char = int2byte(i)
4551
4592
        try:
4552
4593
            char.decode(encoding)
4553
4594
        except UnicodeDecodeError: