~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Patch Queue Manager
  • Date: 2016-04-21 04:10:52 UTC
  • mfrom: (6616.1.1 fix-en-user-guide)
  • Revision ID: pqm@pqm.ubuntu.com-20160421041052-clcye7ns1qcl2n7w
(richard-wilbur) Ensure build of English use guide always uses English text
 even when user's locale specifies a different language. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2013, 2015, 2016 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
32
32
import errno
33
33
import itertools
34
34
import logging
 
35
import math
35
36
import os
36
37
import platform
37
38
import pprint
60
61
import bzrlib
61
62
from bzrlib import (
62
63
    branchbuilder,
63
 
    bzrdir,
 
64
    controldir,
64
65
    chk_map,
65
66
    commands as _mod_commands,
66
67
    config,
248
249
    different types of display.
249
250
 
250
251
    When a test finishes, in whatever way, it calls one of the addSuccess,
251
 
    addFailure or addError classes.  These in turn may redirect to a more
 
252
    addFailure or addError methods.  These in turn may redirect to a more
252
253
    specific case for the special test results supported by our extended
253
254
    tests.
254
255
 
359
360
            return float(''.join(details['benchtime'].iter_bytes()))
360
361
        return getattr(testCase, "_benchtime", None)
361
362
 
 
363
    def _delta_to_float(self, a_timedelta, precision):
 
364
        # This calls ceiling to ensure that the most pessimistic view of time
 
365
        # taken is shown (rather than leaving it to the Python %f operator
 
366
        # to decide whether to round/floor/ceiling. This was added when we
 
367
        # had pyp3 test failures that suggest a floor was happening.
 
368
        shift = 10 ** precision
 
369
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
 
370
            a_timedelta.microseconds / 1000000.0) * shift) / shift
 
371
 
362
372
    def _elapsedTestTimeString(self):
363
373
        """Return a time string for the overall time the current test has taken."""
364
374
        return self._formatTime(self._delta_to_float(
365
 
            self._now() - self._start_datetime))
 
375
            self._now() - self._start_datetime, 3))
366
376
 
367
377
    def _testTimeString(self, testCase):
368
378
        benchmark_time = self._extractBenchmarkTime(testCase)
1001
1011
    def setUp(self):
1002
1012
        super(TestCase, self).setUp()
1003
1013
 
 
1014
        # At this point we're still accessing the config files in $BZR_HOME (as
 
1015
        # set by the user running selftest).
1004
1016
        timeout = config.GlobalStack().get('selftest.timeout')
1005
1017
        if timeout:
1006
1018
            timeout_fixture = fixtures.TimeoutFixture(timeout)
1027
1039
        # between tests.  We should get rid of this altogether: bug 656694. --
1028
1040
        # mbp 20101008
1029
1041
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
1030
 
        # Isolate config option expansion until its default value for bzrlib is
1031
 
        # settled on or a the FIXME associated with _get_expand_default_value
1032
 
        # is addressed -- vila 20110219
1033
 
        self.overrideAttr(config, '_expand_default_value', None)
1034
1042
        self._log_files = set()
1035
1043
        # Each key in the ``_counters`` dict holds a value for a different
1036
1044
        # counter. When the test ends, addDetail() should be used to output the
1329
1337
        # hook into bzr dir opening. This leaves a small window of error for
1330
1338
        # transport tests, but they are well known, and we can improve on this
1331
1339
        # step.
1332
 
        bzrdir.BzrDir.hooks.install_named_hook("pre_open",
 
1340
        controldir.ControlDir.hooks.install_named_hook("pre_open",
1333
1341
            self._preopen_isolate_transport, "Check bzr directories are safe.")
1334
1342
 
1335
1343
    def _ndiff_strings(self, a, b):
1361
1369
            % (message,
1362
1370
               pprint.pformat(a), pprint.pformat(b)))
1363
1371
 
 
1372
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
 
1373
    # need a deprecation period for them -- vila 2016-02-01
1364
1374
    assertEquals = assertEqual
1365
1375
 
1366
1376
    def assertEqualDiff(self, a, b, message=None):
1369
1379
        This is intended for use with multi-line strings where it can
1370
1380
        be hard to find the differences by eye.
1371
1381
        """
1372
 
        # TODO: perhaps override assertEquals to call this for strings?
 
1382
        # TODO: perhaps override assertEqual to call this for strings?
1373
1383
        if a == b:
1374
1384
            return
1375
1385
        if message is None:
1782
1792
 
1783
1793
        :returns: The actual attr value.
1784
1794
        """
