/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 bzrlib/tests/__init__.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2013, 2015, 2016 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
20
20
 
21
21
# NOTE: Some classes in here use camelCaseNaming() rather than
22
22
# underscore_naming().  That's for consistency with unittest; it's not the
23
 
# general style of breezy.  Please continue that consistency when adding e.g.
 
23
# general style of bzrlib.  Please continue that consistency when adding e.g.
24
24
# new assertFoo() methods.
25
25
 
26
26
import atexit
27
27
import codecs
28
28
import copy
 
29
from cStringIO import StringIO
29
30
import difflib
30
31
import doctest
31
32
import errno
32
 
import functools
33
33
import itertools
34
34
import logging
35
35
import math
58
58
        % (testtools.__file__, _testtools_version))
59
59
from testtools import content
60
60
 
61
 
import breezy
62
 
from .. import (
 
61
import bzrlib
 
62
from bzrlib import (
63
63
    branchbuilder,
64
64
    controldir,
 
65
    chk_map,
65
66
    commands as _mod_commands,
66
67
    config,
67
68
    i18n,
82
83
    transport as _mod_transport,
83
84
    workingtree,
84
85
    )
85
 
from breezy.bzr import (
86
 
    chk_map,
87
 
    )
88
86
try:
89
 
    import breezy.lsprof
 
87
    import bzrlib.lsprof
90
88
except ImportError:
91
89
    # lsprof not available
92
90
    pass
93
 
from ..sixish import (
94
 
    BytesIO,
95
 
    PY3,
96
 
    string_types,
97
 
    text_type,
98
 
    )
99
 
from ..bzr.smart import client, request
100
 
from ..transport import (
 
91
from bzrlib.smart import client, request
 
92
from bzrlib.transport import (
101
93
    memory,
102
94
    pathfilter,
103
95
    )
104
 
from ..tests import (
 
96
from bzrlib.symbol_versioning import (
 
97
    deprecated_function,
 
98
    deprecated_in,
 
99
    )
 
100
from bzrlib.tests import (
105
101
    fixtures,
106
102
    test_server,
107
103
    TestUtil,
108
104
    treeshape,
109
 
    ui_testing,
110
105
    )
111
 
from ..tests.features import _CompatabilityThunkFeature
 
106
from bzrlib.ui import NullProgressView
 
107
from bzrlib.ui.text import TextUIFactory
 
108
from bzrlib.tests.features import _CompatabilityThunkFeature
112
109
 
113
110
# Mark this python module as being part of the implementation
114
111
# of unittest: this gives us better tracebacks where the last
127
124
SUBUNIT_SEEK_CUR = 1
128
125
 
129
126
# These are intentionally brought into this namespace. That way plugins, etc
130
 
# can just "from breezy.tests import TestCase, TestLoader, etc"
 
127
# can just "from bzrlib.tests import TestCase, TestLoader, etc"
131
128
TestSuite = TestUtil.TestSuite
132
129
TestLoader = TestUtil.TestLoader
133
130
 
139
136
# the tests should start without this variable in the environment. There are a
140
137
# few exceptions but you shouldn't violate this rule lightly.
141
138
isolated_environ = {
142
 
    'BRZ_HOME': None,
 
139
    'BZR_HOME': None,
143
140
    'HOME': None,
144
 
    'GNUPGHOME': None,
145
141
    'XDG_CONFIG_HOME': None,
146
 
    # brz now uses the Win32 API and doesn't rely on APPDATA, but the
 
142
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
147
143
    # tests do check our impls match APPDATA
148
 
    'BRZ_EDITOR': None, # test_msgeditor manipulates this variable
 
144
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
149
145
    'VISUAL': None,
150
146
    'EDITOR': None,
151
 
    'BRZ_EMAIL': None,
 
147
    'BZR_EMAIL': None,
152
148
    'BZREMAIL': None, # may still be present in the environment
153
 
    'EMAIL': 'jrandom@example.com', # set EMAIL as brz does not guess
154
 
    'BRZ_PROGRESS_BAR': None,
155
 
    # This should trap leaks to ~/.brz.log. This occurs when tests use TestCase
 
149
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
 
150
    'BZR_PROGRESS_BAR': None,
 
151
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
156
152
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
157
 
    # TestCase should not use disk resources, BRZ_LOG is one.
158
 
    'BRZ_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
159
 
    'BRZ_PLUGIN_PATH': '-site',
160
 
    'BRZ_DISABLE_PLUGINS': None,
161
 
    'BRZ_PLUGINS_AT': None,
162
 
    'BRZ_CONCURRENCY': None,
 
153
    # TestCase should not use disk resources, BZR_LOG is one.
 
154
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
155
    'BZR_PLUGIN_PATH': None,
 
156
    'BZR_DISABLE_PLUGINS': None,
 
157
    'BZR_PLUGINS_AT': None,
 
158
    'BZR_CONCURRENCY': None,
163
159
    # Make sure that any text ui tests are consistent regardless of
164
160
    # the environment the test case is run in; you may want tests that
165
161
    # test other combinations.  'dumb' is a reasonable guess for tests
166
 
    # going to a pipe or a BytesIO.
 
162
    # going to a pipe or a StringIO.
167
163
    'TERM': 'dumb',
168
164
    'LINES': '25',
169
165
    'COLUMNS': '80',
170
 
    'BRZ_COLUMNS': '80',
 
166
    'BZR_COLUMNS': '80',
171
167
    # Disable SSH Agent
172
168
    'SSH_AUTH_SOCK': None,
173
169
    # Proxies
195
191
 
196
192
def override_os_environ(test, env=None):
197
193
    """Modify os.environ keeping a copy.
198
 
 
 
194
    
199
195
    :param test: A test instance
200
196
 
201
197
    :param env: A dict containing variable definitions to be installed
202
198
    """
203
199
    if env is None:
204
200
        env = isolated_environ
205
 
    test._original_os_environ = dict(**os.environ)
206
 
    for var in env:
207
 
        osutils.set_or_unset_env(var, env[var])
 
201
    test._original_os_environ = dict([(var, value)
 
202
                                      for var, value in os.environ.iteritems()])
 
203
    for var, value in env.iteritems():
 
204
        osutils.set_or_unset_env(var, value)
208
205
        if var not in test._original_os_environ:
209
206
            # The var is new, add it with a value of None, so
210
207
            # restore_os_environ will delete it
216
213
 
217
214
    :param test: A test instance previously passed to override_os_environ.
218
215
    """
219
 
    for var, value in test._original_os_environ.items():
 
216
    for var, value in test._original_os_environ.iteritems():
220
217
        # Restore the original value (or delete it if the value has been set to
221
218
        # None in override_os_environ).
222
219
        osutils.set_or_unset_env(var, value)
272
269
        """
273
270
        testtools.TextTestResult.__init__(self, stream)
274
271
        if bench_history is not None:
275
 
            from breezy.version import _get_bzr_source_tree
 
272
            from bzrlib.version import _get_bzr_source_tree
276
273
            src_tree = _get_bzr_source_tree()
277
274
            if src_tree:
278
275
                try:
392
389
 
393
390
    def _shortened_test_description(self, test):
394
391
        what = test.id()
395
 
        what = re.sub(r'^breezy\.tests\.', '', what)
 
392
        what = re.sub(r'^bzrlib\.tests\.', '', what)
396
393
        return what
397
394
 
398
395
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
415
412
        addOnException = getattr(test, "addOnException", None)
416
413
        if addOnException is not None:
417
414
            addOnException(self._record_traceback_from_test)
418
 
        # Only check for thread leaks on breezy derived test cases
 
415
        # Only check for thread leaks on bzrlib derived test cases
419
416
        if isinstance(test, TestCase):
420
417
            test.addCleanup(self._check_leaked_threads, test)
421
418
 
538
535
 
539
536
    def _post_mortem(self, tb=None):
540
537
        """Start a PDB post mortem session."""
541
 
        if os.environ.get('BRZ_TEST_PDB', None):
 
538
        if os.environ.get('BZR_TEST_PDB', None):
542
539
            import pdb
543
540
            pdb.post_mortem(tb)
544
541
 
558
555
        else:
559
556
            bzr_path = sys.executable
560
557
        self.stream.write(
561
 
            'brz selftest: %s\n' % (bzr_path,))
 
558
            'bzr selftest: %s\n' % (bzr_path,))
562
559
        self.stream.write(
563
560
            '   %s\n' % (
564
 
                    breezy.__path__[0],))
 
561
                    bzrlib.__path__[0],))
565
562
        self.stream.write(
566
563
            '   bzr-%s python-%s %s\n' % (
567
 
                    breezy.version_string,
568
 
                    breezy._format_version_tuple(sys.version_info),
 
564
                    bzrlib.version_string,
 
565
                    bzrlib._format_version_tuple(sys.version_info),
569
566
                    platform.platform(aliased=1),
570
567
                    ))
571
568
        self.stream.write('\n')
600
597
 
601
598
    def __init__(self, stream, descriptions, verbosity,
602
599
                 bench_history=None,
 
600
                 pb=None,
603
601
                 strict=None,
604
602
                 ):
605
603
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
606
604
            bench_history, strict)
 
605
        # We no longer pass them around, but just rely on the UIFactory stack
 
606
        # for state
 
607
        if pb is not None:
 
608
            warnings.warn("Passing pb to TextTestResult is deprecated")
607
609
        self.pb = self.ui.nested_progress_bar()
608
610
        self.pb.show_pct = False
609
611
        self.pb.show_spinner = False
790
792
        # to encode using ascii.
791
793
        new_encoding = osutils.get_terminal_encoding()
792
794
        codec = codecs.lookup(new_encoding)
793
 
        encode = codec.encode
 
795
        if type(codec) is tuple:
 
796
            # Python 2.4
 
797
            encode = codec[0]
 
798
        else:
 
799
            encode = codec.encode
794
800
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
795
801
        #                so should swap to the plain codecs.StreamWriter
796
802
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
884
890
    """
885
891
 
886
892
 
887
 
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
888
 
 
889
 
    @symbol_versioning.deprecated_method(
890
 
        symbol_versioning.deprecated_in((3, 0)))
 
893
class StringIOWrapper(object):
 
894
    """A wrapper around cStringIO which just adds an encoding attribute.
 
895
 
 
896
    Internally we can check sys.stdout to see what the output encoding
 
897
    should be. However, cStringIO has no encoding attribute that we can
 
898
    set. So we wrap it instead.
 
899
    """
 
900
    encoding='ascii'
 
901
    _cstring = None
 
902
 
891
903
    def __init__(self, s=None):
892
 
        super(StringIOWrapper, self).__init__(s)
893
 
 
894
 
 
895
 
TestUIFactory = ui_testing.TestUIFactory
 
904
        if s is not None:
 
905
            self.__dict__['_cstring'] = StringIO(s)
 
906
        else:
 
907
            self.__dict__['_cstring'] = StringIO()
 
908
 
 
909
    def __getattr__(self, name, getattr=getattr):
 
910
        return getattr(self.__dict__['_cstring'], name)
 
911
 
 
912
    def __setattr__(self, name, val):
 
913
        if name == 'encoding':
 
914
            self.__dict__['encoding'] = val
 
915
        else:
 
916
            return setattr(self._cstring, name, val)
 
917
 
 
918
 
 
919
class TestUIFactory(TextUIFactory):
 
920
    """A UI Factory for testing.
 
