/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: Jelmer Vernooij
  • Date: 2018-11-12 01:41:38 UTC
  • mto: (7143.16.20 even-more-cleanups)
  • mto: This revision was merged to the branch mainline in revision 7175.
  • Revision ID: jelmer@jelmer.uk-20181112014138-3b0zyx91cu3wdq3k
More PEP8 fixes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
75
75
    hooks,
76
76
    lock as _mod_lock,
77
77
    lockdir,
78
 
    memorytree,
79
78
    osutils,
80
79
    plugin as _mod_plugin,
81
80
    pyutils,
113
112
    treeshape,
114
113
    ui_testing,
115
114
    )
116
 
from ..tests.features import _CompatabilityThunkFeature
117
115
 
118
116
# Mark this python module as being part of the implementation
119
117
# of unittest: this gives us better tracebacks where the last
311
309
        self._show_list('ERROR', self.errors)
312
310
        self._show_list('FAIL', self.failures)
313
311
        self.stream.write(self.sep2)
314
 
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
315
 
                                                         run, run != 1 and "s" or "", timeTaken))
 
312
        self.stream.write("%s %d test%s in %.3fs\n\n" % (
 
313
            actionTaken, run, run != 1 and "s" or "", timeTaken))
316
314
        if not self.wasSuccessful():
317
315
            self.stream.write("FAILED (")
318
316
            failed, errored = map(len, (self.failures, self.errors))
371
369
        # to decide whether to round/floor/ceiling. This was added when we
372
370
        # had pyp3 test failures that suggest a floor was happening.
373
371
        shift = 10 ** precision
374
 
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds
375
 
                          + a_timedelta.microseconds / 1000000.0) * shift) / shift
 
372
        return math.ceil(
 
373
            (a_timedelta.days * 86400.0 + a_timedelta.seconds +
 
374
             a_timedelta.microseconds / 1000000.0) * shift) / shift
376
375
 
377
376
    def _elapsedTestTimeString(self):
378
 
        """Return a time string for the overall time the current test has taken."""
 
377
        """Return time string for overall time the current test has taken."""
379
378
        return self._formatTime(self._delta_to_float(
380
379
            self._now() - self._start_datetime, 3))
381
380
 
632
631
        # tests skipped as known not to be relevant are not important enough
633
632
        # to show here
634
633
        # if self.skip_count:
635
 
        ##     a += ', %d skip' % self.skip_count
 
634
        #     a += ', %d skip' % self.skip_count
636
635
        # if self.known_failure_count:
637
 
        ##     a += '+%dX' % self.known_failure_count
 
636
        #     a += '+%dX' % self.known_failure_count
638
637
        if self.num_tests:
639
638
            a += '/%d' % self.num_tests
640
639
        a += ' in '
654
653
    def report_test_start(self, test):
655
654
        self.pb.update(
656
655
            self._progress_prefix_text() +
657
 
                ' ' +
658
 
                self._shortened_test_description(test))
 
656
            ' ' +
 
657
            self._shortened_test_description(test))
659
658
 
660
659
    def _test_description(self, test):
661
660
        return self._shortened_test_description(test)
783
782
 
784
783
        :param result_decorators: An optional list of decorators to apply
785
784
            to the result object being used by the runner. Decorators are
786
 
            applied left to right - the first element in the list is the 
 
785
            applied left to right - the first element in the list is the
787
786
            innermost decorator.
