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."""
21
24
from bzrlib import (
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.
31
from bzrlib.tests import TestCase, TestCaseWithTransport, TestSkipped
32
34
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\"",
34
82
def test_disabled_method(self):
35
83
error = errors.DisabledMethod("class name")
36
84
self.assertEqualDiff(
53
107
'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",
56
123
def test_in_process_transport(self):
57
124
error = errors.InProcessTransport('fpp')
58
125
self.assertEqualDiff(
59
126
"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",
62
143
def test_inventory_modified(self):
63
144
error = errors.InventoryModified("a tree to be repred")
64
145
self.assertEqualDiff("The current inventory for the tree 'a tree to "
362
505
"Container has multiple records with the same name: n\xc3\xa5me",
508
def test_check_error(self):
509
# This has a member called 'message', which is problematic in
510
# python2.5 because that is a slot on the base Exception class
511
e = errors.BzrCheckError('example check failure')
513
"Internal check failed: example check failure",
515
self.assertTrue(e.internal_error)
517
def test_repository_data_stream_error(self):
518
"""Test the formatting of RepositoryDataStreamError."""
519
e = errors.RepositoryDataStreamError(u"my reason")
521
"Corrupt or incompatible data stream: my reason", str(e))
523
def test_immortal_pending_deletion_message(self):
524
err = errors.ImmortalPendingDeletion('foo')
526
"Unable to delete transform temporary directory foo. "
527
"Please examine foo to see if it contains any files "
528
"you wish to keep, and delete it when you are done.",
531
def test_unable_create_symlink(self):
532
err = errors.UnableCreateSymlink()
534
"Unable to create symlink on this platform",
536
err = errors.UnableCreateSymlink(path=u'foo')
538
"Unable to create symlink 'foo' on this platform",
540
err = errors.UnableCreateSymlink(path=u'\xb5')
542
"Unable to create symlink u'\\xb5' on this platform",
545
def test_invalid_url_join(self):
546
"""Test the formatting of InvalidURLJoin."""
547
e = errors.InvalidURLJoin('Reason', 'base path', ('args',))
549
"Invalid URL join request: Reason: 'base path' + ('args',)",
552
def test_incorrect_url(self):
553
err = errors.InvalidBugTrackerURL('foo', 'http://bug.com/')
555
("The URL for bug tracker \"foo\" doesn't contain {id}: "
559
def test_unable_encode_path(self):
560
err = errors.UnableEncodePath('foo', 'executable')
561
self.assertEquals("Unable to encode executable path 'foo' in "
562
"user encoding " + osutils.get_user_encoding(),
565
def test_unknown_format(self):
566
err = errors.UnknownFormatError('bar', kind='foo')
567
self.assertEquals("Unknown foo format: 'bar'", str(err))
569
def test_unknown_rules(self):
570
err = errors.UnknownRules(['foo', 'bar'])
571
self.assertEquals("Unknown rules detected: foo, bar.", str(err))
573
def test_hook_failed(self):
574
# Create an exc_info tuple by raising and catching an exception.
577
except ZeroDivisionError:
578
exc_info = sys.exc_info()
579
err = errors.HookFailed('hook stage', 'hook name', exc_info, warn=False)
580
self.assertStartsWith(
581
str(err), 'Hook \'hook name\' during hook stage failed:\n')
583
str(err), 'integer division or modulo by zero')
585
def test_tip_change_rejected(self):
586
err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
588
u'Tip change rejected: Unicode message\N{INTERROBANG}',
591
'Tip change rejected: Unicode message\xe2\x80\xbd',
594
def test_error_from_smart_server(self):
595
error_tuple = ('error', 'tuple')
596
err = errors.ErrorFromSmartServer(error_tuple)
598
"Error received from smart server: ('error', 'tuple')", str(err))
600
def test_untranslateable_error_from_smart_server(self):
601
error_tuple = ('error', 'tuple')
602
orig_err = errors.ErrorFromSmartServer(error_tuple)
603
err = errors.UnknownErrorFromSmartServer(orig_err)
605
"Server sent an unexpected error: ('error', 'tuple')", str(err))
607
def test_smart_message_handler_error(self):
608
# Make an exc_info tuple.
610
raise Exception("example error")
612
exc_info = sys.exc_info()
613
err = errors.SmartMessageHandlerError(exc_info)
614
self.assertStartsWith(
615
str(err), "The message handler raised an exception:\n")
616
self.assertEndsWith(str(err), "Exception: example error\n")
618
def test_must_have_working_tree(self):
619
err = errors.MustHaveWorkingTree('foo', 'bar')
620
self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
623
def test_no_such_view(self):
624
err = errors.NoSuchView('foo')
625
self.assertEquals("No such view: foo.", str(err))
627
def test_views_not_supported(self):
628
err = errors.ViewsNotSupported('atree')
630
self.assertStartsWith(err_str, "Views are not supported by ")
631
self.assertEndsWith(err_str, "; use 'bzr upgrade' to change your "
632
"tree to a later format.")
634
def test_file_outside_view(self):
635
err = errors.FileOutsideView('baz', ['foo', 'bar'])
636
self.assertEquals('Specified file "baz" is outside the current view: '
637
'foo, bar', str(err))
639
def test_invalid_shelf_id(self):
641
err = errors.InvalidShelfId(invalid_id)
642
self.assertEqual('"foo" is not a valid shelf id, '
643
'try a number instead.', str(err))
645
def test_unresumable_write_group(self):
647
wg_tokens = ['token']
649
err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
651
"Repository dummy repo cannot resume write group "
652
"['token']: a reason", str(err))
654
def test_unsuspendable_write_group(self):
656
err = errors.UnsuspendableWriteGroup(repo)
658
'Repository dummy repo cannot suspend a write group.', str(err))
660
def test_not_branch_no_args(self):
661
err = errors.NotBranchError('path')
662
self.assertEqual('Not a branch: "path".', str(err))
664
def test_not_branch_bzrdir_with_repo(self):
665
bzrdir = self.make_repository('repo').bzrdir
666
err = errors.NotBranchError('path', bzrdir=bzrdir)
668
'Not a branch: "path": location is a repository.', str(err))
670
def test_not_branch_bzrdir_without_repo(self):
671
bzrdir = self.make_bzrdir('bzrdir')
672
err = errors.NotBranchError('path', bzrdir=bzrdir)
673
self.assertEqual('Not a branch: "path".', str(err))
675
def test_not_branch_laziness(self):
676
real_bzrdir = self.make_bzrdir('path')
677
class FakeBzrDir(object):
680
def open_repository(self):
681
self.calls.append('open_repository')
682
raise errors.NoRepositoryPresent(real_bzrdir)
683
fake_bzrdir = FakeBzrDir()
684
err = errors.NotBranchError('path', bzrdir=fake_bzrdir)
685
self.assertEqual([], fake_bzrdir.calls)
687
self.assertEqual(['open_repository'], fake_bzrdir.calls)
688
# Stringifying twice doesn't try to open a repository twice.
690
self.assertEqual(['open_repository'], fake_bzrdir.calls)
692
def test_invalid_pattern(self):
693
error = errors.InvalidPattern('Bad pattern msg.')
694
self.assertEqualDiff("Invalid pattern(s) found. Bad pattern msg.",
697
def test_recursive_bind(self):
698
error = errors.RecursiveBind('foo_bar_branch')
699
msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
700
'Please use `bzr unbind` to fix.')
701
self.assertEqualDiff(msg, str(error))
366
704
class PassThroughError(errors.BzrError):
368
706
_fmt = """Pass through %(foo)s and %(bar)s"""
370
708
def __init__(self, foo, bar):