921
 
 
922
    Hide the progress bar but emit note()s.
 
923
    Redirect stdin.
 
924
    Allows get_password to be tested without real tty attached.
 
925
 
 
926
    See also CannedInputUIFactory which lets you provide programmatic input in
 
927
    a structured way.
 
928
    """
 
929
    # TODO: Capture progress events at the model level and allow them to be
 
930
    # observed by tests that care.
 
931
    #
 
932
    # XXX: Should probably unify more with CannedInputUIFactory or a
 
933
    # particular configuration of TextUIFactory, or otherwise have a clearer
 
934
    # idea of how they're supposed to be different.
 
935
    # See https://bugs.launchpad.net/bzr/+bug/408213
 
936
 
 
937
    def __init__(self, stdout=None, stderr=None, stdin=None):
 
938
        if stdin is not None:
 
939
            # We use a StringIOWrapper to be able to test various
 
940
            # encodings, but the user is still responsible to
 
941
            # encode the string and to set the encoding attribute
 
942
            # of StringIOWrapper.
 
943
            stdin = StringIOWrapper(stdin)
 
944
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
 
945
 
 
946
    def get_non_echoed_password(self):
 
947
        """Get password from stdin without trying to handle the echo mode"""
 
948
        password = self.stdin.readline()
 
949
        if not password:
 
950
            raise EOFError
 
951
        if password[-1] == '\n':
 
952
            password = password[:-1]
 
953
        return password
 
954
 
 
955
    def make_progress_view(self):
 
956
        return NullProgressView()
896
957
 
897
958
 
898
959
def isolated_doctest_setUp(test):
899
960
    override_os_environ(test)
900
 
    osutils.set_or_unset_env('BRZ_HOME', '/nonexistent')
901
 
    test._orig_ui_factory = ui.ui_factory
902
 
    ui.ui_factory = ui.SilentUIFactory()
903
961
 
904
962
 
905
963
def isolated_doctest_tearDown(test):
906
964
    restore_os_environ(test)
907
 
    ui.ui_factory = test._orig_ui_factory
908
965
 
909
966
 
910
967
def IsolatedDocTestSuite(*args, **kwargs):
919
976
 
920
977
 
921
978
class TestCase(testtools.TestCase):
922
 
    """Base class for brz unit tests.
 
979
    """Base class for bzr unit tests.
923
980
 
924
981
    Tests that need access to disk resources should subclass
925
982
    TestCaseInTempDir not TestCase.
931
988
    is read into memory and removed from disk.
932
989
 
933
990
    There are also convenience functions to invoke bzr's command-line
934
 
    routine, and to build and check brz trees.
 
991
    routine, and to build and check bzr trees.
935
992
 
936
993
    In addition to the usual method of overriding tearDown(), this class also
937
994
    allows subclasses to register cleanup functions via addCleanup, which are
954
1011
    def setUp(self):
955
1012
        super(TestCase, self).setUp()
956
1013
 
957
 
        # At this point we're still accessing the config files in $BRZ_HOME (as
 
1014
        # At this point we're still accessing the config files in $BZR_HOME (as
958
1015
        # set by the user running selftest).
959
1016
        timeout = config.GlobalStack().get('selftest.timeout')
960
1017
        if timeout:
966
1023
            self.requireFeature(feature)
967
1024
        self._cleanEnvironment()
968
1025
 
969
 
        self.overrideAttr(breezy.get_global_state(), 'cmdline_overrides',
970
 
                          config.CommandLineStore())
 
1026
        if bzrlib.global_state is not None:
 
1027
            self.overrideAttr(bzrlib.global_state, 'cmdline_overrides',
 
1028
                              config.CommandLineStore())
971
1029
 
972
1030
        self._silenceUI()
973
1031
        self._startLogFile()
980
1038
        # Isolate global verbosity level, to make sure it's reproducible
981
1039
        # between tests.  We should get rid of this altogether: bug 656694. --
982
1040
        # mbp 20101008
983
 
        self.overrideAttr(breezy.trace, '_verbosity_level', 0)
 
1041
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
984
1042
        self._log_files = set()
985
1043
        # Each key in the ``_counters`` dict holds a value for a different
986
1044
        # counter. When the test ends, addDetail() should be used to output the
1001
1059
    def discardDetail(self, name):
1002
1060
        """Extend the addDetail, getDetails api so we can remove a detail.
1003
1061
 
1004
 
        eg. brz always adds the 'log' detail at startup, but we don't want to
 
1062
        eg. bzr always adds the 'log' detail at startup, but we don't want to
1005
1063
        include it for skipped, xfail, etc tests.
1006
1064
 
1007
1065
        It is safe to call this for a detail that doesn't exist, in case this
1029
1087
        _counters = self._counters # Avoid closing over self
1030
1088
        if counter_name is None:
1031
1089
            counter_name = name
1032
 
        if counter_name in _counters:
 
1090
        if _counters.has_key(counter_name):
1033
1091
            raise AssertionError('%s is already used as a counter name'
1034
1092
                                  % (counter_name,))
1035
1093
        _counters[counter_name] = 0
1036
1094
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
1037
 
            lambda: [b'%d' % (_counters[counter_name],)]))
 
1095
            lambda: ['%d' % (_counters[counter_name],)]))
1038
1096
        def increment_counter(*args, **kwargs):
1039
1097
            _counters[counter_name] += 1
1040
1098
        label = 'count %s calls' % (counter_name,)
1126
1184
                (acquired_locks, released_locks, broken_locks))
1127
1185
            if not self._lock_check_thorough:
1128
1186
                # Rather than fail, just warn
1129
 
                print("Broken test %s: %s" % (self, message))
 
1187
                print "Broken test %s: %s" % (self, message)
1130
1188
                return
1131
1189
            self.fail(message)
1132
1190
 
1163
1221
 
1164
1222
    def permit_url(self, url):
1165
1223
        """Declare that url is an ok url to use in this test.
1166
 
 
 
1224
        
1167
1225
        Do this for memory transports, temporary test directory etc.
1168
 
 
 
1226
        
1169
1227
        Do not do this for the current working directory, /tmp, or any other
1170
1228
        preexisting non isolated url.
1171
1229
        """
1174
1232
        self._bzr_selftest_roots.append(url)
1175
1233
 
1176
1234
    def permit_source_tree_branch_repo(self):
1177
 
        """Permit the source tree brz is running from to be opened.
 
1235
        """Permit the source tree bzr is running from to be opened.
1178
1236
 
1179
 
        Some code such as breezy.version attempts to read from the brz branch
1180
 
        that brz is executing from (if any). This method permits that directory
 
1237
        Some code such as bzrlib.version attempts to read from the bzr branch
 
1238
        that bzr is executing from (if any). This method permits that directory
1181
1239
        to be used in the test suite.
1182
1240
        """
1183
1241
        path = self.get_source_path()
1186
1244
            try:
1187
1245
                workingtree.WorkingTree.open(path)
1188
1246
            except (errors.NotBranchError, errors.NoWorkingTree):
1189
 
                raise TestSkipped('Needs a working tree of brz sources')
 
1247
                raise TestSkipped('Needs a working tree of bzr sources')
1190
1248
        finally:
1191
1249
            self.enable_directory_isolation()
1192
1250
 
1224
1282
 
1225
1283
    def record_directory_isolation(self):
1226
1284
        """Gather accessed directories to permit later access.
1227
 
 
1228
 
        This is used for tests that access the branch brz is running from.
 
1285
        
 
1286
        This is used for tests that access the branch bzr is running from.
1229
1287
        """
1230
1288
        self._directory_isolation = "record"
1231
1289
 
1276
1334
        # TestCase has no safe place it can write to.
1277
1335
        self._bzr_selftest_roots = []
1278
1336
        # Currently the easiest way to be sure that nothing is going on is to
1279
 
        # hook into brz dir opening. This leaves a small window of error for
 
1337
        # hook into bzr dir opening. This leaves a small window of error for
1280
1338
        # transport tests, but they are well known, and we can improve on this
1281
1339
        # step.
1282
1340
        controldir.ControlDir.hooks.install_named_hook("pre_open",
1283
 
            self._preopen_isolate_transport, "Check brz directories are safe.")
 
1341
            self._preopen_isolate_transport, "Check bzr directories are safe.")
1284
1342
 
1285
1343
    def _ndiff_strings(self, a, b):
1286
1344
        """Return ndiff between two strings containing lines.
1301
1359
        try:
1302
1360
            if a == b:
1303
1361
                return
1304
 
        except UnicodeError as e:
 
1362
        except UnicodeError, e:
1305
1363
            # If we can't compare without getting a UnicodeError, then
1306
1364
            # obviously they are different
1307
1365
            trace.mutter('UnicodeError: %s', e)
1311
1369
            % (message,
1312
1370
               pprint.pformat(a), pprint.pformat(b)))
1313
1371
 
1314
 
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
1315
 
    # need a deprecation period for them -- vila 2016-02-01
1316
1372
    assertEquals = assertEqual
1317
1373
 
1318
1374
    def assertEqualDiff(self, a, b, message=None):
1321
1377
        This is intended for use with multi-line strings where it can
1322
1378
        be hard to find the differences by eye.
1323
1379
        """
1324
 
        # TODO: perhaps override assertEqual to call this for strings?
 
1380
        # TODO: perhaps override assertEquals to call this for strings?
1325
1381
        if a == b:
1326
1382
            return
1327
1383
        if message is None:
1450
1506
        """
1451
1507
        try:
1452
1508
            list(func(*args, **kwargs))
1453
 
        except excClass as e:
 
1509
        except excClass, e:
1454
1510
            return e
1455
1511
        else:
1456
 
            if getattr(excClass, '__name__', None) is not None:
 
1512
            if getattr(excClass,'__name__', None) is not None:
1457
1513
                excName = excClass.__name__
1458
1514
            else:
1459
1515
                excName = str(excClass)
1460
 
            raise self.failureException("%s not raised" % excName)
 
1516
            raise self.failureException, "%s not raised" % excName
1461
1517
 
1462
1518
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
1463
1519
        """Assert that a callable raises a particular exception.
1471
1527
        """
1472
1528
        try:
1473
1529
            callableObj(*args, **kwargs)
1474
 
        except excClass as e:
 
1530
        except excClass, e:
1475
1531
            return e
1476
1532
        else:
1477
 
            if getattr(excClass, '__name__', None) is not None:
 
1533
            if getattr(excClass,'__name__', None) is not None:
1478
1534
                excName = excClass.__name__
1479
1535
            else:
1480
1536
                # probably a tuple
1481
1537
                excName = str(excClass)
1482
 
            raise self.failureException("%s not raised" % excName)
 
1538
            raise self.failureException, "%s not raised" % excName
1483
1539
 
1484
1540
    def assertIs(self, left, right, message=None):
1485
1541
        if not (left is right):
1529
1585
    def assertFileEqual(self, content, path):
1530
1586
        """Fail if path does not contain 'content'."""
1531
1587
        self.assertPathExists(path)
1532
 
        with open(path, 'rb') as f:
 
1588
        f = file(path, 'rb')
 
1589
        try:
1533
1590
            s = f.read()
 
1591
        finally:
 
1592
            f.close()
1534
1593
        self.assertEqualDiff(content, s)
1535
1594
 
1536
1595
    def assertDocstring(self, expected_docstring, obj):