788
787
        """
789
788
        # stream may know claim to know to write unicode strings, but in older
864
863
def _clever_some_str(value):
865
864
    try:
866
865
        return str(value)
867
 
    except:
 
866
    except BaseException:
868
867
        try:
869
868
            return repr(value).replace('\\n', '\n')
870
 
        except:
 
869
        except BaseException:
871
870
            return '<unprintable %s object>' % type(value).__name__
872
871
 
873
872
 
949
948
    def __init__(self, methodName='testMethod'):
950
949
        super(TestCase, self).__init__(methodName)
951
950
        self._directory_isolation = True
952
 
        self.exception_handlers.insert(0,
953
 
                                       (UnavailableFeature, self._do_unsupported_or_skip))
954
 
        self.exception_handlers.insert(0,
955
 
                                       (TestNotApplicable, self._do_not_applicable))
 
951
        self.exception_handlers.insert(
 
952
            0, (UnavailableFeature, self._do_unsupported_or_skip))
 
953
        self.exception_handlers.insert(
 
954
            0, (TestNotApplicable, self._do_not_applicable))
956
955
 
957
956
    def setUp(self):
958
957
        super(TestCase, self).setUp()
1036
1035
            raise AssertionError('%s is already used as a counter name'
1037
1036
                                 % (counter_name,))
1038
1037
        _counters[counter_name] = 0
1039
 
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
1040
 
                                                     lambda: [b'%d' % (_counters[counter_name],)]))
 
1038
        self.addDetail(counter_name, content.Content(
 
1039
            content.UTF8_TEXT,
 
1040
            lambda: [b'%d' % (_counters[counter_name],)]))
1041
1041
 
1042
1042
        def increment_counter(*args, **kwargs):
1043
1043
            _counters[counter_name] += 1
1219
1219
            return
1220
1220
        # This prevents all transports, including e.g. sftp ones backed on disk
1221
1221
        # from working unless they are explicitly granted permission. We then
1222
 
        # depend on the code that sets up test transports to check that they are
1223
 
        # appropriately isolated and enable their use by calling
 
1222
        # depend on the code that sets up test transports to check that they
 
1223
        # are appropriately isolated and enable their use by calling
1224
1224
        # self.permit_transport()
1225
1225
        if not osutils.is_inside_any(self._bzr_selftest_roots, url):
1226
1226
            raise errors.BzrError("Attempt to escape test isolation: %r %r"
1283
1283
        # hook into brz dir opening. This leaves a small window of error for
1284
1284
        # transport tests, but they are well known, and we can improve on this
1285
1285
        # step.
1286
 
        controldir.ControlDir.hooks.install_named_hook("pre_open",
1287
 
                                                       self._preopen_isolate_transport, "Check brz directories are safe.")
 
1286
        controldir.ControlDir.hooks.install_named_hook(
 
1287
            "pre_open", self._preopen_isolate_transport,
 
1288
            "Check brz directories are safe.")
1288
1289
 
1289
1290
    def _ndiff_strings(self, a, b):
1290
1291
        """Return ndiff between two strings containing lines.
1417
1418
    def assertContainsRe(self, haystack, needle_re, flags=0):
1418
1419
        """Assert that a contains something matching a regular expression."""
1419
1420
        if not re.search(needle_re, haystack, flags):
1420
 
            if ('\n' if isinstance(haystack, str) else b'\n') in haystack or len(haystack) > 60:
 
1421
            if (('\n' if isinstance(haystack, str) else b'\n') in haystack or
 
1422
                    len(haystack) > 60):
1421
1423
                # a long string, format it in a more readable way
