Rev 2874: If an internal error happens in a test, don't turn it into a return code plus traceback but rather let it run up and be seen as a test error (mbp) in file:///home/pqm/archives/thelove/bzr/%2Btrunk/

Canonical.com Patch Queue Manager pqm at pqm.ubuntu.com
Tue Oct 2 08:48:23 BST 2007


At file:///home/pqm/archives/thelove/bzr/%2Btrunk/

------------------------------------------------------------
revno: 2874
revision-id: pqm at pqm.ubuntu.com-20071002074820-0o6n138uq5uh7snb
parent: pqm at pqm.ubuntu.com-20071002034323-vljek8tt4xkzxkcu
parent: mbp at sourcefrog.net-20071002071411-e12qelg28twzd6rz
committer: Canonical.com Patch Queue Manager <pqm at pqm.ubuntu.com>
branch nick: +trunk
timestamp: Tue 2007-10-02 08:48:20 +0100
message:
  If an internal error happens in a test, don't turn it into a return code plus traceback but rather let it run up and be seen as a test error (mbp)
modified:
  NEWS                           NEWS-20050323055033-4e00b5db738777ff
  bzrlib/commands.py             bzr.py-20050309040720-d10f4714595cf8c3
  bzrlib/errors.py               errors.py-20050309040759-20512168c4e14fbd
  bzrlib/symbol_versioning.py    symbol_versioning.py-20060105104851-9ecf8af605d15a80
  bzrlib/tests/__init__.py       selftest.py-20050531073622-8d0e3c8845c97a64
  bzrlib/tests/blackbox/test_command_encoding.py test_command_encoding.py-20060106032110-45431fd2ce9ff21f
  bzrlib/tests/blackbox/test_exceptions.py test_exceptions.py-20060604211237-yi2cxg0ose3xk4id-1
  bzrlib/tests/blackbox/test_non_ascii.py test_non_ascii.py-20060105214030-68010be784a5d854
  bzrlib/tests/blackbox/test_selftest.py test_selftest.py-20060123024542-01c5f1bbcb596d78
  bzrlib/tests/test_selftest.py  test_selftest.py-20051202044319-c110a115d8c0456a
  bzrlib/trace.py                trace.py-20050309040759-c8ed824bdcd4748a
  doc/developers/HACKING.txt     HACKING-20050805200004-2a5dc975d870f78c
    ------------------------------------------------------------
    revno: 2830.2.12
    merged: mbp at sourcefrog.net-20071002071411-e12qelg28twzd6rz
    parent: mbp at sourcefrog.net-20071002065652-9pjpwb1vulkjvrvh
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-10-02 17:14:11 +1000
    message:
      Fix vim lossage
    ------------------------------------------------------------
    revno: 2830.2.11
    merged: mbp at sourcefrog.net-20071002065652-9pjpwb1vulkjvrvh
    parent: mbp at sourcefrog.net-20071002061356-t1od1dmnppz33diq
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-10-02 16:56:52 +1000
    message:
      Integrate testing of return codes/error reporting
    ------------------------------------------------------------
    revno: 2830.2.10
    merged: mbp at sourcefrog.net-20071002061356-t1od1dmnppz33diq
    parent: mbp at sourcefrog.net-20071002060452-4e4w9deuxn3azr0m
    parent: mbp at sourcefrog.net-20070918072340-gs8a71bda3e26dsh
    parent: pqm at pqm.ubuntu.com-20070928041435-uls0r9txks111272
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-10-02 16:13:56 +1000
    message:
      merge trunk
        ------------------------------------------------------------
        revno: 2830.2.5.1.1
        merged: mbp at sourcefrog.net-20070918072340-gs8a71bda3e26dsh
        parent: mbp at sourcefrog.net-20070918063155-ifdze60wpnslgdbv
        committer: Martin Pool <mbp at sourcefrog.net>
        branch nick: test-traceback
        timestamp: Tue 2007-09-18 17:23:40 +1000
        message:
          Make run_bzr_decode undeprecated again, but put it in the particular test class
          TestNonAscii that needs it.  Remove run_bzr(output_encoding) parameter.
          
          run_bzr_decode now takes a specific parameter that says if we expect the
          operation to fail with a UnicodeError, and we test for that in particular.
    ------------------------------------------------------------
    revno: 2830.2.9
    merged: mbp at sourcefrog.net-20071002060452-4e4w9deuxn3azr0m
    parent: mbp at sourcefrog.net-20071002060412-x3koee70tqi5fg36
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-10-02 16:04:52 +1000
    message:
      Add EXIT_OK=0
    ------------------------------------------------------------
    revno: 2830.2.8
    merged: mbp at sourcefrog.net-20071002060412-x3koee70tqi5fg36
    parent: mbp at sourcefrog.net-20070924064221-nu12try0hbilenlj
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-10-02 16:04:12 +1000
    message:
      Review cleanups of test_non_ascii
    ------------------------------------------------------------
    revno: 2830.2.7
    merged: mbp at sourcefrog.net-20070924064221-nu12try0hbilenlj
    parent: mbp at sourcefrog.net-20070921060245-j6a3g6oxdbs1bdjn
    parent: mbp at sourcefrog.net-20070820060505-4ywu68q7scnbfmat
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Mon 2007-09-24 16:42:21 +1000
    message:
      Return exitcode 4 on internal error
        ------------------------------------------------------------
        revno: 2713.2.3
        merged: mbp at sourcefrog.net-20070820060505-4ywu68q7scnbfmat
        parent: mbp at sourcefrog.net-20070820041609-gere4zndmrvviwji
        parent: pqm at pqm.ubuntu.com-20070820045741-zojy0q9vgi0d860r
        committer: Martin Pool <mbp at sourcefrog.net>
        branch nick: error-exitcode
        timestamp: Mon 2007-08-20 16:05:05 +1000
        message:
          merge trunk
        ------------------------------------------------------------
        revno: 2713.2.2
        merged: mbp at sourcefrog.net-20070820041609-gere4zndmrvviwji
        parent: mbp at sourcefrog.net-20070816075121-fr9221nx4clj2eoz
        committer: Martin Pool <mbp at sourcefrog.net>
        branch nick: error-exitcode
        timestamp: Mon 2007-08-20 14:16:09 +1000
        message:
          Add mention of exitcode 4 for internal errors
        ------------------------------------------------------------
        revno: 2713.2.1
        merged: mbp at sourcefrog.net-20070816075121-fr9221nx4clj2eoz
        parent: pqm at pqm.ubuntu.com-20070816055011-tnjdmdi948uyvz6a
        committer: Martin Pool <mbp at sourcefrog.net>
        branch nick: error-exitcode
        timestamp: Thu 2007-08-16 17:51:21 +1000
        message:
          Return exitcode 4 if an internal error occurs
    ------------------------------------------------------------
    revno: 2830.2.6
    merged: mbp at sourcefrog.net-20070921060245-j6a3g6oxdbs1bdjn
    parent: mbp at sourcefrog.net-20070918063155-ifdze60wpnslgdbv
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Fri 2007-09-21 16:02:45 +1000
    message:
      Make run_bzr_decode undeprecated again, but put it in the particular test class
      TestNonAscii that needs it.  Remove run_bzr(output_encoding) parameter.
      
      run_bzr_decode now takes a specific parameter that says if we expect the
      operation to fail with a UnicodeError, and we test for that in particular.
    ------------------------------------------------------------
    revno: 2830.2.5
    merged: mbp at sourcefrog.net-20070918063155-ifdze60wpnslgdbv
    parent: mbp at sourcefrog.net-20070918062825-vw07w72sphre1z9l
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-09-18 16:31:55 +1000
    message:
      Deprecated ``run_bzr_decode``; use the new ``output_encoding`` parameter to 
      ``TestCase.run_bzr`` instead.
      
      Removed previously deprecated varargs interface to ``TestCase.run_bzr`` and
      deprecated methods ``TestCase.capture`` and ``TestCase.run_bzr_captured``.
      (Martin Pool)
    ------------------------------------------------------------
    revno: 2830.2.4
    merged: mbp at sourcefrog.net-20070918062825-vw07w72sphre1z9l
    parent: mbp at sourcefrog.net-20070918054731-0t0117jhw02neu8h
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-09-18 16:28:25 +1000
    message:
      Fix previously hidden NameError in reconfigure
    ------------------------------------------------------------
    revno: 2830.2.3
    merged: mbp at sourcefrog.net-20070918054731-0t0117jhw02neu8h
    parent: mbp at sourcefrog.net-20070918054009-ftyrlbde4dmzi40t
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-09-18 15:47:31 +1000
    message:
      Fix up test_command_encoding to expect to see the assertion raised on unicode errors
    ------------------------------------------------------------
    revno: 2830.2.2
    merged: mbp at sourcefrog.net-20070918054009-ftyrlbde4dmzi40t
    parent: mbp at sourcefrog.net-20070918053531-hwrmyg05y3az3xcx
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-09-18 15:40:09 +1000
    message:
      Update test for report_exception to be cleaner and work with new run_bzr behavior
    ------------------------------------------------------------
    revno: 2830.2.1
    merged: mbp at sourcefrog.net-20070918053531-hwrmyg05y3az3xcx
    parent: pqm at pqm.ubuntu.com-20070918034007-n72x452efuovdelm
    committer: Martin Pool <mbp at sourcefrog.net>
    branch nick: test-traceback
    timestamp: Tue 2007-09-18 15:35:31 +1000
    message:
      If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