1541
1600
        else:
1542
1601
            self.assertEqual(expected_docstring, obj.__doc__)
1543
1602
 
 
1603
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
 
1604
    def failUnlessExists(self, path):
 
1605
        return self.assertPathExists(path)
 
1606
 
1544
1607
    def assertPathExists(self, path):
1545
1608
        """Fail unless path or paths, which may be abs or relative, exist."""
1546
 
        if not isinstance(path, (str, text_type)):
 
1609
        if not isinstance(path, basestring):
1547
1610
            for p in path:
1548
1611
                self.assertPathExists(p)
1549
1612
        else:
1550
1613
            self.assertTrue(osutils.lexists(path),
1551
1614
                path + " does not exist")
1552
1615
 
 
1616
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
 
1617
    def failIfExists(self, path):
 
1618
        return self.assertPathDoesNotExist(path)
 
1619
 
1553
1620
    def assertPathDoesNotExist(self, path):
1554
1621
        """Fail if path or paths, which may be abs or relative, exist."""
1555
 
        if not isinstance(path, (str, text_type)):
 
1622
        if not isinstance(path, basestring):
1556
1623
            for p in path:
1557
1624
                self.assertPathDoesNotExist(p)
1558
1625
        else:
1675
1742
 
1676
1743
    def _startLogFile(self):
1677
1744
        """Setup a in-memory target for bzr and testcase log messages"""
1678
 
        pseudo_log_file = BytesIO()
 
1745
        pseudo_log_file = StringIO()
1679
1746
        def _get_log_contents_for_weird_testtools_api():
1680
1747
            return [pseudo_log_file.getvalue().decode(
1681
1748
                "utf-8", "replace").encode("utf-8")]
1771
1838
        return calls
1772
1839
 
1773
1840
    def _cleanEnvironment(self):
1774
 
        for name, value in isolated_environ.items():
 
1841
        for name, value in isolated_environ.iteritems():
1775
1842
            self.overrideEnv(name, value)
1776
1843
 
1777
1844
    def _restoreHooks(self):
1778
1845
        for klass, (name, hooks) in self._preserved_hooks.items():
1779
1846
            setattr(klass, name, hooks)
1780
1847
        self._preserved_hooks.clear()
1781
 
        breezy.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1848
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
1782
1849
        self._preserved_lazy_hooks.clear()
1783
1850
 
1784
1851
    def knownFailure(self, reason):
1818
1885
        if not callable(addSkip):
1819
1886
            result.addSuccess(result)
1820
1887
        else:
1821
 
            addSkip(self, str(reason))
 
1888
            addSkip(self, reason)
1822
1889
 
1823
1890
    @staticmethod
1824
1891
    def _do_known_failure(self, result, e):
1876
1943
    def time(self, callable, *args, **kwargs):
1877
1944
        """Run callable and accrue the time it takes to the benchmark time.
1878
1945
 
1879
 
        If lsprofiling is enabled (i.e. by --lsprof-time to brz selftest) then
 
1946
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1880
1947
        this will cause lsprofile statistics to be gathered and stored in
1881
1948
        self._benchcalls.
1882
1949
        """
1883
1950
        if self._benchtime is None:
1884
 
            self.addDetail('benchtime', content.Content(content.UTF8_TEXT,
1885
 
                lambda:[str(self._benchtime).encode('utf-8')]))
 
1951
            self.addDetail('benchtime', content.Content(content.ContentType(
 
1952
                "text", "plain"), lambda:[str(self._benchtime)]))
1886
1953
            self._benchtime = 0
1887
1954
        start = time.time()
1888
1955
        try:
1890
1957
                return callable(*args, **kwargs)
1891
1958
            else:
1892
1959
                # record this benchmark
1893
 
                ret, stats = breezy.lsprof.profile(callable, *args, **kwargs)
 
1960
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
1894
1961
                stats.sort()
1895
1962
                self._benchcalls.append(((callable, args, kwargs), stats))
1896
1963
                return ret
1901
1968
        trace.mutter(*args)
1902
1969
 
1903
1970
    def get_log(self):
1904
 
        """Get a unicode string containing the log from breezy.trace.
 
1971
        """Get a unicode string containing the log from bzrlib.trace.
1905
1972
 
1906
1973
        Undecodable characters are replaced.
1907
1974
        """
1918
1985
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1919
1986
            working_dir):
1920
1987
        """Run bazaar command line, splitting up a string command line."""
1921
 
        if isinstance(args, string_types):
1922
 
            args = shlex.split(args)
 
1988
        if isinstance(args, basestring):
 
1989
            # shlex don't understand unicode strings,
 
1990
            # so args should be plain string (bialix 20070906)
 
1991
            args = list(shlex.split(str(args)))
1923
1992
        return self._run_bzr_core(args, retcode=retcode,
1924
1993
                encoding=encoding, stdin=stdin, working_dir=working_dir,
1925
1994
                )
1931
2000
        chk_map.clear_cache()
1932
2001
        if encoding is None:
1933
2002
            encoding = osutils.get_user_encoding()
1934
 
 
1935
 
        self.log('run brz: %r', args)
1936
 
 
1937
 
        stdout = ui_testing.BytesIOWithEncoding()
1938
 
        stderr = ui_testing.BytesIOWithEncoding()
1939
 
        stdout.encoding = stderr.encoding = encoding
1940
 
 
 
2003
        stdout = StringIOWrapper()
 
2004
        stderr = StringIOWrapper()
 
2005
        stdout.encoding = encoding
 
2006
        stderr.encoding = encoding
 
2007
 
 
2008
        self.log('run bzr: %r', args)
1941
2009
        # FIXME: don't call into logging here
1942
 
        handler = trace.EncodedStreamHandler(
1943
 
            stderr, errors="replace", level=logging.INFO)
 
2010
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
 
2011
            level=logging.INFO)
1944
2012
        logger = logging.getLogger('')
1945
2013
        logger.addHandler(handler)
1946
 
 
1947
 
        self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
1948
 
        self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
1949
 
 
1950
2014
        old_ui_factory = ui.ui_factory
1951
 
        ui.ui_factory = ui_testing.TestUIFactory(
1952
 
            stdin=stdin,
1953
 
            stdout=self._last_cmd_stdout,
1954
 
            stderr=self._last_cmd_stderr)
 
2015
        ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
1955
2016
 
1956
2017
        cwd = None
1957
2018
        if working_dir is not None:
1959
2020
            os.chdir(working_dir)
1960
2021
 
1961
2022
        try:
1962
 
            with ui.ui_factory:
 
2023
            try:
1963
2024
                result = self.apply_redirected(
1964
2025
                    ui.ui_factory.stdin,
1965
2026
                    stdout, stderr,
1966
2027
                    _mod_commands.run_bzr_catch_user_errors,
1967
2028
                    args)
 
2029
            except KeyboardInterrupt:
 
2030
                # Reraise KeyboardInterrupt with contents of redirected stdout
 
2031
                # and stderr as arguments, for tests which are interested in
 
2032
                # stdout and stderr and are expecting the exception.
 
2033
                out = stdout.getvalue()
 
2034
                err = stderr.getvalue()
 
2035
                if out:
 
2036
                    self.log('output:\n%r', out)
 
2037
                if err:
 
2038
                    self.log('errors:\n%r', err)
 
2039
                raise KeyboardInterrupt(out, err)
1968
2040
        finally:
1969
2041
            logger.removeHandler(handler)
1970
2042
            ui.ui_factory = old_ui_factory
1978
2050
        if err:
1979
2051
            self.log('errors:\n%r', err)
1980
2052
        if retcode is not None:
1981
 
            self.assertEqual(retcode, result,
 
2053
            self.assertEquals(retcode, result,
1982
2054
                              message='Unexpected return code')
1983
2055
        return result, out, err
1984
2056
 
1985
 
    def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
1986
 
                working_dir=None, error_regexes=[]):
1987
 
        """Invoke brz, as if it were run from the command line.
 
2057
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
 
2058
                working_dir=None, error_regexes=[], output_encoding=None):
 
2059
        """Invoke bzr, as if it were run from the command line.
1988
2060
 
1989
 
        The argument list should not include the brz program name - the
1990
 
        first argument is normally the brz command.  Arguments may be
 
2061
        The argument list should not include the bzr program name - the
 
2062
        first argument is normally the bzr command.  Arguments may be
1991
2063
        passed in three ways:
1992
2064
 
1993
2065
        1- A list of strings, eg ["commit", "a"].  This is recommended
1997
2069
        2- A single string, eg "add a".  This is the most convenient
1998
2070
        for hardcoded commands.
1999
2071
 
2000
 
        This runs brz through the interface that catches and reports
 
2072
        This runs bzr through the interface that catches and reports
2001
2073
        errors, and with logging set to something approximating the
2002
2074
        default, so that error reporting can be checked.
2003
2075
 
2004
2076
        This should be the main method for tests that want to exercise the
2005
 
        overall behavior of the brz application (rather than a unit test
 
2077
        overall behavior of the bzr application (rather than a unit test
2006
2078
        or a functional test of the library.)
2007
2079
 
2008
2080
        This sends the stdout/stderr results into the test's log,
2028
2100
        return out, err
2029
2101
 
2030
2102
    def run_bzr_error(self, error_regexes, *args, **kwargs):
2031
 
        """Run brz, and check that stderr contains the supplied regexes
 
2103
        """Run bzr, and check that stderr contains the supplied regexes
2032
2104
 
2033
2105
        :param error_regexes: Sequence of regular expressions which
2034
2106
            must each be found in the error output. The relative ordering
2035
2107
            is not enforced.
2036
 
        :param args: command-line arguments for brz
2037
 
        :param kwargs: Keyword arguments which are interpreted by run_brz
 
2108
        :param args: command-line arguments for bzr
 
2109
        :param kwargs: Keyword arguments which are interpreted by run_bzr
2038
2110
            This function changes the default value of retcode to be 3,
2039
 
            since in most cases this is run when you expect brz to fail.
 
2111
            since in most cases this is run when you expect bzr to fail.
2040
2112
 
2041
2113
        :return: (out, err) The actual output of running the command (in case
2042
2114
            you want to do more inspection)
2058
2130
        return out, err
2059
2131
 
2060
2132
    def run_bzr_subprocess(self, *args, **kwargs):
2061
 
        """Run brz in a subprocess for testing.
 
2133
        """Run bzr in a subprocess for testing.
2062
2134
 
2063
 
        This starts a new Python interpreter and runs brz in there.
 
2135
        This starts a new Python interpreter and runs bzr in there.
2064
2136
        This should only be used for tests that have a justifiable need for
2065
2137
        this isolation: e.g. they are testing startup time, or signal
2066
2138
        handling, or early startup code, etc.  Subprocess code can't be
2084
2156
        if len(args) == 1:
2085
2157
            if isinstance(args[0], list):
2086
2158
                args = args[0]
2087
 
            elif isinstance(args[0], (str, text_type)):
 
2159
            elif isinstance(args[0], basestring):
2088
2160
                args = list(shlex.split(args[0]))
2089
2161
        else:
2090
2162
            raise ValueError("passing varargs to run_bzr_subprocess")
2101
2173
                             skip_if_plan_to_signal=False,
2102
2174
                             working_dir=None,
2103
2175
                             allow_plugins=False, stderr=subprocess.PIPE):
2104
 
        """Start brz in a subprocess for testing.
 