1785
 
        value = getattr(obj, attr_name)
1786
1795
        # The actual value is captured by the call below
1787
 
        self.addCleanup(setattr, obj, attr_name, value)
 
1796
        value = getattr(obj, attr_name, _unitialized_attr)
 
1797
        if value is _unitialized_attr:
 
1798
            # When the test completes, the attribute should not exist, but if
 
1799
            # we aren't setting a value, we don't need to do anything.
 
1800
            if new is not _unitialized_attr:
 
1801
                self.addCleanup(delattr, obj, attr_name)
 
1802
        else:
 
1803
            self.addCleanup(setattr, obj, attr_name, value)
1788
1804
        if new is not _unitialized_attr:
1789
1805
            setattr(obj, attr_name, new)
1790
1806
        return value
2036
2052
        if err:
2037
2053
            self.log('errors:\n%r', err)
2038
2054
        if retcode is not None:
2039
 
            self.assertEquals(retcode, result,
 
2055
            self.assertEqual(retcode, result,
2040
2056
                              message='Unexpected return code')
2041
2057
        return result, out, err
2042
2058
 
2451
2467
        self.transport_readonly_server = None
2452
2468
        self.__vfs_server = None
2453
2469
 
 
2470
    def setUp(self):
 
2471
        super(TestCaseWithMemoryTransport, self).setUp()
 
2472
 
 
2473
        def _add_disconnect_cleanup(transport):
 
2474
            """Schedule disconnection of given transport at test cleanup
 
2475
 
 
2476
            This needs to happen for all connected transports or leaks occur.
 
2477
 
 
2478
            Note reconnections may mean we call disconnect multiple times per
 
2479
            transport which is suboptimal but seems harmless.
 
2480
            """
 
2481
            self.addCleanup(transport.disconnect)
 
2482
 
 
2483
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2484
            _add_disconnect_cleanup, None)
 
2485
 
 
2486
        self._make_test_root()
 
2487
        self.addCleanup(os.chdir, os.getcwdu())
 
2488
        self.makeAndChdirToTestDir()
 
2489
        self.overrideEnvironmentForTesting()
 
2490
        self.__readonly_server = None
 
2491
        self.__server = None
 
2492
        self.reduceLockdirTimeout()
 
2493
        # Each test may use its own config files even if the local config files
 
2494
        # don't actually exist. They'll rightly fail if they try to create them
 
2495
        # though.
 
2496
        self.overrideAttr(config, '_shared_stores', {})
 
2497
 
2454
2498
    def get_transport(self, relpath=None):
2455
2499
        """Return a writeable transport.
2456
2500
 
2599
2643
        real branch.
2600
2644
        """
2601
2645
        root = TestCaseWithMemoryTransport.TEST_ROOT
2602
 
        # Make sure we get a readable and accessible home for .bzr.log
2603
 
        # and/or config files, and not fallback to weird defaults (see
2604
 
        # http://pad.lv/825027).
2605
 
        self.assertIs(None, os.environ.get('BZR_HOME', None))
2606
 
        os.environ['BZR_HOME'] = root
2607
 
        wt = bzrdir.BzrDir.create_standalone_workingtree(root)
2608
 
        del os.environ['BZR_HOME']
 
2646
        try:
 
2647
            # Make sure we get a readable and accessible home for .bzr.log
 
2648
            # and/or config files, and not fallback to weird defaults (see
 
2649
            # http://pad.lv/825027).
 
2650
            self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2651
            os.environ['BZR_HOME'] = root
 
2652
            wt = controldir.ControlDir.create_standalone_workingtree(root)
 
2653
            del os.environ['BZR_HOME']
 
2654
        except Exception, e:
 
2655
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
2609
2656
        # Hack for speed: remember the raw bytes of the dirstate file so that
2610
2657
        # we don't need to re-open the wt to check it hasn't changed.
2611
2658
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
2681
2728
        if format is None:
2682
2729
            format = self.get_default_format()
2683
2730
        if isinstance(format, basestring):
2684
 
            format = bzrdir.format_registry.make_bzrdir(format)
 
2731
            format = controldir.format_registry.make_bzrdir(format)
2685
2732
        return format
2686
2733
 
2687
2734
    def make_bzrdir(self, relpath, format=None):
2734
2781
        self.overrideEnv('HOME', test_home_dir)
