13
15
# You should have received a copy of the GNU General Public License
14
16
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
19
"""Tests for the formatting and construction of errors."""
24
21
from bzrlib import (
31
from bzrlib.tests import TestCase, TestCaseWithTransport, TestSkipped
25
from bzrlib.tests import TestCase, TestCaseWithTransport
28
# TODO: Make sure builtin exception class formats are consistent - e.g. should
29
# or shouldn't end with a full stop, etc.
34
32
class TestErrors(TestCaseWithTransport):
36
def test_no_arg_named_message(self):
37
"""Ensure the __init__ and _fmt in errors do not have "message" arg.
39
This test fails if __init__ or _fmt in errors has an argument
40
named "message" as this can cause errors in some Python versions.
41
Python 2.5 uses a slot for StandardError.message.
44
fmt_pattern = re.compile("%\(message\)[sir]")
45
subclasses_present = getattr(errors.BzrError, '__subclasses__', None)
46
if not subclasses_present:
47
raise TestSkipped('__subclasses__ attribute required for classes. '
48
'Requires Python 2.5 or later.')
49
for c in errors.BzrError.__subclasses__():
50
init = getattr(c, '__init__', None)
51
fmt = getattr(c, '_fmt', None)
53
args = inspect.getargspec(init)[0]
54
self.assertFalse('message' in args,
55
('Argument name "message" not allowed for '
56
'"errors.%s.__init__"' % c.__name__))
57
if fmt and fmt_pattern.search(fmt):
58
self.assertFalse(True, ('"message" not allowed in '
59
'"errors.%s._fmt"' % c.__name__))
61
def test_bad_filename_encoding(self):
62
error = errors.BadFilenameEncoding('bad/filen\xe5me', 'UTF-8')
64
"Filename 'bad/filen\\xe5me' is not valid in your current"
65
" filesystem encoding UTF-8",
68
def test_corrupt_dirstate(self):
69
error = errors.CorruptDirstate('path/to/dirstate', 'the reason why')
71
"Inconsistency in dirstate file path/to/dirstate.\n"
72
"Error: the reason why",
75
def test_dirstate_corrupt(self):
76
error = errors.DirstateCorrupt('.bzr/checkout/dirstate',
77
'trailing garbage: "x"')
78
self.assertEqualDiff("The dirstate file (.bzr/checkout/dirstate)"
79
" appears to be corrupt: trailing garbage: \"x\"",
82
34
def test_disabled_method(self):
83
35
error = errors.DisabledMethod("class name")
84
36
self.assertEqualDiff(
107
53
'It supports versions "(4, 5, 6)" to "(7, 8, 9)".',
110
def test_inconsistent_delta(self):
111
error = errors.InconsistentDelta('path', 'file-id', 'reason for foo')
112
self.assertEqualDiff(
113
"An inconsistent delta was supplied involving 'path', 'file-id'\n"
114
"reason: reason for foo",
117
def test_inconsistent_delta_delta(self):
118
error = errors.InconsistentDeltaDelta([], 'reason')
119
self.assertEqualDiff(
120
"An inconsistent delta was supplied: []\nreason: reason",
123
56
def test_in_process_transport(self):
124
57
error = errors.InProcessTransport('fpp')
125
58
self.assertEqualDiff(
126
59
"The transport 'fpp' is only accessible within this process.",
129
def test_invalid_http_range(self):
130
error = errors.InvalidHttpRange('path',
131
'Content-Range: potatoes 0-00/o0oo0',
133
self.assertEquals("Invalid http range"
134
" 'Content-Range: potatoes 0-00/o0oo0'"
135
" for path: bad range",
138
def test_invalid_range(self):
139
error = errors.InvalidRange('path', 12, 'bad range')
140
self.assertEquals("Invalid range access in path at 12: bad range",
143
62
def test_inventory_modified(self):
144
63
error = errors.InventoryModified("a tree to be repred")
145
64
self.assertEqualDiff("The current inventory for the tree 'a tree to "
498
362
"Container has multiple records with the same name: n\xc3\xa5me",
501
def test_check_error(self):
502
# This has a member called 'message', which is problematic in
503
# python2.5 because that is a slot on the base Exception class
504
e = errors.BzrCheckError('example check failure')
506
"Internal check failed: example check failure",
508
self.assertTrue(e.internal_error)
510
def test_repository_data_stream_error(self):
511
"""Test the formatting of RepositoryDataStreamError."""
512
e = errors.RepositoryDataStreamError(u"my reason")
514
"Corrupt or incompatible data stream: my reason", str(e))
516
def test_immortal_pending_deletion_message(self):
517
err = errors.ImmortalPendingDeletion('foo')
519
"Unable to delete transform temporary directory foo. "
520
"Please examine foo to see if it contains any files "
521
"you wish to keep, and delete it when you are done.",
524
def test_unable_create_symlink(self):
525
err = errors.UnableCreateSymlink()
527
"Unable to create symlink on this platform",
529
err = errors.UnableCreateSymlink(path=u'foo')
531
"Unable to create symlink 'foo' on this platform",
533
err = errors.UnableCreateSymlink(path=u'\xb5')
535
"Unable to create symlink u'\\xb5' on this platform",
538
def test_invalid_url_join(self):
539
"""Test the formatting of InvalidURLJoin."""
540
e = errors.InvalidURLJoin('Reason', 'base path', ('args',))
542
"Invalid URL join request: Reason: 'base path' + ('args',)",
545
def test_incorrect_url(self):
546
err = errors.InvalidBugTrackerURL('foo', 'http://bug.com/')
548
("The URL for bug tracker \"foo\" doesn't contain {id}: "
552
def test_unable_encode_path(self):
553
err = errors.UnableEncodePath('foo', 'executable')
554
self.assertEquals("Unable to encode executable path 'foo' in "
555
"user encoding " + osutils.get_user_encoding(),
558
def test_unknown_format(self):
559
err = errors.UnknownFormatError('bar', kind='foo')
560
self.assertEquals("Unknown foo format: 'bar'", str(err))
562
def test_unknown_rules(self):
563
err = errors.UnknownRules(['foo', 'bar'])
564
self.assertEquals("Unknown rules detected: foo, bar.", str(err))
566
def test_hook_failed(self):
567
# Create an exc_info tuple by raising and catching an exception.
570
except ZeroDivisionError:
571
exc_info = sys.exc_info()
572
err = errors.HookFailed('hook stage', 'hook name', exc_info, warn=False)
573
self.assertStartsWith(
574
str(err), 'Hook \'hook name\' during hook stage failed:\n')
576
str(err), 'integer division or modulo by zero')
578
def test_tip_change_rejected(self):
579
err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
581
u'Tip change rejected: Unicode message\N{INTERROBANG}',
584
'Tip change rejected: Unicode message\xe2\x80\xbd',
587
def test_error_from_smart_server(self):
588
error_tuple = ('error', 'tuple')
589
err = errors.ErrorFromSmartServer(error_tuple)
591
"Error received from smart server: ('error', 'tuple')", str(err))
593
def test_untranslateable_error_from_smart_server(self):
594
error_tuple = ('error', 'tuple')
595
orig_err = errors.ErrorFromSmartServer(error_tuple)
596
err = errors.UnknownErrorFromSmartServer(orig_err)
598
"Server sent an unexpected error: ('error', 'tuple')", str(err))
600
def test_smart_message_handler_error(self):
601
# Make an exc_info tuple.
603
raise Exception("example error")
605
exc_info = sys.exc_info()
606
err = errors.SmartMessageHandlerError(exc_info)
607
self.assertStartsWith(
608
str(err), "The message handler raised an exception:\n")
609
self.assertEndsWith(str(err), "Exception: example error\n")
611
def test_must_have_working_tree(self):
612
err = errors.MustHaveWorkingTree('foo', 'bar')
613
self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
616
def test_no_such_view(self):
617
err = errors.NoSuchView('foo')
618
self.assertEquals("No such view: foo.", str(err))
620
def test_views_not_supported(self):
621
err = errors.ViewsNotSupported('atree')
623
self.assertStartsWith(err_str, "Views are not supported by ")
624
self.assertEndsWith(err_str, "; use 'bzr upgrade' to change your "
625
"tree to a later format.")
627
def test_file_outside_view(self):
628
err = errors.FileOutsideView('baz', ['foo', 'bar'])
629
self.assertEquals('Specified file "baz" is outside the current view: '
630
'foo, bar', str(err))
632
def test_invalid_shelf_id(self):
634
err = errors.InvalidShelfId(invalid_id)
635
self.assertEqual('"foo" is not a valid shelf id, '
636
'try a number instead.', str(err))
638
def test_unresumable_write_group(self):
640
wg_tokens = ['token']
642
err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
644
"Repository dummy repo cannot resume write group "
645
"['token']: a reason", str(err))
647
def test_unsuspendable_write_group(self):
649
err = errors.UnsuspendableWriteGroup(repo)
651
'Repository dummy repo cannot suspend a write group.', str(err))
653
def test_not_branch_no_args(self):
654
err = errors.NotBranchError('path')
655
self.assertEqual('Not a branch: "path".', str(err))
657
def test_not_branch_bzrdir_with_repo(self):
658
bzrdir = self.make_repository('repo').bzrdir
659
err = errors.NotBranchError('path', bzrdir=bzrdir)
661
'Not a branch: "path": location is a repository.', str(err))
663
def test_not_branch_bzrdir_without_repo(self):
664
bzrdir = self.make_bzrdir('bzrdir')
665
err = errors.NotBranchError('path', bzrdir=bzrdir)
666
self.assertEqual('Not a branch: "path".', str(err))
668
def test_not_branch_laziness(self):
669
real_bzrdir = self.make_bzrdir('path')
670
class FakeBzrDir(object):
673
def open_repository(self):
674
self.calls.append('open_repository')
675
raise errors.NoRepositoryPresent(real_bzrdir)
676
fake_bzrdir = FakeBzrDir()
677
err = errors.NotBranchError('path', bzrdir=fake_bzrdir)
678
self.assertEqual([], fake_bzrdir.calls)
680
self.assertEqual(['open_repository'], fake_bzrdir.calls)
681
# Stringifying twice doesn't try to open a repository twice.
683
self.assertEqual(['open_repository'], fake_bzrdir.calls)
685
def test_invalid_pattern(self):
686
error = errors.InvalidPattern('Bad pattern msg.')
687
self.assertEqualDiff("Invalid pattern(s) found. Bad pattern msg.",
690
def test_recursive_bind(self):
691
error = errors.RecursiveBind('foo_bar_branch')
692
msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
693
'Please use `bzr unbind` to fix.')
694
self.assertEqualDiff(msg, str(error))
697
366
class PassThroughError(errors.BzrError):
699
368
_fmt = """Pass through %(foo)s and %(bar)s"""
701
370
def __init__(self, foo, bar):