2176
        """Start bzr in a subprocess for testing.
2105
2177
 
2106
 
        This starts a new Python interpreter and runs brz in there.
 
2178
        This starts a new Python interpreter and runs bzr in there.
2107
2179
        This should only be used for tests that have a justifiable need for
2108
2180
        this isolation: e.g. they are testing startup time, or signal
2109
2181
        handling, or early startup code, etc.  Subprocess code can't be
2110
2182
        profiled or debugged so easily.
2111
2183
 
2112
 
        :param process_args: a list of arguments to pass to the brz executable,
 
2184
        :param process_args: a list of arguments to pass to the bzr executable,
2113
2185
            for example ``['--version']``.
2114
2186
        :param env_changes: A dictionary which lists changes to environment
2115
2187
            variables. A value of None will unset the env variable.
2117
2189
            child, so you don't need to fix the environment after running.
2118
2190
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
2119
2191
            doesn't support signalling subprocesses.
2120
 
        :param allow_plugins: If False (default) pass --no-plugins to brz.
 
2192
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
2121
2193
        :param stderr: file to use for the subprocess's stderr.  Valid values
2122
2194
            are those valid for the stderr argument of `subprocess.Popen`.
2123
2195
            Default value is ``subprocess.PIPE``.
2138
2210
        old_env = {}
2139
2211
 
2140
2212
        def cleanup_environment():
2141
 
            for env_var, value in env_changes.items():
 
2213
            for env_var, value in env_changes.iteritems():
2142
2214
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
2143
2215
 
2144
2216
        def restore_environment():
2145
 
            for env_var, value in old_env.items():
 
2217
            for env_var, value in old_env.iteritems():
2146
2218
                osutils.set_or_unset_env(env_var, value)
2147
2219
 
2148
 
        bzr_path = self.get_brz_path()
 
2220
        bzr_path = self.get_bzr_path()
2149
2221
 
2150
2222
        cwd = None
2151
2223
        if working_dir is not None:
2159
2231
            cleanup_environment()
2160
2232
            # Include the subprocess's log file in the test details, in case
2161
2233
            # the test fails due to an error in the subprocess.
2162
 
            self._add_subprocess_log(trace._get_brz_log_filename())
 
2234
            self._add_subprocess_log(trace._get_bzr_log_filename())
2163
2235
            command = [sys.executable]
2164
2236
            # frozen executables don't need the path to bzr
2165
2237
            if getattr(sys, "frozen", None) is None:
2213
2285
        return subprocess.Popen(*args, **kwargs)
2214
2286
 
2215
2287
    def get_source_path(self):
2216
 
        """Return the path of the directory containing breezy."""
2217
 
        return os.path.dirname(os.path.dirname(breezy.__file__))
 
2288
        """Return the path of the directory containing bzrlib."""
 
2289
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
2218
2290
 
2219
 
    def get_brz_path(self):
2220
 
        """Return the path of the 'brz' executable for this test suite."""
2221
 
        brz_path = os.path.join(self.get_source_path(), "brz")
2222
 
        if not os.path.isfile(brz_path):
 
2291
    def get_bzr_path(self):
 
2292
        """Return the path of the 'bzr' executable for this test suite."""
 
2293
        bzr_path = os.path.join(self.get_source_path(), "bzr")
 
2294
        if not os.path.isfile(bzr_path):
2223
2295
            # We are probably installed. Assume sys.argv is the right file
2224
 
            brz_path = sys.argv[0]
2225
 
        return brz_path
 
2296
            bzr_path = sys.argv[0]
 
2297
        return bzr_path
2226
2298
 
2227
2299
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
2228
2300
                              universal_newlines=False, process_args=None):
2246
2318
        if retcode is not None and retcode != process.returncode:
2247
2319
            if process_args is None:
2248
2320
                process_args = "(unknown args)"
2249
 
            trace.mutter('Output of brz %r:\n%s', process_args, out)
2250
 
            trace.mutter('Error for brz %r:\n%s', process_args, err)
2251
 
            self.fail('Command brz %r failed with retcode %d != %d'
 
2321
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2322
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
 
2323
            self.fail('Command bzr %s failed with retcode %s != %s'
2252
2324
                      % (process_args, retcode, process.returncode))
2253
2325
        return [out, err]
2254
2326
 
2282
2354
        if not callable(a_callable):
2283
2355
            raise ValueError("a_callable must be callable.")
2284
2356
        if stdin is None:
2285
 
            stdin = BytesIO(b"")
 
2357
            stdin = StringIO("")
2286
2358
        if stdout is None:
2287
2359
            if getattr(self, "_log_file", None) is not None:
2288
2360
                stdout = self._log_file
2289
2361
            else:
2290
 
                stdout = BytesIO()
 
2362
                stdout = StringIO()
2291
2363
        if stderr is None:
2292
2364
            if getattr(self, "_log_file", None is not None):
2293
2365
                stderr = self._log_file
2294
2366
            else:
2295
 
                stderr = BytesIO()
 
2367
                stderr = StringIO()
2296
2368
        real_stdin = sys.stdin
2297
2369
        real_stdout = sys.stdout
2298
2370
        real_stderr = sys.stderr
2315
2387
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2316
2388
 
2317
2389
    def make_utf8_encoded_stringio(self, encoding_type=None):
2318
 
        """Return a wrapped BytesIO, that will encode text input to UTF-8."""
 
2390
        """Return a StringIOWrapper instance, that will encode Unicode
 
2391
        input to UTF-8.
 
2392
        """
2319
2393
        if encoding_type is None:
2320
2394
            encoding_type = 'strict'
2321
 
        bio = BytesIO()
 
2395
        sio = StringIO()
2322
2396
        output_encoding = 'utf-8'
2323
 
        sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
 
2397
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
2324
2398
        sio.encoding = output_encoding
2325
2399
        return sio
2326
2400
 
2327
2401
    def disable_verb(self, verb):
2328
2402
        """Disable a smart server verb for one test."""
2329
 
        from breezy.bzr.smart import request
 
2403
        from bzrlib.smart import request
2330
2404
        request_handlers = request.request_handlers
2331
2405
        orig_method = request_handlers.get(verb)
2332
2406
        orig_info = request_handlers.get_info(verb)
2334
2408
        self.addCleanup(request_handlers.register, verb, orig_method,
2335
2409
            info=orig_info)
2336
2410
 
2337
 
    def __hash__(self):
2338
 
        return id(self)
2339
 
 
2340
2411
 
2341
2412
class CapturedCall(object):
2342
2413
    """A helper for capturing smart server calls for easy debug analysis."""
2367
2438
    Tests that need disk resources should derive from TestCaseInTempDir
2368
2439
    orTestCaseWithTransport.
2369
2440
 
2370
 
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all brz tests.
 
2441
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2371
2442
 
2372
2443
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2373
2444
    a directory which does not exist. This serves to help ensure test isolation
2411
2482
            _add_disconnect_cleanup, None)
2412
2483
 
2413
2484
        self._make_test_root()
2414
 
        self.addCleanup(os.chdir, osutils.getcwd())
 
2485
        self.addCleanup(os.chdir, os.getcwdu())
2415
2486
        self.makeAndChdirToTestDir()
2416
2487
        self.overrideEnvironmentForTesting()
2417
2488
        self.__readonly_server = None
2571
2642
        """
2572
2643
        root = TestCaseWithMemoryTransport.TEST_ROOT
2573
2644
        try:
2574
 
            # Make sure we get a readable and accessible home for .brz.log
 
2645
            # Make sure we get a readable and accessible home for .bzr.log
2575
2646
            # and/or config files, and not fallback to weird defaults (see
2576
2647
            # http://pad.lv/825027).
2577
 
            self.assertIs(None, os.environ.get('BRZ_HOME', None))
2578
 
            os.environ['BRZ_HOME'] = root
 
2648
            self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2649
            os.environ['BZR_HOME'] = root
2579
2650
            wt = controldir.ControlDir.create_standalone_workingtree(root)
2580
 
            del os.environ['BRZ_HOME']
2581
 
        except Exception as e:
 
2651
            del os.environ['BZR_HOME']
 
2652
        except Exception, e:
2582
2653
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
2583
2654
        # Hack for speed: remember the raw bytes of the dirstate file so that
2584
2655
        # we don't need to re-open the wt to check it hasn't changed.
2636
2707
    def make_branch(self, relpath, format=None, name=None):
2637
2708
        """Create a branch on the transport at relpath."""
2638
2709
        repo = self.make_repository(relpath, format=format)
2639
 
        return repo.controldir.create_branch(append_revisions_only=False, name=name)
 
2710
        return repo.bzrdir.create_branch(append_revisions_only=False,
 
2711
                                         name=name)
2640
2712
 
2641
2713
    def get_default_format(self):
2642
2714
        return 'default'
