15
13
# You should have received a copy of the GNU General Public License
16
14
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
17
"""Tests for the formatting and construction of errors."""
22
24
from bzrlib import (
29
from bzrlib.tests import TestCase, TestCaseWithTransport
30
from bzrlib.tests import (
32
TestCaseWithTransport,
32
37
class TestErrors(TestCaseWithTransport):
39
def test_no_arg_named_message(self):
40
"""Ensure the __init__ and _fmt in errors do not have "message" arg.
42
This test fails if __init__ or _fmt in errors has an argument
43
named "message" as this can cause errors in some Python versions.
44
Python 2.5 uses a slot for StandardError.message.
47
fmt_pattern = re.compile("%\(message\)[sir]")
48
subclasses_present = getattr(errors.BzrError, '__subclasses__', None)
49
if not subclasses_present:
50
raise TestSkipped('__subclasses__ attribute required for classes. '
51
'Requires Python 2.5 or later.')
52
for c in errors.BzrError.__subclasses__():
53
init = getattr(c, '__init__', None)
54
fmt = getattr(c, '_fmt', None)
56
args = inspect.getargspec(init)[0]
57
self.assertFalse('message' in args,
58
('Argument name "message" not allowed for '
59
'"errors.%s.__init__"' % c.__name__))
60
if fmt and fmt_pattern.search(fmt):
61
self.assertFalse(True, ('"message" not allowed in '
62
'"errors.%s._fmt"' % c.__name__))
34
64
def test_bad_filename_encoding(self):
35
65
error = errors.BadFilenameEncoding('bad/filen\xe5me', 'UTF-8')
36
66
self.assertEqualDiff(
114
150
"read without data loss.",
117
def test_install_failed(self):
118
error = errors.InstallFailed(['rev-one'])
119
self.assertEqual("Could not install revisions:\nrev-one", str(error))
120
error = errors.InstallFailed(['rev-one', 'rev-two'])
121
self.assertEqual("Could not install revisions:\nrev-one, rev-two",
123
error = errors.InstallFailed([None])
124
self.assertEqual("Could not install revisions:\nNone", str(error))
153
def test_jail_break(self):
154
error = errors.JailBreak("some url")
155
self.assertEqualDiff("An attempt to access a url outside the server"
156
" jail was made: 'some url'.",
126
159
def test_lock_active(self):
127
160
error = errors.LockActive("lock description")
561
587
self.assertEquals(
562
588
"Server sent an unexpected error: ('error', 'tuple')", str(err))
590
def test_smart_message_handler_error(self):
591
# Make an exc_info tuple.
593
raise Exception("example error")
595
err = errors.SmartMessageHandlerError(sys.exc_info())
596
# GZ 2010-11-08: Should not store exc_info in exception instances.
598
self.assertStartsWith(
599
str(err), "The message handler raised an exception:\n")
600
self.assertEndsWith(str(err), "Exception: example error\n")
604
def test_must_have_working_tree(self):
605
err = errors.MustHaveWorkingTree('foo', 'bar')
606
self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
609
def test_no_such_view(self):
610
err = errors.NoSuchView('foo')
611
self.assertEquals("No such view: foo.", str(err))
613
def test_views_not_supported(self):
614
err = errors.ViewsNotSupported('atree')
616
self.assertStartsWith(err_str, "Views are not supported by ")
617
self.assertEndsWith(err_str, "; use 'bzr upgrade' to change your "
618
"tree to a later format.")
620
def test_file_outside_view(self):
621
err = errors.FileOutsideView('baz', ['foo', 'bar'])
622
self.assertEquals('Specified file "baz" is outside the current view: '
623
'foo, bar', str(err))
625
def test_invalid_shelf_id(self):
627
err = errors.InvalidShelfId(invalid_id)
628
self.assertEqual('"foo" is not a valid shelf id, '
629
'try a number instead.', str(err))
631
def test_unresumable_write_group(self):
633
wg_tokens = ['token']
635
err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
637
"Repository dummy repo cannot resume write group "
638
"['token']: a reason", str(err))
640
def test_unsuspendable_write_group(self):
642
err = errors.UnsuspendableWriteGroup(repo)
644
'Repository dummy repo cannot suspend a write group.', str(err))
646
def test_not_branch_no_args(self):
647
err = errors.NotBranchError('path')
648
self.assertEqual('Not a branch: "path".', str(err))
650
def test_not_branch_bzrdir_with_repo(self):
651
bzrdir = self.make_repository('repo').bzrdir
652
err = errors.NotBranchError('path', bzrdir=bzrdir)
654
'Not a branch: "path": location is a repository.', str(err))
656
def test_not_branch_bzrdir_without_repo(self):
657
bzrdir = self.make_bzrdir('bzrdir')
658
err = errors.NotBranchError('path', bzrdir=bzrdir)
659
self.assertEqual('Not a branch: "path".', str(err))
661
def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
662
class FakeBzrDir(object):
663
def open_repository(self):
664
# str() on the NotBranchError will trigger a call to this,
665
# which in turn will another, identical NotBranchError.
666
raise errors.NotBranchError('path', bzrdir=FakeBzrDir())
667
err = errors.NotBranchError('path', bzrdir=FakeBzrDir())
668
self.assertEqual('Not a branch: "path".', str(err))
670
def test_not_branch_laziness(self):
671
real_bzrdir = self.make_bzrdir('path')
672
class FakeBzrDir(object):
675
def open_repository(self):
676
self.calls.append('open_repository')
677
raise errors.NoRepositoryPresent(real_bzrdir)
678
fake_bzrdir = FakeBzrDir()
679
err = errors.NotBranchError('path', bzrdir=fake_bzrdir)
680
self.assertEqual([], fake_bzrdir.calls)
682
self.assertEqual(['open_repository'], fake_bzrdir.calls)
683
# Stringifying twice doesn't try to open a repository twice.
685
self.assertEqual(['open_repository'], fake_bzrdir.calls)
687
def test_invalid_pattern(self):
688
error = errors.InvalidPattern('Bad pattern msg.')
689
self.assertEqualDiff("Invalid pattern(s) found. Bad pattern msg.",
692
def test_recursive_bind(self):
693
error = errors.RecursiveBind('foo_bar_branch')
694
msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
695
'Please use `bzr unbind` to fix.')
696
self.assertEqualDiff(msg, str(error))
698
def test_retry_with_new_packs(self):
699
fake_exc_info = ('{exc type}', '{exc value}', '{exc traceback}')
700
error = errors.RetryWithNewPacks(
701
'{context}', reload_occurred=False, exc_info=fake_exc_info)
703
'Pack files have changed, reload and retry. context: '
704
'{context} {exc value}', str(error))
565
707
class PassThroughError(errors.BzrError):
567
709
_fmt = """Pass through %(foo)s and %(bar)s"""
569
711
def __init__(self, foo, bar):
607
745
e = ErrorWithBadFormat(not_thing='x')
608
746
self.assertStartsWith(
609
747
str(e), 'Unprintable exception ErrorWithBadFormat')
749
def test_cannot_bind_address(self):
750
# see <https://bugs.launchpad.net/bzr/+bug/286871>
751
e = errors.CannotBindAddress('example.com', 22,
752
socket.error(13, 'Permission denied'))
753
self.assertContainsRe(str(e),
754
r'Cannot bind address "example\.com:22":.*Permission denied')
756
def test_file_timestamp_unavailable(self):
757
e = errors.FileTimestampUnavailable("/path/foo")
758
self.assertEquals("The filestamp for /path/foo is not available.",
761
def test_transform_rename_failed(self):
762
e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
764
u"Failed to rename from to to: readonly file",