=== modified file 'NEWS'
--- a/NEWS	2007-09-28 00:50:33 +0000
+++ b/NEWS	2007-10-02 06:13:56 +0000
@@ -9,6 +9,11 @@
 
   NOTES WHEN UPGRADING:
 
+  CHANGES:
+  
+   * ``bzr`` now returns exit code 4 if an internal error occurred, and 
+     3 if a normal error occurred.  (Martin Pool)
+
    * ``pull``, ``merge`` and ``push`` will no longer silently correct some
      repository index errors that occured as a result of the Weave disk format.
      Instead the ``reconcile`` command needs to be run to correct those
@@ -115,6 +120,14 @@
      enable_cache() has been called - the caching feature is now exclusively for
      reading existing data. (Robert Collins)
 
+   * Removed previously deprecated varargs interface to ``TestCase.run_bzr`` and
+     deprecated methods ``TestCase.capture`` and ``TestCase.run_bzr_captured``.
+     (Martin Pool)
+
+   * Special purpose method ``TestCase.run_bzr_decode`` is moved to the test_non_ascii 
+     class that needs it.
+     (Martin Pool)
+
    * The ``VersionedFile`` interface now allows content checks to be bypassed
      by supplying check_content=False.  This saves nearly 30% of the minimum
      cost to store a version of a file. (Robert Collins)