2653
2725
        """
2654
2726
        if format is None:
2655
2727
            format = self.get_default_format()
2656
 
        if isinstance(format, str):
2657
 
            format = controldir.format_registry.make_controldir(format)
 
2728
        if isinstance(format, basestring):
 
2729
            format = controldir.format_registry.make_bzrdir(format)
2658
2730
        return format
2659
2731
 
2660
 
    def make_controldir(self, relpath, format=None):
 
2732
    def make_bzrdir(self, relpath, format=None):
2661
2733
        try:
2662
2734
            # might be a relative or absolute path
2663
2735
            maybe_a_url = self.get_url(relpath)
2679
2751
        # real format, which is incorrect.  Actually we should make sure that
2680
2752
        # RemoteBzrDir returns a RemoteRepository.
2681
2753
        # maybe  mbp 20070410
2682
 
        made_control = self.make_controldir(relpath, format=format)
 
2754
        made_control = self.make_bzrdir(relpath, format=format)
2683
2755
        return made_control.create_repository(shared=shared)
2684
2756
 
2685
2757
    def make_smart_server(self, path, backing_server=None):
2694
2766
    def make_branch_and_memory_tree(self, relpath, format=None):
2695
2767
        """Create a branch on the default transport and a MemoryTree for it."""
2696
2768
        b = self.make_branch(relpath, format=format)
2697
 
        return b.create_memorytree()
 
2769
        return memorytree.MemoryTree.create_on_branch(b)
2698
2770
 
2699
2771
    def make_branch_builder(self, relpath, format=None):
2700
2772
        branch = self.make_branch(relpath, format=format)
2702
2774
 
2703
2775
    def overrideEnvironmentForTesting(self):
2704
2776
        test_home_dir = self.test_home_dir
2705
 
        if not PY3 and isinstance(test_home_dir, text_type):
 
2777
        if isinstance(test_home_dir, unicode):
2706
2778
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2707
2779
        self.overrideEnv('HOME', test_home_dir)
2708
 
        self.overrideEnv('BRZ_HOME', test_home_dir)
2709
 
        self.overrideEnv('GNUPGHOME', os.path.join(test_home_dir, '.gnupg'))
 
2780
        self.overrideEnv('BZR_HOME', test_home_dir)
2710
2781
 
2711
2782
    def setup_smart_server_with_call_log(self):
2712
2783
        """Sets up a smart server as the transport server with a call log."""
2758
2829
        super(TestCaseInTempDir, self).setUp()
2759
2830
        # Remove the protection set in isolated_environ, we have a proper
2760
2831
        # access to disk resources now.
2761
 
        self.overrideEnv('BRZ_LOG', None)
 
2832
        self.overrideEnv('BZR_LOG', None)
2762
2833
 
2763
2834
    def check_file_contents(self, filename, expect):
2764
2835
        self.log("check contents of file %s" % filename)
2765
 
        with open(filename) as f:
 
2836
        f = file(filename)
 
2837
        try:
2766
2838
            contents = f.read()
 
2839
        finally:
 
2840
            f.close()
2767
2841
        if contents != expect:
2768
2842
            self.log("expected: %r" % expect)
2769
2843
            self.log("actually: %r" % contents)
2810
2884
        os.mkdir(self.test_dir)
2811
2885
        os.chdir(self.test_dir)
2812
2886
        # put name of test inside
2813
 
        with open(self.test_base_dir + '/name', 'w') as f:
 
2887
        f = file(self.test_base_dir + '/name', 'w')
 
2888
        try:
2814
2889
            f.write(self.id())
 
2890
        finally:
 
2891
            f.close()
2815
2892
 
2816
2893
    def deleteTestDir(self):
2817
2894
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2842
2919
        if transport is None or transport.is_readonly():
2843
2920
            transport = _mod_transport.get_transport_from_path(".")
2844
2921
        for name in shape:
2845
 
            self.assertIsInstance(name, (str, text_type))
 
2922
            self.assertIsInstance(name, basestring)
2846
2923
            if name[-1] == '/':
2847
2924
                transport.mkdir(urlutils.escape(name[:-1]))
2848
2925
            else:
2849
2926
                if line_endings == 'binary':
2850
 
                    end = b'\n'
 
2927
                    end = '\n'
2851
2928
                elif line_endings == 'native':
2852
 
                    end = os.linesep.encode('ascii')
 
2929
                    end = os.linesep
2853
2930
                else:
2854
2931
                    raise errors.BzrError(
2855
2932
                        'Invalid line ending request %r' % line_endings)
2856
 
                content = b"contents of %s%s" % (name.encode('utf-8'), end)
 
2933
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2857
2934
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2858
2935
 
2859
2936
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2862
2939
        """Assert whether path or paths are in the WorkingTree"""
2863
2940
        if tree is None:
2864
2941
            tree = workingtree.WorkingTree.open(root_path)
2865
 
        if not isinstance(path, (str, text_type)):
 
2942
        if not isinstance(path, basestring):
2866
2943
            for p in path:
2867
2944
                self.assertInWorkingTree(p, tree=tree)
2868
2945
        else:
2869
 
            self.assertTrue(tree.is_versioned(path),
 
2946
            self.assertIsNot(tree.path2id(path), None,
2870
2947
                path+' not in working tree.')
2871
2948
 
2872
2949
    def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2873
2950
        """Assert whether path or paths are not in the WorkingTree"""
2874
2951
        if tree is None:
2875
2952
            tree = workingtree.WorkingTree.open(root_path)
2876
 
        if not isinstance(path, (str, text_type)):
 
2953
        if not isinstance(path, basestring):
2877
2954
            for p in path:
2878
 
                self.assertNotInWorkingTree(p, tree=tree)
 
2955
                self.assertNotInWorkingTree(p,tree=tree)
2879
2956
        else:
2880
 
            self.assertFalse(tree.is_versioned(path), path+' in working tree.')
 
2957
            self.assertIs(tree.path2id(path), None, path+' in working tree.')
2881
2958
 
2882
2959
 
2883
2960
class TestCaseWithTransport(TestCaseInTempDir):
2941
3018
            return b.create_checkout(relpath, lightweight=True)
2942
3019
        b = self.make_branch(relpath, format=format)
2943
3020
        try:
2944
 
            return b.controldir.create_workingtree()
 
3021
            return b.bzrdir.create_workingtree()
2945
3022
        except errors.NotLocalUrl:
2946
3023
            # We can only make working trees locally at the moment.  If the
2947
3024
            # transport can't support them, then we keep the non-disk-backed
2992
3069
        There is no point in forcing them to duplicate the extension related
2993
3070
        warning.
2994
3071
        """
2995
 
        config.GlobalConfig().set_user_option(
2996
 
            'suppress_warnings', 'missing_extensions')
 
3072
        config.GlobalStack().set('ignore_missing_extensions', True)
2997
3073
 
2998
3074
 
2999
3075
class ChrootedTestCase(TestCaseWithTransport):
3009
3085
    """
3010
3086
 
3011
3087
    def setUp(self):
3012
 
        from breezy.tests import http_server
 
3088
        from bzrlib.tests import http_server
3013
3089
        super(ChrootedTestCase, self).setUp()
3014
3090
        if not self.vfs_transport_factory == memory.MemoryServer:
3015
3091
            self.transport_readonly_server = http_server.HttpServer
3217
3293
              stream=None,
3218
3294
              result_decorators=None,
3219
3295
              ):
3220
 
    """Run a test suite for brz selftest.
 
3296
    """Run a test suite for bzr selftest.
3221
3297
 
3222
3298
    :param runner_class: The class of runner to use. Must support the
3223
3299
        constructor arguments passed by run_suite which are more than standard
3267
3343
        # to take effect, though that is of marginal benefit.
3268
3344
        if verbosity >= 2:
3269
3345
            stream.write("Listing tests only ...\n")
3270
 
        if getattr(runner, 'list', None) is not None:
3271
 
            runner.list(suite)
3272
 
        else:
3273
 
            for t in iter_suite_tests(suite):
3274
 
                stream.write("%s\n" % (t.id()))
 
3346
        for t in iter_suite_tests(suite):
 
3347
            stream.write("%s\n" % (t.id()))
3275
3348
        return True
3276
3349
    result = runner.run(suite)
3277
3350
    if strict:
3324
3397
 
3325
3398
def random_order(random_seed, runner):
3326
3399
    """Return a test suite decorator factory for randomising tests order.
3327
 
 
3328
 
    :param random_seed: now, a string which casts to an integer, or an integer.
 
3400
    
 
3401
    :param random_seed: now, a string which casts to a long, or a long.
3329
3402
    :param runner: A test runner with a stream attribute to report on.
3330
3403
    """
3331
3404
    if random_seed is None:
3403
3476
    @staticmethod
3404
3477
    def actual_seed(seed):
3405
3478
        if seed == "now":
3406
 
            # We convert the seed to an integer to make it reuseable across
 
3479
            # We convert the seed to a long to make it reuseable across
3407
3480
            # invocations (because the user can reenter it).
3408
 
            return int(time.time())
 
3481
            return long(time.time())
3409
3482
        else:
3410
 
            # Convert the seed to an integer if we can
 
3483
            # Convert the seed to a long if we can
3411
3484
            try:
3412
 
                return int(seed)
 
3485
                return long(seed)
3413
3486
            except (TypeError, ValueError):
3414
3487
                pass
3415
3488
        return seed
3432
3505
    # than the fastest.
3433
3506
    partitions = [list() for i in range(count)]
3434
3507
    tests = iter_suite_tests(suite)
3435
 
    for partition, test in zip(itertools.cycle(partitions), tests):
 
3508
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
3436
3509
        partition.append(test)
3437
3510
    return partitions
3438
3511
 
3494
3567
                # child actually gets keystrokes for pdb etc).
3495
3568
                sys.stdin.close()
3496
3569
                subunit_result = AutoTimingTestResultDecorator(
3497
 
                    SubUnitBzrProtocolClientv1(stream))
 
3570
                    SubUnitBzrProtocolClient(stream))
3498
3571
                process_suite.run(subunit_result)
3499
3572
            except:
3500
3573
                # Try and report traceback on stream, but exit with error even
3540
3613
    test_blocks = partition_tests(suite, concurrency)
3541
3614
    for process_tests in test_blocks:
3542
3615
        # ugly; currently reimplement rather than reuses TestCase methods.
3543
 
        bzr_path = os.path.dirname(os.path.dirname(breezy.__file__))+'/bzr'
 
3616
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
3544
3617
        if not os.path.isfile(bzr_path):
3545
3618
            # We are probably installed. Assume sys.argv is the right file
3546
3619
            bzr_path = sys.argv[0]
3585
3658
    """
3586
3659
 
3587
3660
    def startTest(self, test):
3588
 
        self.profiler = breezy.lsprof.BzrProfiler()
 
3661
        self.profiler = bzrlib.lsprof.BzrProfiler()
3589
3662
        # Prevent deadlocks in tests that use lsprof: those tests will
3590
3663
        # unavoidably fail.
3591
 
        breezy.lsprof.BzrProfiler.profiler_block = 0
 
3664
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3592
3665
        self.profiler.start()
3593
3666
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3594
3667
 
3607
3680
        self.profiler = None
3608
3681
 
3609
3682
 
3610
 
# Controlled by "brz selftest -E=..." option
 
3683
# Controlled by "bzr selftest -E=..." option
3611
3684
# Currently supported:
3612
3685
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
3613
3686
#                           preserves any flags supplied at the command line.
3645
3718
    # XXX: Very ugly way to do this...
3646
3719
    # Disable warning about old formats because we don't want it to disturb
3647
3720
    # any blackbox tests.
3648
 
    from breezy import repository
 
3721
    from bzrlib import repository
3649
3722
    repository._deprecation_warning_done = True
3650
3723
 
3651
3724
    global default_transport
3665
3738
        if starting_with:
3666
3739
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
3667
3740
                             for start in starting_with]
3668
 
            # Always consider 'unittest' an interesting name so that failed
3669
 
            # suites wrapped as test cases appear in the output.
3670
 
            starting_with.append('unittest')
3671
3741
        if test_suite_factory is None:
3672
3742
            # Reduce loading time by loading modules based on the starting_with
3673
3743
            # patterns.
3711
3781
    test_list = []
3712
3782
    try:
3713
3783
        ftest = open(file_name, 'rt')
3714
 
    except IOError as e:
 
3784
    except IOError, e:
3715
3785
        if e.errno != errno.ENOENT:
3716
3786
            raise
3717
3787
        else:
3796
3866
 
3797
3867
    def refers_to(self, module_name):
3798
3868
        """Is there tests for the module or one of its sub modules."""
3799
 
        return module_name in self.modules
 
3869
        return self.modules.has_key(module_name)
3800
3870
 
3801
3871
    def includes(self, test_id):
3802
 
        return test_id in self.tests
 
3872
        return self.tests.has_key(test_id)
3803
3873
 
3804
3874
 
3805
3875
class TestPrefixAliasRegistry(registry.Registry):
3845
3915
 
3846
3916
 
3847
3917
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3848
 
# appear prefixed ('breezy.' is "replaced" by 'breezy.').
3849
 
test_prefix_alias_registry.register('breezy', 'breezy')
 
3918
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
 
3919
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3850
3920
 
3851
3921
# Obvious highest levels prefixes, feel free to add your own via a plugin
3852
 
test_prefix_alias_registry.register('bd', 'breezy.doc')
3853
 
test_prefix_alias_registry.register('bu', 'breezy.utils')
3854
 
test_prefix_alias_registry.register('bt', 'breezy.tests')
3855
 
test_prefix_alias_registry.register('bb', 'breezy.tests.blackbox')
3856
 
test_prefix_alias_registry.register('bp', 'breezy.plugins')
 
3922
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
 
3923
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
 
3924
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
 
3925
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
 
3926
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3857
3927
 
3858
3928
 
