~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Robert Collins
  • Date: 2007-07-02 05:26:25 UTC
  • mfrom: (2566 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2568.
  • Revision ID: robertc@robertcollins.net-20070702052625-motr7ljwhmqvw9rg
Merge with bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
37
37
from pprint import pformat
38
38
import random
39
39
import re
 
40
import shlex
40
41
import stat
41
42
from subprocess import Popen, PIPE
42
43
import sys
76
77
from bzrlib.revision import common_ancestor
77
78
import bzrlib.store
78
79
from bzrlib import symbol_versioning
 
80
from bzrlib.symbol_versioning import (
 
81
    deprecated_method,
 
82
    zero_eighteen,
 
83
    )
79
84
import bzrlib.trace
80
85
from bzrlib.transport import get_transport
81
86
import bzrlib.transport
747
752
        self._benchcalls = []
748
753
        self._benchtime = None
749
754
        self._clear_hooks()
 
755
        self._clear_debug_flags()
 
756
 
 
757
    def _clear_debug_flags(self):
 
758
        """Prevent externally set debug flags affecting tests.
 
759
        
 
760
        Tests that want to use debug flags can just set them in the
 
761
        debug_flags set during setup/teardown.
 
762
        """
 
763
        self._preserved_debug_flags = set(debug.debug_flags)
 
764
        debug.debug_flags.clear()
 
765
        self.addCleanup(self._restore_debug_flags)
750
766
 
751
767
    def _clear_hooks(self):
752
768
        # prevent hooks affecting tests
760
776
        # reset all hooks to an empty instance of the appropriate type
761
777
        bzrlib.branch.Branch.hooks = bzrlib.branch.BranchHooks()
762
778
        bzrlib.smart.server.SmartTCPServer.hooks = bzrlib.smart.server.SmartServerHooks()
763
 
        # FIXME: Rather than constructing new objects like this, how about
764
 
        # having save() and clear() methods on the base Hook class? mbp
765
 
        # 20070416
766
779
 
767
780
    def _silenceUI(self):
768
781
        """Turn off UI for duration of test"""
871
884
                excName = str(excClass)
872
885
            raise self.failureException, "%s not raised" % excName
873
886
 
874
 
    def assertRaises(self, excClass, func, *args, **kwargs):
 
887
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
875
888
        """Assert that a callable raises a particular exception.
876
889
 
877
890
        :param excClass: As for the except statement, this may be either an
878
 
        exception class, or a tuple of classes.
 
891
            exception class, or a tuple of classes.
 
892
        :param callableObj: A callable, will be passed ``*args`` and
 
893
            ``**kwargs``.
879
894
 
880
895
        Returns the exception so that you can examine it.
881
896
        """
882
897
        try:
883
 
            func(*args, **kwargs)
 
898
            callableObj(*args, **kwargs)
884
899
        except excClass, e:
885
900
            return e
886
901
        else:
965
980
        :param args: The positional arguments for the callable
966
981
        :param kwargs: The keyword arguments for the callable
967
982
        :return: A tuple (warnings, result). result is the result of calling
968
 
            a_callable(*args, **kwargs).
 
983
            a_callable(``*args``, ``**kwargs``).
969
984
        """
970
985
        local_warnings = []
971
986
        def capture_warnings(msg, cls=None, stacklevel=None):
984
999
    def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
985
1000
        """Call a deprecated callable without warning the user.
986
1001
 
 
1002
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1003
        not other callers that go direct to the warning module.
 
1004
 
987
1005
        :param deprecation_format: The deprecation format that the callable
988
 
            should have been deprecated with. This is the same type as the 
989
 
            parameter to deprecated_method/deprecated_function. If the 
 
1006
            should have been deprecated with. This is the same type as the
 
1007
            parameter to deprecated_method/deprecated_function. If the
990
1008
            callable is not deprecated with this format, an assertion error
991
1009
            will be raised.
992
1010
        :param a_callable: A callable to call. This may be a bound method or
993
 
            a regular function. It will be called with *args and **kwargs.
 
1011
            a regular function. It will be called with ``*args`` and
 
1012
            ``**kwargs``.
994
1013
        :param args: The positional arguments for the callable
995
1014
        :param kwargs: The keyword arguments for the callable
996
 
        :return: The result of a_callable(*args, **kwargs)
 
1015
        :return: The result of a_callable(``*args``, ``**kwargs``)
997
1016
        """
998
1017
        call_warnings, result = self._capture_warnings(a_callable,
999
1018
            *args, **kwargs)
1013
1032
        as it allows you to simply specify the deprecation format being used
1014
1033
        and will ensure that that is issued for the function being called.
1015
1034
 
 
1035
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1036
        not other callers that go direct to the warning module.
 
1037
 
1016
1038
        :param expected: a list of the deprecation warnings expected, in order
1017
1039
        :param callable: The callable to call
1018
1040
        :param args: The positional arguments for the callable
1097
1119
        """Set an environment variable, and reset it when finished."""
1098
1120
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1099
1121
 
 
1122
    def _restore_debug_flags(self):
 
1123
        debug.debug_flags.clear()
 
1124
        debug.debug_flags.update(self._preserved_debug_flags)
 
1125
 
1100
1126
    def _restoreEnvironment(self):
1101
1127
        for name, value in self.__old_env.iteritems():
1102
1128
            osutils.set_or_unset_env(name, value)
1193
1219
        else:
1194
1220
            return "DELETED log file to reduce memory footprint"
1195
1221
 
 
1222
    @deprecated_method(zero_eighteen)
1196
1223
    def capture(self, cmd, retcode=0):
1197
1224
        """Shortcut that splits cmd into words, runs, and returns stdout"""
1198
1225
        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
1205
1232
        if not feature.available():
1206
1233
            raise UnavailableFeature(feature)
1207
1234
 
 
1235
    @deprecated_method(zero_eighteen)
1208
1236
    def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None,
1209
1237
                         working_dir=None):
1210
1238
        """Invoke bzr and return (stdout, stderr).
1211
1239
 
1212
 
        Useful for code that wants to check the contents of the
1213
 
        output, the way error messages are presented, etc.
1214
 
 
1215
 
        This should be the main method for tests that want to exercise the
1216
 
        overall behavior of the bzr application (rather than a unit test
1217
 
        or a functional test of the library.)
1218
 
 
1219
 
        Much of the old code runs bzr by forking a new copy of Python, but
1220
 
        that is slower, harder to debug, and generally not necessary.
1221
 
 
1222
 
        This runs bzr through the interface that catches and reports
1223
 
        errors, and with logging set to something approximating the
1224
 
        default, so that error reporting can be checked.
1225
 
 
1226
 
        :param argv: arguments to invoke bzr
1227
 
        :param retcode: expected return code, or None for don't-care.
1228
 
        :param encoding: encoding for sys.stdout and sys.stderr
 
1240
        Don't call this method, just use run_bzr() which is equivalent.
 
1241
 
 
1242
        :param argv: Arguments to invoke bzr.  This may be either a 
 
1243
            single string, in which case it is split by shlex into words, 
 
1244
            or a list of arguments.
 
1245
        :param retcode: Expected return code, or None for don't-care.
 
1246
        :param encoding: Encoding for sys.stdout and sys.stderr
1229
1247
        :param stdin: A string to be used as stdin for the command.
1230
1248
        :param working_dir: Change to this directory before running
1231
1249
        """
 
1250
        return self._run_bzr_autosplit(argv, retcode=retcode,
 
1251
                encoding=encoding, stdin=stdin, working_dir=working_dir,
 
1252
                )
 
1253
 
 
1254
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
 
1255
            working_dir):
 
1256
        """Run bazaar command line, splitting up a string command line."""
 
1257
        if isinstance(args, basestring):
 
1258
            args = list(shlex.split(args))
 
1259
        return self._run_bzr_core(args, retcode=retcode,
 
1260
                encoding=encoding, stdin=stdin, working_dir=working_dir,
 
1261
                )
 
1262
 
 
1263
    def _run_bzr_core(self, args, retcode, encoding, stdin,
 
1264
            working_dir):
1232
1265
        if encoding is None:
1233
1266
            encoding = bzrlib.user_encoding
1234
1267
        stdout = StringIOWrapper()
1236
1269
        stdout.encoding = encoding
1237
1270
        stderr.encoding = encoding
1238
1271
 
1239
 
        self.log('run bzr: %r', argv)
 
1272
        self.log('run bzr: %r', args)
1240
1273
        # FIXME: don't call into logging here
1241
1274
        handler = logging.StreamHandler(stderr)
1242
1275
        handler.setLevel(logging.INFO)
1251
1284
            os.chdir(working_dir)
1252
1285
 
1253
1286
        try:
1254
 
            saved_debug_flags = frozenset(debug.debug_flags)
1255
 
            debug.debug_flags.clear()
1256
 
            try:
1257
 
                result = self.apply_redirected(ui.ui_factory.stdin,
1258
 
                                               stdout, stderr,
1259
 
                                               bzrlib.commands.run_bzr_catch_errors,
1260
 
                                               argv)
1261
 
            finally:
1262
 
                debug.debug_flags.update(saved_debug_flags)
 
1287
            result = self.apply_redirected(ui.ui_factory.stdin,
 
1288
                stdout, stderr,
 
1289
                bzrlib.commands.run_bzr_catch_errors,
 
1290
                args)
1263
1291
        finally:
1264
1292
            logger.removeHandler(handler)
1265
1293
            ui.ui_factory = old_ui_factory
1280
1308
    def run_bzr(self, *args, **kwargs):
1281
1309
        """Invoke bzr, as if it were run from the command line.
1282
1310
 
 
1311
        The argument list should not include the bzr program name - the
 
1312
        first argument is normally the bzr command.  Arguments may be
 
1313
        passed in three ways:
 
1314
 
 
1315
        1- A list of strings, eg ["commit", "a"].  This is recommended
 
1316
        when the command contains whitespace or metacharacters, or 
 
1317
        is built up at run time.
 
1318
 
 
1319
        2- A single string, eg "add a".  This is the most convenient 
 
1320
        for hardcoded commands.
 
1321
 
 
1322
        3- Several varargs parameters, eg run_bzr("add", "a").  
 
1323
        This is not recommended for new code.
 
1324
 
 
1325
        This runs bzr through the interface that catches and reports
 
1326
        errors, and with logging set to something approximating the
 
1327
        default, so that error reporting can be checked.
 
1328
 
1283
1329
        This should be the main method for tests that want to exercise the
1284
1330
        overall behavior of the bzr application (rather than a unit test
1285
1331
        or a functional test of the library.)
1287
1333
        This sends the stdout/stderr results into the test's log,
1288
1334
        where it may be useful for debugging.  See also run_captured.
1289
1335
 
1290
 
        :param stdin: A string to be used as stdin for the command.
1291
 
        :param retcode: The status code the command should return
1292
 
        :param working_dir: The directory to run the command in
 
1336
        :keyword stdin: A string to be used as stdin for the command.
 
1337
        :keyword retcode: The status code the command should return;
 
1338
            default 0.
 
1339
        :keyword working_dir: The directory to run the command in
 
1340
        :keyword error_regexes: A list of expected error messages.  If
 
1341
            specified they must be seen in the error output of the command.
1293
1342
        """
1294
1343
        retcode = kwargs.pop('retcode', 0)
1295
1344
        encoding = kwargs.pop('encoding', None)
1297
1346
        working_dir = kwargs.pop('working_dir', None)
1298
1347
        error_regexes = kwargs.pop('error_regexes', [])
1299
1348
 
1300
 
        out, err = self.run_bzr_captured(args, retcode=retcode,
1301
 
            encoding=encoding, stdin=stdin, working_dir=working_dir)
 
1349
        if len(args) == 1:
 
1350
            if isinstance(args[0], (list, basestring)):
 
1351
                args = args[0]
 
1352
        else:
 
1353
            ## symbol_versioning.warn(zero_eighteen % "passing varargs to run_bzr",
 
1354
            ##         DeprecationWarning, stacklevel=2)
 
1355
            # not done yet, because too many tests would need to  be updated -
 
1356
            # but please don't do this in new code.  -- mbp 20070626
 
1357
            pass
 
1358
 
 
1359
        out, err = self._run_bzr_autosplit(args=args,
 
1360
            retcode=retcode,
 
1361
            encoding=encoding, stdin=stdin, working_dir=working_dir,
 
1362
            )
1302
1363
 
1303
1364
        for regex in error_regexes:
1304
1365
            self.assertContainsRe(err, regex)
1305
1366
        return out, err
1306
1367
 
1307
 
 
1308
1368
    def run_bzr_decode(self, *args, **kwargs):
1309
1369
        if 'encoding' in kwargs:
1310
1370
            encoding = kwargs['encoding']
1314
1374
 
1315
1375
    def run_bzr_error(self, error_regexes, *args, **kwargs):
1316
1376
        """Run bzr, and check that stderr contains the supplied regexes
1317
 
        
1318
 
        :param error_regexes: Sequence of regular expressions which 
 
1377
 
 
1378
        :param error_regexes: Sequence of regular expressions which
1319
1379
            must each be found in the error output. The relative ordering
1320
1380
            is not enforced.
1321
1381
        :param args: command-line arguments for bzr
1322
1382
        :param kwargs: Keyword arguments which are interpreted by run_bzr
1323
1383
            This function changes the default value of retcode to be 3,
1324
1384
            since in most cases this is run when you expect bzr to fail.
1325
 
        :return: (out, err) The actual output of running the command (in case you
1326
 
                 want to do more inspection)
1327
 
 
1328
 
        Examples of use:
 
1385
        :return: (out, err) The actual output of running the command (in case
 
1386
            you want to do more inspection)
 
1387
 
 
1388
        Examples of use::
 
1389
 
1329
1390
            # Make sure that commit is failing because there is nothing to do
1330
1391
            self.run_bzr_error(['no changes to commit'],
1331
1392
                               'commit', '-m', 'my commit comment')
1348
1409
        handling, or early startup code, etc.  Subprocess code can't be 
1349
1410
        profiled or debugged so easily.
1350
1411
 
1351
 
        :param retcode: The status code that is expected.  Defaults to 0.  If
 
1412
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
1352
1413
            None is supplied, the status code is not checked.
1353
 
        :param env_changes: A dictionary which lists changes to environment
 
1414
        :keyword env_changes: A dictionary which lists changes to environment
1354
1415
            variables. A value of None will unset the env variable.
1355
1416
            The values must be strings. The change will only occur in the
1356
1417
            child, so you don't need to fix the environment after running.
1357
 
        :param universal_newlines: Convert CRLF => LF
1358
 
        :param allow_plugins: By default the subprocess is run with
 
1418
        :keyword universal_newlines: Convert CRLF => LF
 
1419
        :keyword allow_plugins: By default the subprocess is run with
1359
1420
            --no-plugins to ensure test reproducibility. Also, it is possible
1360
1421
            for system-wide plugins to create unexpected output on stderr,
1361
1422
            which can cause unnecessary test failures.
1385
1446
        profiled or debugged so easily.
1386
1447
 
1387
1448
        :param process_args: a list of arguments to pass to the bzr executable,
1388
 
            for example `['--version']`.
 
1449
            for example ``['--version']``.
1389
1450
        :param env_changes: A dictionary which lists changes to environment
1390
1451
            variables. A value of None will unset the env variable.
1391
1452
            The values must be strings. The change will only occur in the
1489
1550
        shape = list(shape)             # copy
1490
1551
        for path, ie in inv.entries():
1491
1552
            name = path.replace('\\', '/')
1492
 
            if ie.kind == 'dir':
 
1553
            if ie.kind == 'directory':
1493
1554
                name = name + '/'
1494
1555
            if name in shape:
1495
1556
                shape.remove(name)
1532
1593
            sys.stderr = real_stderr
1533
1594
            sys.stdin = real_stdin
1534
1595
 
1535
 
    @symbol_versioning.deprecated_method(symbol_versioning.zero_eleven)
1536
 
    def merge(self, branch_from, wt_to):
1537
 
        """A helper for tests to do a ui-less merge.
1538
 
 
1539
 
        This should move to the main library when someone has time to integrate
1540
 
        it in.
1541
 
        """
1542
 
        # minimal ui-less merge.
1543
 
        wt_to.branch.fetch(branch_from)
1544
 
        base_rev = common_ancestor(branch_from.last_revision(),
1545
 
                                   wt_to.branch.last_revision(),
1546
 
                                   wt_to.branch.repository)
1547
 
        merge_inner(wt_to.branch, branch_from.basis_tree(),
1548
 
                    wt_to.branch.repository.revision_tree(base_rev),
1549
 
                    this_tree=wt_to)
1550
 
        wt_to.add_parent_tree_id(branch_from.last_revision())
1551
 
 
1552
1596
    def reduceLockdirTimeout(self):
1553
1597
        """Reduce the default lock timeout for the duration of the test, so that
1554
1598
        if LockContention occurs during a test, it does so quickly.
1561
1605
        self.addCleanup(resetTimeout)
1562
1606
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
1563
1607
 
1564
 
BzrTestBase = TestCase
1565
 
 
1566
1608
 
1567
1609
class TestCaseWithMemoryTransport(TestCase):
1568
1610
    """Common test class for tests that do not need disk resources.
1730
1772
        capabilities of the local filesystem, but it might actually be a
1731
1773
        MemoryTransport or some other similar virtual filesystem.
1732
1774
 
1733
 
        This is the backing transport (if any) of the server returned by 
 
1775
        This is the backing transport (if any) of the server returned by
1734
1776
        get_url and get_readonly_url.
1735
1777
 
1736
1778
        :param relpath: provides for clients to get a path relative to the base
1737
1779
            url.  These should only be downwards relative, not upwards.
 
1780
        :return: A URL
1738
1781
        """
1739
1782
        base = self.get_vfs_only_server().get_url()
1740
1783
        return self._adjust_url(base, relpath)
1876
1919
        self.addCleanup(self.deleteTestDir)
1877
1920
 
1878
1921
    def deleteTestDir(self):
 
1922
        os.chdir(self.TEST_ROOT)
1879
1923
        _rmtree_temp_dir(self.test_base_dir)
1880
1924
 
1881
1925
    def build_tree(self, shape, line_endings='binary', transport=None):
1887
1931
        This assumes that all the elements in the tree being built are new.
1888
1932
 
1889
1933
        This doesn't add anything to a branch.
 
1934
 
1890
1935
        :param line_endings: Either 'binary' or 'native'
1891
 
                             in binary mode, exact contents are written
1892
 
                             in native mode, the line endings match the
1893
 
                             default platform endings.
1894
 
 
1895
 
        :param transport: A transport to write to, for building trees on 
1896
 
                          VFS's. If the transport is readonly or None,
1897
 
                          "." is opened automatically.
 
1936
            in binary mode, exact contents are written in native mode, the
 
1937
            line endings match the default platform endings.
 
1938
        :param transport: A transport to write to, for building trees on VFS's.
 
1939
            If the transport is readonly or None, "." is opened automatically.
 
1940
        :return: None
1898
1941
        """
1899
1942
        # It's OK to just create them using forward slashes on windows.
1900
1943
        if transport is None or transport.is_readonly():
2253
2296
                   'bzrlib.tests.test_graph',
2254
2297
                   'bzrlib.tests.test_hashcache',
2255
2298
                   'bzrlib.tests.test_help',
 
2299
                   'bzrlib.tests.test_hooks',
2256
2300
                   'bzrlib.tests.test_http',
2257
2301
                   'bzrlib.tests.test_http_response',
2258
2302
                   'bzrlib.tests.test_https_ca_bundle',