@@ -161,6 +174,12 @@
 
   TESTING:
 
+   * When running bzr commands within the test suite, internal exceptions are
+     not caught and reported in the usual way, but rather allowed to propagate
+     up and be visible to the test suite.  A new API ``run_bzr_catch_user_errors``
+     makes this behavior available to other users.
+     (Martin Pool)
+
 
 bzr 0.91rc2 2007-09-11
 ======================

=== modified file 'bzrlib/commands.py'
--- a/bzrlib/commands.py	2007-09-10 02:40:07 +0000
+++ b/bzrlib/commands.py	2007-09-24 06:42:21 +0000
@@ -803,12 +803,29 @@
     except (KeyboardInterrupt, Exception), e:
         # used to handle AssertionError and KeyboardInterrupt
         # specially here, but hopefully they're handled ok by the logger now
-        trace.report_exception(sys.exc_info(), sys.stderr)
+        exitcode = trace.report_exception(sys.exc_info(), sys.stderr)
         if os.environ.get('BZR_PDB'):
             print '**** entering debugger'
             import pdb
             pdb.post_mortem(sys.exc_traceback)
-        return 3
+        return exitcode
+
+
+def run_bzr_catch_user_errors(argv):
+    """Run bzr and report user errors, but let internal errors propagate.
+
+    This is used for the test suite, and might be useful for other programs
+    that want to wrap the commandline interface.
+    """
+    try:
+        return run_bzr(argv)
+    except Exception, e:
+        if (isinstance(e, (OSError, IOError))
+            or not getattr(e, 'internal_error', True)):
+            trace.report_exception(sys.exc_info(), sys.stderr)
+            return 3
+        else:
+            raise
 
 
 class HelpCommandIndex(object):