3859
3929
def _test_suite_testmod_names():
3860
3930
    """Return the standard list of test module names to test."""
3861
3931
    return [
3862
 
        'breezy.doc',
3863
 
        'breezy.tests.blackbox',
3864
 
        'breezy.tests.commands',
3865
 
        'breezy.tests.per_branch',
3866
 
        'breezy.tests.per_bzrdir',
3867
 
        'breezy.tests.per_controldir',
3868
 
        'breezy.tests.per_controldir_colo',
3869
 
        'breezy.tests.per_foreign_vcs',
3870
 
        'breezy.tests.per_interrepository',
3871
 
        'breezy.tests.per_intertree',
3872
 
        'breezy.tests.per_inventory',
3873
 
        'breezy.tests.per_interbranch',
3874
 
        'breezy.tests.per_lock',
3875
 
        'breezy.tests.per_merger',
3876
 
        'breezy.tests.per_transport',
3877
 
        'breezy.tests.per_tree',
3878
 
        'breezy.tests.per_pack_repository',
3879
 
        'breezy.tests.per_repository',
3880
 
        'breezy.tests.per_repository_chk',
3881
 
        'breezy.tests.per_repository_reference',
3882
 
        'breezy.tests.per_repository_vf',
3883
 
        'breezy.tests.per_uifactory',
3884
 
        'breezy.tests.per_versionedfile',
3885
 
        'breezy.tests.per_workingtree',
3886
 
        'breezy.tests.test__annotator',
3887
 
        'breezy.tests.test__bencode',
3888
 
        'breezy.tests.test__btree_serializer',
3889
 
        'breezy.tests.test__chk_map',
3890
 
        'breezy.tests.test__dirstate_helpers',
3891
 
        'breezy.tests.test__groupcompress',
3892
 
        'breezy.tests.test__known_graph',
3893
 
        'breezy.tests.test__rio',
3894
 
        'breezy.tests.test__simple_set',
3895
 
        'breezy.tests.test__static_tuple',
3896
 
        'breezy.tests.test__walkdirs_win32',
3897
 
        'breezy.tests.test_ancestry',
3898
 
        'breezy.tests.test_annotate',
3899
 
        'breezy.tests.test_atomicfile',
3900
 
        'breezy.tests.test_bad_files',
3901
 
        'breezy.tests.test_bisect',
3902
 
        'breezy.tests.test_bisect_multi',
3903
 
        'breezy.tests.test_branch',
3904
 
        'breezy.tests.test_branchbuilder',
3905
 
        'breezy.tests.test_btree_index',
3906
 
        'breezy.tests.test_bugtracker',
3907
 
        'breezy.tests.test_bundle',
3908
 
        'breezy.tests.test_bzrdir',
3909
 
        'breezy.tests.test__chunks_to_lines',
3910
 
        'breezy.tests.test_cache_utf8',
3911
 
        'breezy.tests.test_chk_map',
3912
 
        'breezy.tests.test_chk_serializer',
3913
 
        'breezy.tests.test_chunk_writer',
3914
 
        'breezy.tests.test_clean_tree',
3915
 
        'breezy.tests.test_cleanup',
3916
 
        'breezy.tests.test_cmdline',
3917
 
        'breezy.tests.test_commands',
3918
 
        'breezy.tests.test_commit',
3919
 
        'breezy.tests.test_commit_merge',
3920
 
        'breezy.tests.test_config',
3921
 
        'breezy.tests.test_conflicts',
3922
 
        'breezy.tests.test_controldir',
3923
 
        'breezy.tests.test_counted_lock',
3924
 
        'breezy.tests.test_crash',
3925
 
        'breezy.tests.test_decorators',
3926
 
        'breezy.tests.test_delta',
3927
 
        'breezy.tests.test_debug',
3928
 
        'breezy.tests.test_diff',
3929
 
        'breezy.tests.test_directory_service',
3930
 
        'breezy.tests.test_dirstate',
3931
 
        'breezy.tests.test_email_message',
3932
 
        'breezy.tests.test_eol_filters',
3933
 
        'breezy.tests.test_errors',
3934
 
        'breezy.tests.test_estimate_compressed_size',
3935
 
        'breezy.tests.test_export',
3936
 
        'breezy.tests.test_export_pot',
3937
 
        'breezy.tests.test_extract',
3938
 
        'breezy.tests.test_features',
3939
 
        'breezy.tests.test_fetch',
3940
 
        'breezy.tests.test_fetch_ghosts',
3941
 
        'breezy.tests.test_fixtures',
3942
 
        'breezy.tests.test_fifo_cache',
3943
 
        'breezy.tests.test_filters',
3944
 
        'breezy.tests.test_filter_tree',
3945
 
        'breezy.tests.test_ftp_transport',
3946
 
        'breezy.tests.test_foreign',
3947
 
        'breezy.tests.test_generate_docs',
3948
 
        'breezy.tests.test_generate_ids',
3949
 
        'breezy.tests.test_globbing',
3950
 
        'breezy.tests.test_gpg',
3951
 
        'breezy.tests.test_graph',
3952
 
        'breezy.tests.test_groupcompress',
3953
 
        'breezy.tests.test_hashcache',
3954
 
        'breezy.tests.test_help',
3955
 
        'breezy.tests.test_hooks',
3956
 
        'breezy.tests.test_http',
3957
 
        'breezy.tests.test_http_response',
3958
 
        'breezy.tests.test_https_ca_bundle',
3959
 
        'breezy.tests.test_https_urllib',
3960
 
        'breezy.tests.test_i18n',
3961
 
        'breezy.tests.test_identitymap',
3962
 
        'breezy.tests.test_ignores',
3963
 
        'breezy.tests.test_index',
3964
 
        'breezy.tests.test_import_tariff',
3965
 
        'breezy.tests.test_info',
3966
 
        'breezy.tests.test_inv',
3967
 
        'breezy.tests.test_inventory_delta',
3968
 
        'breezy.tests.test_knit',
3969
 
        'breezy.tests.test_lazy_import',
3970
 
        'breezy.tests.test_lazy_regex',
3971
 
        'breezy.tests.test_library_state',
3972
 
        'breezy.tests.test_lock',
3973
 
        'breezy.tests.test_lockable_files',
3974
 
        'breezy.tests.test_lockdir',
3975
 
        'breezy.tests.test_log',
3976
 
        'breezy.tests.test_lru_cache',
3977
 
        'breezy.tests.test_lsprof',
3978
 
        'breezy.tests.test_mail_client',
3979
 
        'breezy.tests.test_matchers',
3980
 
        'breezy.tests.test_memorytree',
3981
 
        'breezy.tests.test_merge',
3982
 
        'breezy.tests.test_merge3',
3983
 
        'breezy.tests.test_merge_core',
3984
 
        'breezy.tests.test_merge_directive',
3985
 
        'breezy.tests.test_mergetools',
3986
 
        'breezy.tests.test_missing',
3987
 
        'breezy.tests.test_msgeditor',
3988
 
        'breezy.tests.test_multiparent',
3989
 
        'breezy.tests.test_mutabletree',
3990
 
        'breezy.tests.test_nonascii',
3991
 
        'breezy.tests.test_options',
3992
 
        'breezy.tests.test_osutils',
3993
 
        'breezy.tests.test_osutils_encodings',
3994
 
        'breezy.tests.test_pack',
3995
 
        'breezy.tests.test_patch',
3996
 
        'breezy.tests.test_patches',
3997
 
        'breezy.tests.test_permissions',
3998
 
        'breezy.tests.test_plugins',
3999
 
        'breezy.tests.test_progress',
4000
 
        'breezy.tests.test_pyutils',
4001
 
        'breezy.tests.test_read_bundle',
4002
 
        'breezy.tests.test_reconcile',
4003
 
        'breezy.tests.test_reconfigure',
4004
 
        'breezy.tests.test_registry',
4005
 
        'breezy.tests.test_remote',
4006
 
        'breezy.tests.test_rename_map',
4007
 
        'breezy.tests.test_repository',
4008
 
        'breezy.tests.test_revert',
4009
 
        'breezy.tests.test_revision',
4010
 
        'breezy.tests.test_revisionspec',
4011
 
        'breezy.tests.test_revisiontree',
4012
 
        'breezy.tests.test_rio',
4013
 
        'breezy.tests.test_rules',
4014
 
        'breezy.tests.test_url_policy_open',
4015
 
        'breezy.tests.test_sampler',
4016
 
        'breezy.tests.test_scenarios',
4017
 
        'breezy.tests.test_script',
4018
 
        'breezy.tests.test_selftest',
4019
 
        'breezy.tests.test_serializer',
4020
 
        'breezy.tests.test_setup',
4021
 
        'breezy.tests.test_sftp_transport',
4022
 
        'breezy.tests.test_shelf',
4023
 
        'breezy.tests.test_shelf_ui',
4024
 
        'breezy.tests.test_smart',
4025
 
        'breezy.tests.test_smart_add',
4026
 
        'breezy.tests.test_smart_request',
4027
 
        'breezy.tests.test_smart_signals',
4028
 
        'breezy.tests.test_smart_transport',
4029
 
        'breezy.tests.test_smtp_connection',
4030
 
        'breezy.tests.test_source',
4031
 
        'breezy.tests.test_ssh_transport',
4032
 
        'breezy.tests.test_status',
4033
 
        'breezy.tests.test_strace',
4034
 
        'breezy.tests.test_subsume',
4035
 
        'breezy.tests.test_switch',
4036
 
        'breezy.tests.test_symbol_versioning',
4037
 
        'breezy.tests.test_tag',
4038
 
        'breezy.tests.test_test_server',
4039
 
        'breezy.tests.test_testament',
4040
 
        'breezy.tests.test_textfile',
4041
 
        'breezy.tests.test_textmerge',
4042
 
        'breezy.tests.test_cethread',
4043
 
        'breezy.tests.test_timestamp',
4044
 
        'breezy.tests.test_trace',
4045
 
        'breezy.tests.test_transactions',
4046
 
        'breezy.tests.test_transform',
4047
 
        'breezy.tests.test_transport',
4048
 
        'breezy.tests.test_transport_log',
4049
 
        'breezy.tests.test_tree',
4050
 
        'breezy.tests.test_treebuilder',
4051
 
        'breezy.tests.test_treeshape',
4052
 
        'breezy.tests.test_tsort',
4053
 
        'breezy.tests.test_tuned_gzip',
4054
 
        'breezy.tests.test_ui',
4055
 
        'breezy.tests.test_uncommit',
4056
 
        'breezy.tests.test_upgrade',
4057
 
        'breezy.tests.test_upgrade_stacked',
4058
 
        'breezy.tests.test_upstream_import',
4059
 
        'breezy.tests.test_urlutils',
4060
 
        'breezy.tests.test_utextwrap',
4061
 
        'breezy.tests.test_version',
4062
 
        'breezy.tests.test_version_info',
4063
 
        'breezy.tests.test_versionedfile',
4064
 
        'breezy.tests.test_vf_search',
4065
 
        'breezy.tests.test_views',
4066
 
        'breezy.tests.test_weave',
4067
 
        'breezy.tests.test_whitebox',
4068
 
        'breezy.tests.test_win32utils',
4069
 
        'breezy.tests.test_workingtree',
4070
 
        'breezy.tests.test_workingtree_4',
4071
 
        'breezy.tests.test_wsgi',
4072
 
        'breezy.tests.test_xml',
 
3932
        'bzrlib.doc',
 
3933
        'bzrlib.tests.blackbox',
 
3934
        'bzrlib.tests.commands',
 
3935
        'bzrlib.tests.per_branch',
 
3936
        'bzrlib.tests.per_bzrdir',
 
3937
        'bzrlib.tests.per_controldir',
 
3938
        'bzrlib.tests.per_controldir_colo',
 
3939
        'bzrlib.tests.per_foreign_vcs',
 
3940
        'bzrlib.tests.per_interrepository',
 
3941
        'bzrlib.tests.per_intertree',
 
3942
        'bzrlib.tests.per_inventory',
 
3943
        'bzrlib.tests.per_interbranch',
 
3944
        'bzrlib.tests.per_lock',
 
3945
        'bzrlib.tests.per_merger',
 
3946
        'bzrlib.tests.per_transport',
 
3947
        'bzrlib.tests.per_tree',
 
3948
        'bzrlib.tests.per_pack_repository',
 
3949
        'bzrlib.tests.per_repository',
 
3950
        'bzrlib.tests.per_repository_chk',
 
3951
        'bzrlib.tests.per_repository_reference',
 
3952
        'bzrlib.tests.per_repository_vf',
 
3953
        'bzrlib.tests.per_uifactory',
 
3954
        'bzrlib.tests.per_versionedfile',
 
3955
        'bzrlib.tests.per_workingtree',
 
3956
        'bzrlib.tests.test__annotator',
 
3957
        'bzrlib.tests.test__bencode',
 
3958
        'bzrlib.tests.test__btree_serializer',
 
3959
        'bzrlib.tests.test__chk_map',
 
3960
        'bzrlib.tests.test__dirstate_helpers',
 
3961
        'bzrlib.tests.test__groupcompress',
 
3962
        'bzrlib.tests.test__known_graph',
 
3963
        'bzrlib.tests.test__rio',
 
3964
        'bzrlib.tests.test__simple_set',
 
3965
        'bzrlib.tests.test__static_tuple',
 
3966
        'bzrlib.tests.test__walkdirs_win32',
 
3967
        'bzrlib.tests.test_ancestry',
 
3968
        'bzrlib.tests.test_annotate',
 
3969
        'bzrlib.tests.test_api',
 
3970
        'bzrlib.tests.test_atomicfile',
 
3971
        'bzrlib.tests.test_bad_files',
 
3972
        'bzrlib.tests.test_bisect_multi',
 
3973
        'bzrlib.tests.test_branch',
 
3974
        'bzrlib.tests.test_branchbuilder',
 
3975
        'bzrlib.tests.test_btree_index',
 
3976
        'bzrlib.tests.test_bugtracker',
 
3977
        'bzrlib.tests.test_bundle',
 
3978
        'bzrlib.tests.test_bzrdir',
 
3979
        'bzrlib.tests.test__chunks_to_lines',
 
3980
        'bzrlib.tests.test_cache_utf8',
 
3981
        'bzrlib.tests.test_chk_map',
 
3982
        'bzrlib.tests.test_chk_serializer',
 
3983
        'bzrlib.tests.test_chunk_writer',
 
3984
        'bzrlib.tests.test_clean_tree',
 
3985
        'bzrlib.tests.test_cleanup',
 
3986
        'bzrlib.tests.test_cmdline',
 
3987
        'bzrlib.tests.test_commands',
 
3988
        'bzrlib.tests.test_commit',
 
3989
        'bzrlib.tests.test_commit_merge',
 
3990
        'bzrlib.tests.test_config',
 
3991
        'bzrlib.tests.test_conflicts',
 
3992
        'bzrlib.tests.test_controldir',
 
3993
        'bzrlib.tests.test_counted_lock',
 
3994
        'bzrlib.tests.test_crash',
 
3995
        'bzrlib.tests.test_decorators',
 
3996
        'bzrlib.tests.test_delta',
 
3997
        'bzrlib.tests.test_debug',
 
3998
        'bzrlib.tests.test_diff',
 
3999
        'bzrlib.tests.test_directory_service',
 
4000
        'bzrlib.tests.test_dirstate',
 
4001
        'bzrlib.tests.test_email_message',
 
4002
        'bzrlib.tests.test_eol_filters',
 
4003
        'bzrlib.tests.test_errors',
 
4004
        'bzrlib.tests.test_estimate_compressed_size',
 
4005
        'bzrlib.tests.test_export',
 
4006
        'bzrlib.tests.test_export_pot',
 
4007
        'bzrlib.tests.test_extract',
 
4008
        'bzrlib.tests.test_features',
 
4009
        'bzrlib.tests.test_fetch',
 
4010
        'bzrlib.tests.test_fixtures',
 
4011
        'bzrlib.tests.test_fifo_cache',
 
4012
        'bzrlib.tests.test_filters',
 
4013
        'bzrlib.tests.test_filter_tree',
 
4014
        'bzrlib.tests.test_ftp_transport',
 
4015
        'bzrlib.tests.test_foreign',
 
4016
        'bzrlib.tests.test_generate_docs',
 
4017
        'bzrlib.tests.test_generate_ids',
 
4018
        'bzrlib.tests.test_globbing',
 
4019
        'bzrlib.tests.test_gpg',
 
4020
        'bzrlib.tests.test_graph',
 
4021
        'bzrlib.tests.test_groupcompress',
 
4022
        'bzrlib.tests.test_hashcache',
 
4023
        'bzrlib.tests.test_help',
 
4024
        'bzrlib.tests.test_hooks',
 
4025
        'bzrlib.tests.test_http',
 
4026
        'bzrlib.tests.test_http_response',
 
4027
        'bzrlib.tests.test_https_ca_bundle',
 
4028
        'bzrlib.tests.test_https_urllib',
 
4029
        'bzrlib.tests.test_i18n',
 
4030
        'bzrlib.tests.test_identitymap',
 
4031
        'bzrlib.tests.test_ignores',
 
4032
        'bzrlib.tests.test_index',
 
4033
        'bzrlib.tests.test_import_tariff',
 
4034
        'bzrlib.tests.test_info',
 
4035
        'bzrlib.tests.test_inv',
 
4036
        'bzrlib.tests.test_inventory_delta',
 
4037
        'bzrlib.tests.test_knit',
 
4038
        'bzrlib.tests.test_lazy_import',
 
4039
        'bzrlib.tests.test_lazy_regex',
 
4040
        'bzrlib.tests.test_library_state',
 
4041
        'bzrlib.tests.test_lock',
 
4042
        'bzrlib.tests.test_lockable_files',
 
4043
        'bzrlib.tests.test_lockdir',
 
4044
        'bzrlib.tests.test_log',
 
4045
        'bzrlib.tests.test_lru_cache',
 
4046
        'bzrlib.tests.test_lsprof',
 
4047
        'bzrlib.tests.test_mail_client',
 
4048
        'bzrlib.tests.test_matchers',
 
4049
        'bzrlib.tests.test_memorytree',
 
4050
        'bzrlib.tests.test_merge',
 
4051
        'bzrlib.tests.test_merge3',
 
4052
        'bzrlib.tests.test_merge_core',
 
4053
        'bzrlib.tests.test_merge_directive',
 
4054
        'bzrlib.tests.test_mergetools',
 
4055
        'bzrlib.tests.test_missing',
 
4056
        'bzrlib.tests.test_msgeditor',
 
4057
        'bzrlib.tests.test_multiparent',
 
4058
        'bzrlib.tests.test_mutabletree',
 
4059
        'bzrlib.tests.test_nonascii',
 
4060
        'bzrlib.tests.test_options',
 
4061
        'bzrlib.tests.test_osutils',
 
4062
        'bzrlib.tests.test_osutils_encodings',
 
4063
        'bzrlib.tests.test_pack',
 
4064
        'bzrlib.tests.test_patch',
 
4065
        'bzrlib.tests.test_patches',
 
4066
        'bzrlib.tests.test_permissions',
 
4067
        'bzrlib.tests.test_plugins',
 
4068
        'bzrlib.tests.test_progress',
 
4069
        'bzrlib.tests.test_pyutils',
 
4070
        'bzrlib.tests.test_read_bundle',
 
4071
        'bzrlib.tests.test_reconcile',
 
4072
        'bzrlib.tests.test_reconfigure',
 
4073
        'bzrlib.tests.test_registry',
 
4074
        'bzrlib.tests.test_remote',
 
4075
        'bzrlib.tests.test_rename_map',
 
4076
        'bzrlib.tests.test_repository',
 
4077
        'bzrlib.tests.test_revert',
 
4078
        'bzrlib.tests.test_revision',
 
4079
        'bzrlib.tests.test_revisionspec',
 
4080
        'bzrlib.tests.test_revisiontree',
 
4081
        'bzrlib.tests.test_rio',
 
4082
        'bzrlib.tests.test_rules',
 
4083
        'bzrlib.tests.test_url_policy_open',
 
4084
        'bzrlib.tests.test_sampler',
 
4085
        'bzrlib.tests.test_scenarios',
 
4086
        'bzrlib.tests.test_script',
 
4087
        'bzrlib.tests.test_selftest',
 
4088
        'bzrlib.tests.test_serializer',
 
4089
        'bzrlib.tests.test_setup',
 
4090
        'bzrlib.tests.test_sftp_transport',
 
4091
        'bzrlib.tests.test_shelf',
 
4092
        'bzrlib.tests.test_shelf_ui',
 
4093
        'bzrlib.tests.test_smart',
 
4094
        'bzrlib.tests.test_smart_add',
 
4095
        'bzrlib.tests.test_smart_request',
 
4096
        'bzrlib.tests.test_smart_signals',
 
4097
        'bzrlib.tests.test_smart_transport',
 
4098
        'bzrlib.tests.test_smtp_connection',
 
4099
        'bzrlib.tests.test_source',
 
4100
        'bzrlib.tests.test_ssh_transport',
 
4101
        'bzrlib.tests.test_status',
 
4102
        'bzrlib.tests.test_store',
 
4103
        'bzrlib.tests.test_strace',
 
4104
        'bzrlib.tests.test_subsume',
 
4105
        'bzrlib.tests.test_switch',
 
4106
        'bzrlib.tests.test_symbol_versioning',
 
4107
        'bzrlib.tests.test_tag',
 
4108
        'bzrlib.tests.test_test_server',
 
4109
        'bzrlib.tests.test_testament',
 
4110
        'bzrlib.tests.test_textfile',
 
4111
        'bzrlib.tests.test_textmerge',
 
4112
        'bzrlib.tests.test_cethread',
 
4113
        'bzrlib.tests.test_timestamp',
 
4114
        'bzrlib.tests.test_trace',
 
4115
        'bzrlib.tests.test_transactions',
 
4116
        'bzrlib.tests.test_transform',
 
4117
        'bzrlib.tests.test_transport',
 
4118
        'bzrlib.tests.test_transport_log',
 
4119
        'bzrlib.tests.test_tree',
 
4120
        'bzrlib.tests.test_treebuilder',
 
4121
        'bzrlib.tests.test_treeshape',
 
4122
        'bzrlib.tests.test_tsort',
 
4123
        'bzrlib.tests.test_tuned_gzip',
 
4124
        'bzrlib.tests.test_ui',
 
4125
        'bzrlib.tests.test_uncommit',
 
4126
        'bzrlib.tests.test_upgrade',
 
4127
        'bzrlib.tests.test_upgrade_stacked',
 
4128
        'bzrlib.tests.test_urlutils',
 
4129
        'bzrlib.tests.test_utextwrap',
 
4130
        'bzrlib.tests.test_version',
 
4131
        'bzrlib.tests.test_version_info',
 
4132
        'bzrlib.tests.test_versionedfile',
 
4133
        'bzrlib.tests.test_vf_search',
 
4134
        'bzrlib.tests.test_weave',
 
4135
        'bzrlib.tests.test_whitebox',
 
4136
        'bzrlib.tests.test_win32utils',
 
4137
        'bzrlib.tests.test_workingtree',
 
4138
        'bzrlib.tests.test_workingtree_4',
 
4139
        'bzrlib.tests.test_wsgi',
 
4140
        'bzrlib.tests.test_xml',
4073
4141
        ]