2735
2782
        self.overrideEnv('BZR_HOME', test_home_dir)
2736
2783
 
2737
 
    def setUp(self):
2738
 
        super(TestCaseWithMemoryTransport, self).setUp()
2739
 
 
2740
 
        def _add_disconnect_cleanup(transport):
2741
 
            """Schedule disconnection of given transport at test cleanup
2742
 
 
2743
 
            This needs to happen for all connected transports or leaks occur.
2744
 
 
2745
 
            Note reconnections may mean we call disconnect multiple times per
2746
 
            transport which is suboptimal but seems harmless.
2747
 
            """
2748
 
            self.addCleanup(transport.disconnect)
2749
 
 
2750
 
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
2751
 
            _add_disconnect_cleanup, None)
2752
 
 
2753
 
        self._make_test_root()
2754
 
        self.addCleanup(os.chdir, os.getcwdu())
2755
 
        self.makeAndChdirToTestDir()
2756
 
        self.overrideEnvironmentForTesting()
2757
 
        self.__readonly_server = None
2758
 
        self.__server = None
2759
 
        self.reduceLockdirTimeout()
2760
 
 
2761
2784
    def setup_smart_server_with_call_log(self):
2762
2785
        """Sets up a smart server as the transport server with a call log."""
2763
2786
        self.transport_server = test_server.SmartTCPServer_for_testing
2855
2878
        # stacking policy to honour; create a bzr dir with an unshared
2856
2879
        # repository (but not a branch - our code would be trying to escape
2857
2880
        # then!) to stop them, and permit it to be read.
2858
 
        # control = bzrdir.BzrDir.create(self.test_base_dir)
 
2881
        # control = controldir.ControlDir.create(self.test_base_dir)
2859
2882
        # control.create_repository()
2860
2883
        self.test_home_dir = self.test_base_dir + '/home'
2861
2884
        os.mkdir(self.test_home_dir)
2950
2973
    readwrite one must both define get_url() as resolving to os.getcwd().
2951
2974
    """
2952
2975
 
 
2976
    def setUp(self):
 
2977
        super(TestCaseWithTransport, self).setUp()
 
2978
        self.__vfs_server = None
 
2979
 
2953
2980
    def get_vfs_only_server(self):
2954
2981
        """See TestCaseWithMemoryTransport.
2955
2982
 
3001
3028
            if self.vfs_transport_factory is test_server.LocalURLServer:
3002
3029
                # the branch is colocated on disk, we cannot create a checkout.
3003
3030
                # hopefully callers will expect this.
3004
 
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
 
3031
                local_controldir = controldir.ControlDir.open(
 
3032
                    self.get_vfs_only_url(relpath))
3005
3033
                wt = local_controldir.create_workingtree()
3006
3034
                if wt.branch._format != b._format:
3007
3035
                    wt._branch = b
3037
3065
        self.assertFalse(differences.has_changed(),
3038
3066
            "Trees %r and %r are different: %r" % (left, right, differences))
3039
3067
 
3040
 
    def setUp(self):
3041
 
        super(TestCaseWithTransport, self).setUp()
3042
 
        self.__vfs_server = None
3043
 
 
3044
3068
    def disable_missing_extensions_warning(self):
3045
3069
        """Some tests expect a precise stderr content.
3046
3070
 
3047
3071
        There is no point in forcing them to duplicate the extension related
3048
3072
        warning.
3049
3073
        """
3050
 
        config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
 
3074
        config.GlobalStack().set('ignore_missing_extensions', True)
3051
3075
 
3052
3076
 
3053
3077
class ChrootedTestCase(TestCaseWithTransport):
3780
3804
 
3781
3805
    :return: (absents, duplicates) absents is a list containing the test found
3782
3806
        in id_list but not in test_suite, duplicates is a list containing the
3783
 
        test found multiple times in test_suite.
 
3807
        tests found multiple times in test_suite.
3784
3808
 
3785
3809
    When using a prefined test id list, it may occurs that some tests do not
3786
3810
    exist anymore or that some tests use the same id. This function warns the
4329
4353
    """Copy test and apply scenario to it.
4330
4354
 
4331
4355
    :param test: A test to adapt.
4332
 
    :param scenario: A tuple describing the scenarion.
 
4356
    :param scenario: A tuple describing the scenario.
4333
4357
        The first element of the tuple is the new test id.
4334
4358
        The second element is a dict containing attributes to set on the
4335
4359
        test.