=== modified file 'bzrlib/errors.py'
--- a/bzrlib/errors.py	2007-09-28 00:50:33 +0000
+++ b/bzrlib/errors.py	2007-10-02 06:13:56 +0000
@@ -44,6 +44,12 @@
 # 'unprintable'.
 
 
+# return codes from the bzr program
+EXIT_OK = 0
+EXIT_ERROR = 3
+EXIT_INTERNAL_ERROR = 4
+
+
 class BzrError(StandardError):
     """
     Base class for errors raised by bzrlib.

=== modified file 'bzrlib/symbol_versioning.py'
--- a/bzrlib/symbol_versioning.py	2007-09-18 04:11:05 +0000
+++ b/bzrlib/symbol_versioning.py	2007-10-02 06:13:56 +0000
@@ -39,6 +39,7 @@
            'zero_eighteen',
            'zero_ninety',
            'zero_ninetyone',
+           'zero_ninetytwo',
            ]
 
 from warnings import warn
@@ -59,6 +60,7 @@
 zero_eighteen = "%s was deprecated in version 0.18."
 zero_ninety = "%s was deprecated in version 0.90."
 zero_ninetyone = "%s was deprecated in version 0.91."
+zero_ninetytwo = "%s was deprecated in version 0.92."
 
 
 def set_warning_method(method):

=== modified file 'bzrlib/tests/__init__.py'
--- a/bzrlib/tests/__init__.py	2007-09-24 08:46:35 +0000
+++ b/bzrlib/tests/__init__.py	2007-10-02 06:13:56 +0000
@@ -78,8 +78,8 @@
 from bzrlib import symbol_versioning
 from bzrlib.symbol_versioning import (
     deprecated_method,
-    zero_eighteen,
     zero_ninetyone,
+    zero_ninetytwo,
     )
 import bzrlib.trace
 from bzrlib.transport import get_transport
@@ -1289,11 +1289,6 @@
         else:
             return "DELETED log file to reduce memory footprint"
 
-    @deprecated_method(zero_eighteen)
-    def capture(self, cmd, retcode=0):
-        """Shortcut that splits cmd into words, runs, and returns stdout"""
-        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
-
     def requireFeature(self, feature):
         """This test requires a specific feature is available.
 
@@ -1302,25 +1297,6 @@
         if not feature.available():
             raise UnavailableFeature(feature)
 
-    @deprecated_method(zero_eighteen)
-    def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None,
-                         working_dir=None):
-        """Invoke bzr and return (stdout, stderr).
-
-        Don't call this method, just use run_bzr() which is equivalent.
-
-        :param argv: Arguments to invoke bzr.  This may be either a 
-            single string, in which case it is split by shlex into words, 
-            or a list of arguments.
-        :param retcode: Expected return code, or None for don't-care.
-        :param encoding: Encoding for sys.stdout and sys.stderr
-        :param stdin: A string to be used as stdin for the command.
-        :param working_dir: Change to this directory before running
-        """
-        return self._run_bzr_autosplit(argv, retcode=retcode,
-                encoding=encoding, stdin=stdin, working_dir=working_dir,
-                )
-
     def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
             working_dir):
         """Run bazaar command line, splitting up a string command line."""
@@ -1356,7 +1332,7 @@
         try:
             result = self.apply_redirected(ui.ui_factory.stdin,
                 stdout, stderr,
-                bzrlib.commands.run_bzr_catch_errors,
+                bzrlib.commands.run_bzr_catch_user_errors,
                 args)
         finally:
             logger.removeHandler(handler)
@@ -1375,7 +1351,8 @@
                               message='Unexpected return code')
         return out, err
 
-    def run_bzr(self, *args, **kwargs):
+    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
+                working_dir=None, error_regexes=[], output_encoding=None):
         """Invoke bzr, as if it were run from the command line.
 
         The argument list should not include the bzr program name - the
@@ -1389,9 +1366,6 @@
         2- A single string, eg "add a".  This is the most convenient 
         for hardcoded commands.
 
-        3- Several varargs parameters, eg run_bzr("add", "a").  
-        This is not recommended for new code.
-
         This runs bzr through the interface that catches and reports
         errors, and with logging set to something approximating the
         default, so that error reporting can be checked.
@@ -1410,39 +1384,17 @@
         :keyword error_regexes: A list of expected error messages.  If
             specified they must be seen in the error output of the command.
         """