4074
4142
 
4075
4143
 
4079
4147
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
4080
4148
        return []
4081
4149
    return [
4082
 
        'breezy',
4083
 
        'breezy.branchbuilder',
4084
 
        'breezy.bzr.inventory',
4085
 
        'breezy.decorators',
4086
 
        'breezy.iterablefile',
4087
 
        'breezy.lockdir',
4088
 
        'breezy.merge3',
4089
 
        'breezy.option',
4090
 
        'breezy.pyutils',
4091
 
        'breezy.symbol_versioning',
4092
 
        'breezy.tests',
4093
 
        'breezy.tests.fixtures',
4094
 
        'breezy.timestamp',
4095
 
        'breezy.transport.http',
4096
 
        'breezy.version_info_formats.format_custom',
 
4150
        'bzrlib',
 
4151
        'bzrlib.branchbuilder',
 
4152
        'bzrlib.decorators',
 
4153
        'bzrlib.inventory',
 
4154
        'bzrlib.iterablefile',
 
4155
        'bzrlib.lockdir',
 
4156
        'bzrlib.merge3',
 
4157
        'bzrlib.option',
 
4158
        'bzrlib.pyutils',
 
4159
        'bzrlib.symbol_versioning',
 
4160
        'bzrlib.tests',
 
4161
        'bzrlib.tests.fixtures',
 
4162
        'bzrlib.timestamp',
 
4163
        'bzrlib.transport.http',
 
4164
        'bzrlib.version_info_formats.format_custom',
4097
4165
        ]