1422
1424
                raise AssertionError(
1423
1425
                    'pattern "%s" not found in\n"""\\\n%s"""\n'
1536
1538
        """Fail if path does not contain 'content'."""
1537
1539
        self.assertPathExists(path)
1538
1540
 
1539
 
        with open(path, 'r' + ('b' if isinstance(content, bytes) else '')) as f:
 
1541
        mode = 'r' + ('b' if isinstance(content, bytes) else '')
 
1542
        with open(path, mode) as f:
1540
1543
            s = f.read()
1541
1544
        self.assertEqualDiff(content, s)
1542
1545
 
1619
1622
        :param kwargs: The keyword arguments for the callable
1620
1623
        :return: The result of a_callable(``*args``, ``**kwargs``)
1621
1624
        """
1622
 
        call_warnings, result = self._capture_deprecation_warnings(a_callable,
1623
 
                                                                   *args, **kwargs)
 
1625
        call_warnings, result = self._capture_deprecation_warnings(
 
1626
            a_callable, *args, **kwargs)
1624
1627
        expected_first_warning = symbol_versioning.deprecation_string(
1625
1628
            a_callable, deprecation_format)
1626
1629
        if len(call_warnings) == 0:
1678
1681
        :param args: The positional arguments for the callable
1679
1682
        :param kwargs: The keyword arguments for the callable
1680
1683
        """
1681
 
        call_warnings, result = self._capture_deprecation_warnings(callable,
1682
 
                                                                   *args, **kwargs)
 
1684
        call_warnings, result = self._capture_deprecation_warnings(
 
1685
            callable, *args, **kwargs)
1683
1686
        self.assertEqual(expected, call_warnings)
1684
1687
        return result
1685
1688
 
1690
1693
        def _get_log_contents_for_weird_testtools_api():
1691
1694
            return [pseudo_log_file.getvalue().decode(
1692
1695
                "utf-8", "replace").encode("utf-8")]
1693
 
        self.addDetail("log", content.Content(content.ContentType("text",
1694
 
                                                                  "plain", {"charset": "utf8"}),
1695
 
                                              _get_log_contents_for_weird_testtools_api))
 
1696
        self.addDetail(
 
1697
            "log", content.Content(
 
1698
                content.ContentType("text", "plain", {"charset": "utf8"}),
 
1699
                _get_log_contents_for_weird_testtools_api))
1696
1700
        self._log_file = pseudo_log_file
1697
1701
        self._log_memento = trace.push_log_file(self._log_file)
1698
1702
        self.addCleanup(self._finishLogFile)
1752
1756
 
1753
1757
        :param name: The environment variable name.
1754
1758
 
1755
 
        :param new: The value to set the variable to. If None, the 
 
1759
        :param new: The value to set the variable to. If None, the
1756
1760
            variable is deleted from the environment.
1757
1761
 
1758
1762
        :returns: The actual variable value.
1768
1772
 
1769
1773
        :param obj: The namespace holding the reference to be replaced;
1770
1774
            typically a module, class, or object.
1771
 
        :param attr_name: A string for the name of the attribute to 
1772
 
            patch.
 
1775
        :param attr_name: A string for the name of the attribute to patch.
1773
1776
        :returns: A list that will be extended with one item every time the
1774
1777
            function is called, with a tuple of (args, kwargs).
1775
1778
        """
1892
1895
        self._benchcalls.
1893
1896
        """
1894
1897
        if self._benchtime is None:
1895
 
            self.addDetail('benchtime', content.Content(content.UTF8_TEXT,
1896
 
                                                        lambda: [str(self._benchtime).encode('utf-8')]))
 
1898
            self.addDetail('benchtime', content.Content(
 
1899
                content.UTF8_TEXT,
 
1900
                lambda: [str(self._benchtime).encode('utf-8')]))
1897
1901
            self._benchtime = 0
1898
1902
        start = time.time()
1899
1903
        try:
2106
2110
        logger.addHandler(handler)
2107
2111
 
2108
2112
        try:
2109
 
            result = self._run_bzr_core(args,
2110
 
                                        encoding=encoding, stdin=stdin, stdout=stdout,
2111
 
                                        stderr=stderr, working_dir=working_dir,
2112
 
                                        )
 
2113
            result = self._run_bzr_core(
 
2114
                args, encoding=encoding, stdin=stdin, stdout=stdout,
 
2115
                stderr=stderr, working_dir=working_dir)
2113
2116
        finally:
2114
2117
            logger.removeHandler(handler)
2115
2118
 
2149
2152
            # Make sure --strict is handling an unknown file, rather than
2150
2153
            # giving us the 'nothing to do' error
2151
2154
            self.build_tree(['unknown'])
2152
 
            self.run_bzr_error(['Commit refused because there are unknown files'],
2153
 
                               ['commit', --strict', '-m', 'my commit comment'])
 
2155
            self.run_bzr_error(
 
2156
                ['Commit refused because there are unknown files'],
 
2157
                ['commit', --strict', '-m', 'my commit comment'])
2154
2158
        """
2155
2159
        kwargs.setdefault('retcode', 3)
2156
2160
        kwargs['error_regexes'] = error_regexes
2300
2304
            #    log_file_path, buffer_now=True)
2301
2305
            with open(log_file_path, 'rb') as log_file:
2302
2306
                log_file_bytes = log_file.read()
2303
 
            detail_content = content.Content(content.ContentType("text",
2304
 
                                                                 "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2307
            detail_content = content.Content(
 
2308
                content.ContentType("text", "plain", {"charset": "utf8"}),
 
2309
                lambda: [log_file_bytes])
2305
2310
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
2306
2311
                           detail_content)
2307
2312
 
2514
2519
            """
2515
2520
            self.addCleanup(transport.disconnect)
2516
2521
 
2517
 
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
2518
 
                                                          _add_disconnect_cleanup, None)
 
2522
        _mod_transport.Transport.hooks.install_named_hook(
 
2523
            'post_connect', _add_disconnect_cleanup, None)
2519
2524
 
2520
2525
        self._make_test_root()
2521
2526
        self.addCleanup(os.chdir, osutils.getcwd())
2572
2577
                self.__readonly_server = test_server.ReadonlyServer()
2573
2578
            else:
2574
2579
                # explicit readonly transport.
2575
 
                self.__readonly_server = self.create_transport_readonly_server()
 
2580
                self.__readonly_server = (
 
2581
                    self.create_transport_readonly_server())
2576
2582
            self.start_server(self.__readonly_server,
2577
2583
                              self.get_vfs_only_server())
2578
2584
        return self.__readonly_server
2733
2739
        This must set self.test_home_dir and self.test_dir and chdir to
2734
2740
        self.test_dir.
2735
2741
 
2736
 
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
 
2742
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this
 
2743
        test.
2737
2744
        """
2738
2745
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2739
2746
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
4272
4279
                if (
4273
4280
                        # Either the module name starts with the specified string
4274
4281
                        name.startswith(start)
4275
 
 or                     # or it may contain tests starting with the specified string
 
4282
                    or                     # or it may contain tests starting with the specified string
4276
4283
                        start.startswith(name)
4277
4284
                        ):
4278
4285
                    return True