-        retcode = kwargs.pop('retcode', 0)
-        encoding = kwargs.pop('encoding', None)
-        stdin = kwargs.pop('stdin', None)
-        working_dir = kwargs.pop('working_dir', None)
-        error_regexes = kwargs.pop('error_regexes', [])
-
-        if kwargs:
-            raise TypeError("run_bzr() got unexpected keyword arguments '%s'"
-                            % kwargs.keys())
-
-        if len(args) == 1:
-            if isinstance(args[0], (list, basestring)):
-                args = args[0]
-        else:
-            symbol_versioning.warn(zero_eighteen % "passing varargs to run_bzr",
-                                   DeprecationWarning, stacklevel=3)
-
-        out, err = self._run_bzr_autosplit(args=args,
+        out, err = self._run_bzr_autosplit(
+            args=args,
             retcode=retcode,
-            encoding=encoding, stdin=stdin, working_dir=working_dir,
+            encoding=encoding,
+            stdin=stdin,
+            working_dir=working_dir,
             )
-
         for regex in error_regexes:
             self.assertContainsRe(err, regex)
         return out, err
 
-    def run_bzr_decode(self, *args, **kwargs):
-        if 'encoding' in kwargs:
-            encoding = kwargs['encoding']
-        else:
-            encoding = bzrlib.user_encoding
-        return self.run_bzr(*args, **kwargs)[0].decode(encoding)
-
     def run_bzr_error(self, error_regexes, *args, **kwargs):
         """Run bzr, and check that stderr contains the supplied regexes
 

=== modified file 'bzrlib/tests/blackbox/test_command_encoding.py'
--- a/bzrlib/tests/blackbox/test_command_encoding.py	2007-06-26 20:32:49 +0000
+++ b/bzrlib/tests/blackbox/test_command_encoding.py	2007-09-18 05:47:31 +0000
@@ -1,5 +1,4 @@
-# Copyright (C) 2005 Canonical Ltd
-# -*- coding: utf-8 -*-
+# Copyright (C) 2005, 2007 Canonical Ltd
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -35,7 +34,7 @@
 
 
 class cmd_echo_strict(cmd_echo_exact):
-    """Replace bogus unicode characters."""
+    """Raise a UnicodeError for unrepresentable characters."""
 
     encoding_type = 'strict'
 
@@ -59,7 +58,9 @@
             # get past main()
             self.assertEqual('foo\xb5', bzr('echo-exact foo\xb5'))
             # Exact should fail to decode the string
-            bzr(['echo-exact', u'foo\xb5'], retcode=3)
+            self.assertRaises(UnicodeEncodeError,
+                bzr,
+                ['echo-exact', u'foo\xb5'])
         finally:
             plugin_cmds.pop('echo-exact')
 
@@ -85,7 +86,9 @@
         try:
             self.assertEqual('foo', bzr('echo-strict foo'))
             # ascii can't encode \xb5
-            bzr(['echo-strict', u'foo\xb5'], retcode=3)
+            self.assertRaises(UnicodeEncodeError,
+                bzr,
+                ['echo-strict', u'foo\xb5'])
         finally:
             plugin_cmds.pop('echo-strict')
 

=== modified file 'bzrlib/tests/blackbox/test_exceptions.py'
--- a/bzrlib/tests/blackbox/test_exceptions.py	2007-09-21 06:13:09 +0000
+++ b/bzrlib/tests/blackbox/test_exceptions.py	2007-10-02 06:56:52 +0000
@@ -1,4 +1,4 @@
-# Copyright (C) 2006 Canonical Ltd
+# Copyright (C) 2006, 2007 Canonical Ltd
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -16,31 +16,49 @@
 
 """Tests for display of exceptions."""
 
+from cStringIO import StringIO
 import os
 import sys
 
-from bzrlib import bzrdir, repository
+from bzrlib import (
+    bzrdir,
+    errors,
+    repository,
+    trace,
+    )
 
 from bzrlib.tests import TestCaseInTempDir, TestCase
 from bzrlib.errors import NotBranchError
 
+
 class TestExceptionReporting(TestCase):
 
     def test_report_exception(self):
         """When an error occurs, display bug report details to stderr"""
-        out, err = self.run_bzr("assert-fail", retcode=3)
+        try:
+            raise AssertionError("failed")
+        except AssertionError, e:
+            erf = StringIO()
+            trace.report_exception(sys.exc_info(), erf)
+        err = erf.getvalue()
+        self.assertContainsRe(err,
+            r'bzr: ERROR: exceptions\.AssertionError: failed\n')
+        self.assertContainsRe(err,
+            r'Please send this report to')
+        self.assertContainsRe(err,
+            '(?m)^encoding: .*, fsenc: .*, lang: .*')
+        self.assertContainsRe(err,
+            '(?m)^plugins:$')
+
+    def test_exception_exitcode(self):
+        # we must use a subprocess, because the normal in-memory mechanism
+        # allows errors to propagate up through the test suite
+        out, err = self.run_bzr_subprocess(['assert-fail'],
+            retcode=errors.EXIT_INTERNAL_ERROR)
+        self.assertEqual(4, errors.EXIT_INTERNAL_ERROR)
         self.assertContainsRe(err,
                 r'bzr: ERROR: exceptions\.AssertionError: always fails\n')
         self.assertContainsRe(err, r'Please send this report to')
-        self.assertContainsRe(err,
-            '(?m)^encoding: .*, fsenc: .*, lang: .*')
-        self.assertContainsRe(err,
-            '(?m)^plugins:$')
-
-    # TODO: assert-fail doesn't need to always be present; we could just
-    # register (and unregister) it from tests that want to touch it.
-    #
-    # TODO: Some kind of test for the feature of invoking pdb
     
 
 class TestDeprecationWarning(TestCaseInTempDir):

=== modified file 'bzrlib/tests/blackbox/test_non_ascii.py'
--- a/bzrlib/tests/blackbox/test_non_ascii.py	2007-06-26 20:32:49 +0000
+++ b/bzrlib/tests/blackbox/test_non_ascii.py	2007-10-02 07:14:11 +0000
@@ -1,5 +1,4 @@
-# Copyright (C) 2006 Canonical Ltd
-# -*- coding: utf-8 -*-
+# Copyright (C) 2006, 2007 Canonical Ltd
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -48,9 +47,32 @@
         bzrlib.user_encoding = self._orig_encoding
         super(TestNonAscii, self).tearDown()
 
+    def run_bzr_decode(self, args, encoding=None, fail=False, retcode=None):
+        """Run bzr and decode the output into a particular encoding.
+
+        Returns a string containing the stdout output from bzr.
+
+        :param fail: If true, the operation is expected to fail with 
+            a UnicodeError.
+        """
+        if encoding is None:
+            encoding = bzrlib.user_encoding
+        try:
+            out = self.run_bzr(args, output_encoding=encoding, encoding=encoding,
+                retcode=retcode)[0]
+            return out.decode(encoding)
+        except UnicodeError, e:
+            if not fail:
+                raise
+        else:
+            # This command, run from the regular command line, will give a
+            # traceback to the user.  That's not really good for a situation
+            # that can be provoked just by the interaction of their input data
+            # and locale, as some of these are.  What would be better?
+            if fail:
+                self.fail("Expected UnicodeError not raised")
+
     def create_base(self):
-        bzr = self.run_bzr
-
         fs_enc = sys.getfilesystemencoding()
         terminal_enc = osutils.get_terminal_encoding()
         fname = self.info['filename']
@@ -86,13 +108,11 @@
         self.wt = wt
 
     def test_status(self):
-        bzr = self.run_bzr_decode
-
         open(self.info['filename'], 'ab').write('added something\n')
-        txt = bzr('status')
+        txt = self.run_bzr_decode('status')
         self.assertEqual(u'modified:\n  %s\n' % (self.info['filename'],), txt)
 
-        txt = bzr('status', encoding='ascii')
+        txt = self.run_bzr_decode('status', encoding='ascii')
         expected = u'modified:\n  %s\n' % (
                     self.info['filename'].encode('ascii', 'replace'),)
         self.assertEqual(expected, txt)
@@ -136,7 +156,7 @@
         txt = bzr(['relpath', self.info['filename']])
         self.assertEqual(self.info['filename'] + '\n', txt)
 
-        bzr(['relpath', self.info['filename']], encoding='ascii', retcode=3)
+        bzr(['relpath', self.info['filename']], encoding='ascii', fail=True)
 
     def test_inventory(self):
         bzr = self.run_bzr_decode
@@ -146,7 +166,7 @@
                          txt.splitlines())
 
         # inventory should fail if unable to encode
-        bzr('inventory', encoding='ascii', retcode=3)
+        bzr('inventory', encoding='ascii', fail=True)
 
         # We don't really care about the ids themselves,
         # but the command shouldn't fail
@@ -177,7 +197,7 @@
         dirname = self.info['directory']
 
         # fname1 already exists
-        bzr(['mv', 'a', fname1], retcode=3)
+        bzr(['mv', 'a', fname1], fail=True)
 
         txt = bzr(['mv', 'a', fname2])
         self.assertEqual(u'a => %s\n' % fname2, txt)
@@ -285,7 +305,7 @@
         txt = bzr('renames')
         self.assertEqual(u'a => %s\n' % fname, txt)
 
-        bzr('renames', retcode=3, encoding='ascii')
+        bzr('renames', fail=True, encoding='ascii')
 
     def test_remove(self):
         bzr = self.run_bzr_decode
@@ -368,7 +388,7 @@
         # Deleted should fail if cannot decode
         # Because it is giving the exact paths
         # which might be used by a front end
-        bzr('deleted', encoding='ascii', retcode=3)
+        bzr('deleted', encoding='ascii', fail=True)
 
     def test_modified(self):
         bzr = self.run_bzr_decode
@@ -379,7 +399,7 @@
         txt = bzr('modified')
         self.assertEqual(fname+'\n', txt)
 
-        bzr('modified', encoding='ascii', retcode=3)
+        bzr('modified', encoding='ascii', fail=True)
 
     def test_added(self):
         bzr = self.run_bzr_decode
@@ -391,7 +411,7 @@
         txt = bzr('added')
         self.assertEqual(fname+'\n', txt)
 
-        bzr('added', encoding='ascii', retcode=3)
+        bzr('added', encoding='ascii', fail=True)
 
     def test_root(self):
         bzr = self.run_bzr_decode
@@ -407,7 +427,7 @@
         txt = bzr('root')
         self.failUnless(txt.endswith(dirname+'\n'))
 
-        txt = bzr('root', encoding='ascii', retcode=3)
+        txt = bzr('root', encoding='ascii', fail=True)
 
     def test_log(self):
         bzr = self.run_bzr_decode
@@ -443,7 +463,7 @@
                         % (fname, fname, fname2))
         self.assertEqual(expected_txt, txt)
 
-        bzr(['touching-revisions', fname2], encoding='ascii', retcode=3)
+        bzr(['touching-revisions', fname2], encoding='ascii', fail=True)
 
     def test_ls(self):
         bzr = self.run_bzr_decode
@@ -455,8 +475,8 @@
         self.assertEqual(sorted(['', 'a', 'b', self.info['filename']]),
                          sorted(txt.split('\0')))
 
-        txt = bzr('ls', encoding='ascii', retcode=3)
-        txt = bzr('ls --null', encoding='ascii', retcode=3)
+        txt = bzr('ls', encoding='ascii', fail=True)
+        txt = bzr('ls --null', encoding='ascii', fail=True)
 
     def test_unknowns(self):
         bzr = self.run_bzr_decode
@@ -469,7 +489,7 @@
         txt = bzr('unknowns')
         self.assertEqual(u'"%s"\n' % (fname,), txt)
 
-        bzr('unknowns', encoding='ascii', retcode=3)
+        bzr('unknowns', encoding='ascii', fail=True)
 
     def test_ignore(self):
         bzr = self.run_bzr_decode

=== modified file 'bzrlib/tests/blackbox/test_selftest.py'
--- a/bzrlib/tests/blackbox/test_selftest.py	2007-08-15 03:51:59 +0000
+++ b/bzrlib/tests/blackbox/test_selftest.py	2007-09-18 06:31:55 +0000
@@ -111,14 +111,6 @@
         self.working_dir = working_dir
         return '', ''
 
-    def test_args(self):
-        """Test that run_bzr passes args correctly to _run_bzr_core"""
-        self.callDeprecated(
-                ['passing varargs to run_bzr was deprecated in version 0.18.'],
-                self.run_bzr,
-                'arg1', 'arg2', 'arg3', retcode=1)
-        self.assertEqual(['arg1', 'arg2', 'arg3'], self.argv)
-
     def test_encoding(self):
         """Test that run_bzr passes encoding to _run_bzr_core"""
         self.run_bzr('foo bar')

=== modified file 'bzrlib/tests/test_selftest.py'
--- a/bzrlib/tests/test_selftest.py	2007-09-17 12:34:31 +0000
+++ b/bzrlib/tests/test_selftest.py	2007-10-02 06:13:56 +0000
@@ -1659,3 +1659,29 @@
             self.check_inventory_shape(tree.inventory, files)
         finally:
             tree.unlock()
+
+
+class TestBlackboxSupport(TestCase):
+    """Tests for testsuite blackbox features."""
+
+    def test_run_bzr_failure_not_caught(self):
+        # When we run bzr in blackbox mode, we want any unexpected errors to
+        # propagate up to the test suite so that it can show the error in the
+        # usual way, and we won't get a double traceback.
+        e = self.assertRaises(
+            AssertionError,
+            self.run_bzr, ['assert-fail'])
+        # make sure we got the real thing, not an error from somewhere else in
+        # the test framework
+        self.assertEquals('always fails', str(e))
+        # check that there's no traceback in the test log
+        self.assertNotContainsRe(self._get_log(keep_log_file=True),
+            r'Traceback')
+
+    def test_run_bzr_user_error_caught(self):
+        # Running bzr in blackbox mode, normal/expected/user errors should be
+        # caught in the regular way and turned into an error message plus exit
+        # code.
+        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
+        self.assertEqual(out, '')
+        self.assertEqual(err, 'bzr: ERROR: Not a branch: "/nonexistantpath/".\n')

=== modified file 'bzrlib/trace.py'
--- a/bzrlib/trace.py	2007-09-24 06:00:49 +0000
+++ b/bzrlib/trace.py	2007-10-02 06:13:56 +0000
@@ -68,6 +68,7 @@
 lazy_import(globals(), """
 from bzrlib import (
     debug,
+    errors,
     osutils,
     plugin,
     )
@@ -312,22 +313,33 @@
 
 
 def report_exception(exc_info, err_file):
+    """Report an exception to err_file (typically stderr) and to .bzr.log.
+
+    This will show either a full traceback or a short message as appropriate.
+
+    :return: The appropriate exit code for this error.
+    """
     exc_type, exc_object, exc_tb = exc_info
     # Log the full traceback to ~/.bzr.log
     log_exception_quietly()
     if (isinstance(exc_object, IOError)
         and getattr(exc_object, 'errno', None) == errno.EPIPE):
         print >>err_file, "bzr: broken pipe"
+        return errors.EXIT_ERROR
     elif isinstance(exc_object, KeyboardInterrupt):
         print >>err_file, "bzr: interrupted"
+        return errors.EXIT_ERROR
     elif not getattr(exc_object, 'internal_error', True):
         report_user_error(exc_info, err_file)
+        return errors.EXIT_ERROR
     elif isinstance(exc_object, (OSError, IOError)):
         # Might be nice to catch all of these and show them as something more
         # specific, but there are too many cases at the moment.
         report_user_error(exc_info, err_file)
+        return errors.EXIT_ERROR
     else:
         report_bug(exc_info, err_file)
+        return errors.EXIT_INTERNAL_ERROR
 
 
 # TODO: Should these be specially encoding the output?

=== modified file 'doc/developers/HACKING.txt'
--- a/doc/developers/HACKING.txt	2007-09-18 04:21:20 +0000
+++ b/doc/developers/HACKING.txt	2007-10-02 06:13:56 +0000
@@ -1102,6 +1102,7 @@
     2. Unrepresentable diff changes (i.e. binary files that we cannot show 
        a diff of).
     3. An error or exception has occurred.
+    4. An internal error occurred (one that shows a traceback.)
 
 Errors are handled through Python exceptions. Exceptions should be defined
 inside bzrlib.errors, so that we can see the whole tree at a glance.




More information about the bazaar-commits mailing list