4098
4166
 
4099
4167
 
4100
4168
def test_suite(keep_only=None, starting_with=None):
4101
 
    """Build and return TestSuite for the whole of breezy.
 
4169
    """Build and return TestSuite for the whole of bzrlib.
4102
4170
 
4103
4171
    :param keep_only: A list of test ids limiting the suite returned.
4104
4172
 
4153
4221
            # still runs the rest of the examples
4154
4222
            doc_suite = IsolatedDocTestSuite(
4155
4223
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
4156
 
        except ValueError as e:
4157
 
            print('**failed to get doctest for: %s\n%s' % (mod, e))
 
4224
        except ValueError, e:
 
4225
            print '**failed to get doctest for: %s\n%s' % (mod, e)
4158
4226
            raise
4159
4227
        if len(doc_suite._tests) == 0:
4160
4228
            raise errors.BzrError("no doctests found in %s" % (mod,))
4206
4274
 
4207
4275
    It is safe to pass scenario generators or iterators.
4208
4276
 
4209
 
    :returns: A list of compound scenarios: the cross-product of all
 
4277
    :returns: A list of compound scenarios: the cross-product of all 
4210
4278
        scenarios, with the names concatenated and the parameters
4211
4279
        merged together.
4212
4280
    """
4213
 
    return functools.reduce(_multiply_two_scenarios, map(list, scenarios))
 
4281
    return reduce(_multiply_two_scenarios, map(list, scenarios))
4214
4282
 
4215
4283
 
4216
4284
def _multiply_two_scenarios(scenarios_left, scenarios_right):
4222
4290
    """
4223
4291
    return [
4224
4292
        ('%s,%s' % (left_name, right_name),
4225
 
         dict(left_dict, **right_dict))
 
4293
         dict(left_dict.items() + right_dict.items()))
4226
4294
        for left_name, left_dict in scenarios_left
4227
4295
        for right_name, right_dict in scenarios_right]
4228
4296
 
4245
4313
    the scenario name at the end of its id(), and updating the test object's
4246
4314
    __dict__ with the scenario_param_dict.
4247
4315
 
4248
 
    >>> import breezy.tests.test_sampler
 
4316
    >>> import bzrlib.tests.test_sampler
4249
4317
    >>> r = multiply_tests(
4250
 
    ...     breezy.tests.test_sampler.DemoTest('test_nothing'),
 
4318
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
4251
4319
    ...     [('one', dict(param=1)),
4252
4320
    ...      ('two', dict(param=2))],
4253
4321
    ...     TestUtil.TestSuite())
4255
4323
    >>> len(tests)
4256
4324
    2
4257
4325
    >>> tests[0].id()
4258
 
    'breezy.tests.test_sampler.DemoTest.test_nothing(one)'
 
4326
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
4259
4327
    >>> tests[0].param
4260
4328
    1
4261
4329
    >>> tests[1].param
4327
4395
    This is meant to be used inside a modules 'load_tests()' function. It will
4328
4396
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4329
4397
    against both implementations. Setting 'test.module' to the appropriate
4330
 
    module. See breezy.tests.test__chk_map.load_tests as an example.
 
4398
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
4331
4399
 
4332
4400
    :param standard_tests: A test suite to permute
4333
4401
    :param loader: A TestLoader
4334
4402
    :param py_module_name: The python path to a python module that can always
4335
4403
        be loaded, and will be considered the 'python' implementation. (eg
4336
 
        'breezy._chk_map_py')
 
4404
        'bzrlib._chk_map_py')
4337
4405
    :param ext_module_name: The python path to an extension module. If the
4338
4406
        module cannot be loaded, a single test will be added, which notes that
4339
4407
        the module is not available. If it can be loaded, all standard_tests
4343
4411
        the module is available.
4344
4412
    """
4345
4413
 
4346
 
    from .features import ModuleAvailableFeature
 
4414
    from bzrlib.tests.features import ModuleAvailableFeature
4347
4415
    py_module = pyutils.get_named_object(py_module_name)
4348
4416
    scenarios = [
4349
4417
        ('python', {'module': py_module}),
4369
4437
    # except on win32, where rmtree(str) will fail
4370
4438
    # since it doesn't have the property of byte-stream paths
4371
4439
    # (they are either ascii or mbcs)
4372
 
    if sys.platform == 'win32' and isinstance(dirname, bytes):
 
4440
    if sys.platform == 'win32':
4373
4441
        # make sure we are using the unicode win32 api
4374
 
        dirname = dirname.decode('mbcs')
 
4442
        dirname = unicode(dirname)
4375
4443
    else:
4376
4444
        dirname = dirname.encode(sys.getfilesystemencoding())
4377
4445
    try:
4378
4446
        osutils.rmtree(dirname)
4379
 
    except OSError as e:
 
4447
    except OSError, e:
4380
4448
        # We don't want to fail here because some useful display will be lost
4381
4449
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4382
4450
        # possible info to the test runner is even worse.
4414
4482
    Return None if all non-ascii characters is valid
4415
4483
    for given encoding.
4416
4484
    """
4417
 
    for i in range(128, 256):
 
4485
    for i in xrange(128, 256):
4418
4486
        char = chr(i)
4419
4487
        try:
4420
4488
            char.decode(encoding)
4427
4495
try:
4428
4496
    from subunit import TestProtocolClient
4429
4497
    from subunit.test_results import AutoTimingTestResultDecorator
4430
 
 
4431
 
    class SubUnitBzrProtocolClientv1(TestProtocolClient):
 
4498
    class SubUnitBzrProtocolClient(TestProtocolClient):
4432
4499
 
4433
4500
        def stopTest(self, test):
4434
 
            super(SubUnitBzrProtocolClientv1, self).stopTest(test)
 
4501
            super(SubUnitBzrProtocolClient, self).stopTest(test)
4435
4502
            _clear__type_equality_funcs(test)
4436
4503
 
4437
4504
        def addSuccess(self, test, details=None):
4439
4506
            # stream, but we don't want to include it in ours.
4440
4507
            if details is not None and 'log' in details:
4441
4508
                del details['log']
4442
 
            return super(SubUnitBzrProtocolClientv1, self).addSuccess(
 
4509
            return super(SubUnitBzrProtocolClient, self).addSuccess(
4443
4510
                test, details)
4444
4511
 
4445
 
    class SubUnitBzrRunnerv1(TextTestRunner):
4446
 
 
 
4512
    class SubUnitBzrRunner(TextTestRunner):
4447
4513
        def run(self, test):
4448
4514
            result = AutoTimingTestResultDecorator(
4449
 
                SubUnitBzrProtocolClientv1(self.stream))
 
4515
                SubUnitBzrProtocolClient(self.stream))
4450
4516
            test.run(result)
4451
4517
            return result
4452
4518
except ImportError:
4453
4519
    pass
4454
4520
 
4455
4521
 
4456
 
try:
4457
 
    from subunit.run import SubunitTestRunner
4458
 
 
4459
 
    class SubUnitBzrRunnerv2(TextTestRunner, SubunitTestRunner):
4460
 
 
4461
 
        def __init__(self, stream=sys.stderr, descriptions=0, verbosity=1,
4462
 
                     bench_history=None, strict=False, result_decorators=None):
4463
 
            TextTestRunner.__init__(
4464
 
                    self, stream=stream,
4465
 
                    descriptions=descriptions, verbosity=verbosity,
4466
 
                    bench_history=bench_history, strict=strict,
4467
 
                    result_decorators=result_decorators)
4468
 
            SubunitTestRunner.__init__(self, verbosity=verbosity,
4469
 
                                       stream=stream)
4470
 
 
4471
 
        run = SubunitTestRunner.run
4472
 
except ImportError:
4473
 
    pass
 
4522
# API compatibility for old plugins; see bug 892622.
 
4523
for name in [
 
4524
    'Feature',
 
4525
    'HTTPServerFeature', 
 
4526
    'ModuleAvailableFeature',
 
4527
    'HTTPSServerFeature', 'SymlinkFeature', 'HardlinkFeature',
 
4528
    'OsFifoFeature', 'UnicodeFilenameFeature',
 
4529
    'ByteStringNamedFilesystem', 'UTF8Filesystem',
 
4530
    'BreakinFeature', 'CaseInsCasePresFilenameFeature',
 
4531
    'CaseInsensitiveFilesystemFeature', 'case_sensitive_filesystem_feature',
 
4532
    'posix_permissions_feature',
 
4533
    ]:
 
4534
    globals()[name] = _CompatabilityThunkFeature(
 
4535
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4536
        'bzrlib.tests', name,
 
4537
        name, 'bzrlib.tests.features')
 
4538
 
 
4539
 
 
4540
for (old_name, new_name) in [
 
4541
    ('UnicodeFilename', 'UnicodeFilenameFeature'),
 
4542
    ]:
 
4543
    globals()[name] = _CompatabilityThunkFeature(
 
4544
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4545
        'bzrlib.tests', old_name,
 
4546
        new_name, 'bzrlib.tests.features')