1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# 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
"""Tests for the formatting and construction of errors."""
31
from ..sixish import (
36
class TestErrors(tests.TestCase):
38
def test_no_arg_named_message(self):
39
"""Ensure the __init__ and _fmt in errors do not have "message" arg.
41
This test fails if __init__ or _fmt in errors has an argument
42
named "message" as this can cause errors in some Python versions.
43
Python 2.5 uses a slot for StandardError.message.
46
fmt_pattern = re.compile("%\(message\)[sir]")
47
for c in errors.BzrError.__subclasses__():
48
init = getattr(c, '__init__', None)
49
fmt = getattr(c, '_fmt', None)
51
args = inspect.getargspec(init)[0]
52
self.assertFalse('message' in args,
53
('Argument name "message" not allowed for '
54
'"errors.%s.__init__"' % c.__name__))
55
if fmt and fmt_pattern.search(fmt):
56
self.assertFalse(True, ('"message" not allowed in '
57
'"errors.%s._fmt"' % c.__name__))
59
def test_bad_filename_encoding(self):
60
error = errors.BadFilenameEncoding(b'bad/filen\xe5me', 'UTF-8')
61
self.assertContainsRe(
63
"^Filename b?'bad/filen\\\\xe5me' is not valid in your current"
64
" filesystem encoding UTF-8$")
66
def test_corrupt_dirstate(self):
67
error = errors.CorruptDirstate('path/to/dirstate', 'the reason why')
69
"Inconsistency in dirstate file path/to/dirstate.\n"
70
"Error: the reason why",
73
def test_dirstate_corrupt(self):
74
error = errors.DirstateCorrupt('.bzr/checkout/dirstate',
75
'trailing garbage: "x"')
76
self.assertEqualDiff("The dirstate file (.bzr/checkout/dirstate)"
77
" appears to be corrupt: trailing garbage: \"x\"",
80
def test_duplicate_file_id(self):
81
error = errors.DuplicateFileId('a_file_id', 'foo')
82
self.assertEqualDiff('File id {a_file_id} already exists in inventory'
83
' as foo', str(error))
85
def test_duplicate_help_prefix(self):
86
error = errors.DuplicateHelpPrefix('foo')
87
self.assertEqualDiff('The prefix foo is in the help search path twice.',
90
def test_ghost_revisions_have_no_revno(self):
91
error = errors.GhostRevisionsHaveNoRevno('target', 'ghost_rev')
92
self.assertEqualDiff("Could not determine revno for {target} because"
93
" its ancestry shows a ghost at {ghost_rev}",
96
def test_incompatibleVersion(self):
97
error = errors.IncompatibleVersion("module", [(4, 5, 6), (7, 8, 9)],
100
'API module is not compatible; one of versions '
101
'[(4, 5, 6), (7, 8, 9)] is required, but current version is '
105
def test_inconsistent_delta(self):
106
error = errors.InconsistentDelta('path', 'file-id', 'reason for foo')
107
self.assertEqualDiff(
108
"An inconsistent delta was supplied involving 'path', 'file-id'\n"
109
"reason: reason for foo",
112
def test_inconsistent_delta_delta(self):
113
error = errors.InconsistentDeltaDelta([], 'reason')
114
self.assertEqualDiff(
115
"An inconsistent delta was supplied: []\nreason: reason",
118
def test_in_process_transport(self):
119
error = errors.InProcessTransport('fpp')
120
self.assertEqualDiff(
121
"The transport 'fpp' is only accessible within this process.",
124
def test_invalid_http_range(self):
125
error = errors.InvalidHttpRange('path',
126
'Content-Range: potatoes 0-00/o0oo0',
128
self.assertEqual("Invalid http range"
129
" 'Content-Range: potatoes 0-00/o0oo0'"
130
" for path: bad range",
133
def test_invalid_range(self):
134
error = errors.InvalidRange('path', 12, 'bad range')
135
self.assertEqual("Invalid range access in path at 12: bad range",
138
def test_inventory_modified(self):
139
error = errors.InventoryModified("a tree to be repred")
140
self.assertEqualDiff("The current inventory for the tree 'a tree to "
141
"be repred' has been modified, so a clean inventory cannot be "
142
"read without data loss.",
145
def test_jail_break(self):
146
error = errors.JailBreak("some url")
147
self.assertEqualDiff("An attempt to access a url outside the server"
148
" jail was made: 'some url'.",
151
def test_lock_active(self):
152
error = errors.LockActive("lock description")
153
self.assertEqualDiff("The lock for 'lock description' is in use and "
157
def test_lock_corrupt(self):
158
error = errors.LockCorrupt("corruption info")
159
self.assertEqualDiff("Lock is apparently held, but corrupted: "
161
"Use 'brz break-lock' to clear it",
164
def test_knit_data_stream_incompatible(self):
165
error = errors.KnitDataStreamIncompatible(
166
'stream format', 'target format')
167
self.assertEqual('Cannot insert knit data stream of format '
168
'"stream format" into knit of format '
169
'"target format".', str(error))
171
def test_knit_data_stream_unknown(self):
172
error = errors.KnitDataStreamUnknown(
174
self.assertEqual('Cannot parse knit data stream of format '
175
'"stream format".', str(error))
177
def test_knit_header_error(self):
178
error = errors.KnitHeaderError('line foo\n', 'path/to/file')
179
self.assertEqual("Knit header error: 'line foo\\n' unexpected"
180
" for file \"path/to/file\".", str(error))
182
def test_knit_index_unknown_method(self):
183
error = errors.KnitIndexUnknownMethod('http://host/foo.kndx',
185
self.assertEqual("Knit index http://host/foo.kndx does not have a"
186
" known method in options: ['bad', 'no-eol']",
189
def test_medium_not_connected(self):
190
error = errors.MediumNotConnected("a medium")
191
self.assertEqualDiff(
192
"The medium 'a medium' is not connected.", str(error))
194
def test_no_smart_medium(self):
195
error = errors.NoSmartMedium("a transport")
196
self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
200
def test_no_such_id(self):
201
error = errors.NoSuchId("atree", "anid")
202
self.assertEqualDiff("The file id \"anid\" is not present in the tree "
206
def test_no_such_revision_in_tree(self):
207
error = errors.NoSuchRevisionInTree("atree", "anid")
208
self.assertEqualDiff("The revision id {anid} is not present in the"
209
" tree atree.", str(error))
210
self.assertIsInstance(error, errors.NoSuchRevision)
212
def test_not_stacked(self):
213
error = errors.NotStacked('a branch')
214
self.assertEqualDiff("The branch 'a branch' is not stacked.",
217
def test_not_write_locked(self):
218
error = errors.NotWriteLocked('a thing to repr')
219
self.assertEqualDiff("'a thing to repr' is not write locked but needs "
223
def test_lock_failed(self):
224
error = errors.LockFailed('http://canonical.com/', 'readonly transport')
225
self.assertEqualDiff("Cannot lock http://canonical.com/: readonly transport",
227
self.assertFalse(error.internal_error)
229
def test_too_many_concurrent_requests(self):
230
error = errors.TooManyConcurrentRequests("a medium")
231
self.assertEqualDiff("The medium 'a medium' has reached its concurrent "
232
"request limit. Be sure to finish_writing and finish_reading on "
233
"the currently open request.",
236
def test_unavailable_representation(self):
237
error = errors.UnavailableRepresentation(('key',), "mpdiff", "fulltext")
238
self.assertEqualDiff("The encoding 'mpdiff' is not available for key "
239
"('key',) which is encoded as 'fulltext'.",
242
def test_unknown_hook(self):
243
error = errors.UnknownHook("branch", "foo")
244
self.assertEqualDiff("The branch hook 'foo' is unknown in this version"
247
error = errors.UnknownHook("tree", "bar")
248
self.assertEqualDiff("The tree hook 'bar' is unknown in this version"
252
def test_unstackable_branch_format(self):
255
error = errors.UnstackableBranchFormat(format, url)
256
self.assertEqualDiff(
257
"The branch '/foo'(foo) is not a stackable format. "
258
"You will need to upgrade the branch to permit branch stacking.",
261
def test_unstackable_location(self):
262
error = errors.UnstackableLocationError('foo', 'bar')
263
self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
266
def test_unstackable_repository_format(self):
269
error = errors.UnstackableRepositoryFormat(format, url)
270
self.assertEqualDiff(
271
"The repository '/foo'(foo) is not a stackable format. "
272
"You will need to upgrade the repository to permit branch stacking.",
275
def test_up_to_date(self):
276
error = errors.UpToDateFormat("someformat")
277
self.assertEqualDiff(
278
"The branch format someformat is already at the most "
279
"recent format.", str(error))
281
def test_read_error(self):
282
# a unicode path to check that %r is being used.
284
error = errors.ReadError(path)
285
self.assertContainsRe(str(error), "^Error reading from u?'a path'.$")
287
def test_bad_index_format_signature(self):
288
error = errors.BadIndexFormatSignature("foo", "bar")
289
self.assertEqual("foo is not an index of type bar.",
292
def test_bad_index_data(self):
293
error = errors.BadIndexData("foo")
294
self.assertEqual("Error in data for index foo.",
297
def test_bad_index_duplicate_key(self):
298
error = errors.BadIndexDuplicateKey("foo", "bar")
299
self.assertEqual("The key 'foo' is already in index 'bar'.",
302
def test_bad_index_key(self):
303
error = errors.BadIndexKey("foo")
304
self.assertEqual("The key 'foo' is not a valid key.",
307
def test_bad_index_options(self):
308
error = errors.BadIndexOptions("foo")
309
self.assertEqual("Could not parse options for index foo.",
312
def test_bad_index_value(self):
313
error = errors.BadIndexValue("foo")
314
self.assertEqual("The value 'foo' is not a valid value.",
317
def test_bzrerror_from_literal_string(self):
318
# Some code constructs BzrError from a literal string, in which case
319
# no further formatting is done. (I'm not sure raising the base class
320
# is a great idea, but if the exception is not intended to be caught
321
# perhaps no more is needed.)
323
raise errors.BzrError('this is my errors; %d is not expanded')
324
except errors.BzrError as e:
325
self.assertEqual('this is my errors; %d is not expanded', str(e))
327
def test_reading_completed(self):
328
error = errors.ReadingCompleted("a request")
329
self.assertEqualDiff("The MediumRequest 'a request' has already had "
330
"finish_reading called upon it - the request has been completed and"
331
" no more data may be read.",
334
def test_writing_completed(self):
335
error = errors.WritingCompleted("a request")
336
self.assertEqualDiff("The MediumRequest 'a request' has already had "
337
"finish_writing called upon it - accept bytes may not be called "
341
def test_writing_not_completed(self):
342
error = errors.WritingNotComplete("a request")
343
self.assertEqualDiff("The MediumRequest 'a request' has not has "
344
"finish_writing called upon it - until the write phase is complete"
345
" no data may be read.",
348
def test_transport_not_possible(self):
349
error = errors.TransportNotPossible('readonly', 'original error')
350
self.assertEqualDiff('Transport operation not possible:'
351
' readonly original error', str(error))
353
def assertSocketConnectionError(self, expected, *args, **kwargs):
354
"""Check the formatting of a SocketConnectionError exception"""
355
e = errors.SocketConnectionError(*args, **kwargs)
356
self.assertEqual(expected, str(e))
358
def test_socket_connection_error(self):
359
"""Test the formatting of SocketConnectionError"""
361
# There should be a default msg about failing to connect
362
# we only require a host name.
363
self.assertSocketConnectionError(
364
'Failed to connect to ahost',
367
# If port is None, we don't put :None
368
self.assertSocketConnectionError(
369
'Failed to connect to ahost',
371
# But if port is supplied we include it
372
self.assertSocketConnectionError(
373
'Failed to connect to ahost:22',
376
# We can also supply extra information about the error
377
# with or without a port
378
self.assertSocketConnectionError(
379
'Failed to connect to ahost:22; bogus error',
380
'ahost', port=22, orig_error='bogus error')
381
self.assertSocketConnectionError(
382
'Failed to connect to ahost; bogus error',
383
'ahost', orig_error='bogus error')
384
# An exception object can be passed rather than a string
385
orig_error = ValueError('bad value')
386
self.assertSocketConnectionError(
387
'Failed to connect to ahost; %s' % (str(orig_error),),
388
host='ahost', orig_error=orig_error)
390
# And we can supply a custom failure message
391
self.assertSocketConnectionError(
392
'Unable to connect to ssh host ahost:444; my_error',
393
host='ahost', port=444, msg='Unable to connect to ssh host',
394
orig_error='my_error')
396
def test_target_not_branch(self):
397
"""Test the formatting of TargetNotBranch."""
398
error = errors.TargetNotBranch('foo')
400
"Your branch does not have all of the revisions required in "
401
"order to merge this merge directive and the target "
402
"location specified in the merge directive is not a branch: "
405
def test_unexpected_smart_server_response(self):
406
e = errors.UnexpectedSmartServerResponse(('not yes',))
408
"Could not understand response from smart server: ('not yes',)",
411
def test_unknown_container_format(self):
412
"""Test the formatting of UnknownContainerFormatError."""
413
e = errors.UnknownContainerFormatError('bad format string')
415
"Unrecognised container format: 'bad format string'",
418
def test_unexpected_end_of_container(self):
419
"""Test the formatting of UnexpectedEndOfContainerError."""
420
e = errors.UnexpectedEndOfContainerError()
422
"Unexpected end of container stream", str(e))
424
def test_unknown_record_type(self):
425
"""Test the formatting of UnknownRecordTypeError."""
426
e = errors.UnknownRecordTypeError("X")
428
"Unknown record type: 'X'",
431
def test_invalid_record(self):
432
"""Test the formatting of InvalidRecordError."""
433
e = errors.InvalidRecordError("xxx")
435
"Invalid record: xxx",
438
def test_container_has_excess_data(self):
439
"""Test the formatting of ContainerHasExcessDataError."""
440
e = errors.ContainerHasExcessDataError("excess bytes")
442
"Container has data after end marker: 'excess bytes'",
445
def test_duplicate_record_name_error(self):
446
"""Test the formatting of DuplicateRecordNameError."""
447
e = errors.DuplicateRecordNameError(b"n\xc3\xa5me")
449
u"Container has multiple records with the same name: n\xe5me",
452
def test_check_error(self):
453
e = errors.BzrCheckError('example check failure')
455
"Internal check failed: example check failure",
457
self.assertTrue(e.internal_error)
459
def test_repository_data_stream_error(self):
460
"""Test the formatting of RepositoryDataStreamError."""
461
e = errors.RepositoryDataStreamError(u"my reason")
463
"Corrupt or incompatible data stream: my reason", str(e))
465
def test_immortal_pending_deletion_message(self):
466
err = errors.ImmortalPendingDeletion('foo')
468
"Unable to delete transform temporary directory foo. "
469
"Please examine foo to see if it contains any files "
470
"you wish to keep, and delete it when you are done.",
473
def test_unable_create_symlink(self):
474
err = errors.UnableCreateSymlink()
476
"Unable to create symlink on this platform",
478
err = errors.UnableCreateSymlink(path=u'foo')
480
"Unable to create symlink 'foo' on this platform",
482
err = errors.UnableCreateSymlink(path=u'\xb5')
484
"Unable to create symlink %s on this platform" % repr(u'\xb5'),
487
def test_invalid_url_join(self):
488
"""Test the formatting of InvalidURLJoin."""
489
e = errors.InvalidURLJoin('Reason', 'base path', ('args',))
491
"Invalid URL join request: Reason: 'base path' + ('args',)",
494
def test_unable_encode_path(self):
495
err = errors.UnableEncodePath('foo', 'executable')
496
self.assertEqual("Unable to encode executable path 'foo' in "
497
"user encoding " + osutils.get_user_encoding(),
500
def test_unknown_format(self):
501
err = errors.UnknownFormatError('bar', kind='foo')
502
self.assertEqual("Unknown foo format: 'bar'", str(err))
504
def test_unknown_rules(self):
505
err = errors.UnknownRules(['foo', 'bar'])
506
self.assertEqual("Unknown rules detected: foo, bar.", str(err))
508
def test_tip_change_rejected(self):
509
err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
511
u'Tip change rejected: Unicode message\N{INTERROBANG}',
514
def test_error_from_smart_server(self):
515
error_tuple = ('error', 'tuple')
516
err = errors.ErrorFromSmartServer(error_tuple)
518
"Error received from smart server: ('error', 'tuple')", str(err))
520
def test_untranslateable_error_from_smart_server(self):
521
error_tuple = ('error', 'tuple')
522
orig_err = errors.ErrorFromSmartServer(error_tuple)
523
err = errors.UnknownErrorFromSmartServer(orig_err)
525
"Server sent an unexpected error: ('error', 'tuple')", str(err))
527
def test_smart_message_handler_error(self):
528
# Make an exc_info tuple.
530
raise Exception("example error")
532
err = errors.SmartMessageHandlerError(sys.exc_info())
533
# GZ 2010-11-08: Should not store exc_info in exception instances.
535
self.assertStartsWith(
536
str(err), "The message handler raised an exception:\n")
537
self.assertEndsWith(str(err), "Exception: example error\n")
541
def test_must_have_working_tree(self):
542
err = errors.MustHaveWorkingTree('foo', 'bar')
543
self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
546
def test_unresumable_write_group(self):
548
wg_tokens = ['token']
550
err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
552
"Repository dummy repo cannot resume write group "
553
"['token']: a reason", str(err))
555
def test_unsuspendable_write_group(self):
557
err = errors.UnsuspendableWriteGroup(repo)
559
'Repository dummy repo cannot suspend a write group.', str(err))
561
def test_not_branch_no_args(self):
562
err = errors.NotBranchError('path')
563
self.assertEqual('Not a branch: "path".', str(err))
565
def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
566
class FakeBzrDir(object):
567
def open_repository(self):
568
# str() on the NotBranchError will trigger a call to this,
569
# which in turn will another, identical NotBranchError.
570
raise errors.NotBranchError('path', controldir=FakeBzrDir())
571
err = errors.NotBranchError('path', controldir=FakeBzrDir())
572
self.assertEqual('Not a branch: "path": NotBranchError.', str(err))
574
def test_recursive_bind(self):
575
error = errors.RecursiveBind('foo_bar_branch')
576
msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
577
'Please use `brz unbind` to fix.')
578
self.assertEqualDiff(msg, str(error))
580
def test_retry_with_new_packs(self):
581
fake_exc_info = ('{exc type}', '{exc value}', '{exc traceback}')
582
error = errors.RetryWithNewPacks(
583
'{context}', reload_occurred=False, exc_info=fake_exc_info)
585
'Pack files have changed, reload and retry. context: '
586
'{context} {exc value}', str(error))
589
class PassThroughError(errors.BzrError):
591
_fmt = """Pass through %(foo)s and %(bar)s"""
593
def __init__(self, foo, bar):
594
errors.BzrError.__init__(self, foo=foo, bar=bar)
597
class ErrorWithBadFormat(errors.BzrError):
599
_fmt = """One format specifier: %(thing)s"""
602
class ErrorWithNoFormat(errors.BzrError):
603
__doc__ = """This class has a docstring but no format string."""
606
class TestErrorFormatting(tests.TestCase):
608
def test_always_str(self):
609
e = PassThroughError(u'\xb5', 'bar')
610
self.assertIsInstance(e.__str__(), str)
611
# In Python str(foo) *must* return a real byte string
612
# not a Unicode string. The following line would raise a
613
# Unicode error, because it tries to call str() on the string
614
# returned from e.__str__(), and it has non ascii characters
616
self.assertEqual('Pass through \xc2\xb5 and bar', s)
618
def test_missing_format_string(self):
619
e = ErrorWithNoFormat(param='randomvalue')
620
self.assertStartsWith(str(e),
621
"Unprintable exception ErrorWithNoFormat")
623
def test_mismatched_format_args(self):
624
# Even though ErrorWithBadFormat's format string does not match the
625
# arguments we constructing it with, we can still stringify an instance
626
# of this exception. The resulting string will say its unprintable.
627
e = ErrorWithBadFormat(not_thing='x')
628
self.assertStartsWith(
629
str(e), 'Unprintable exception ErrorWithBadFormat')
631
def test_cannot_bind_address(self):
632
# see <https://bugs.launchpad.net/bzr/+bug/286871>
633
e = errors.CannotBindAddress('example.com', 22,
634
socket.error(13, 'Permission denied'))
635
self.assertContainsRe(
637
r'Cannot bind address "example\.com:22":.*Permission denied')
639
def test_transform_rename_failed(self):
640
e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
642
u"Failed to rename from to to: readonly file",
646
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
647
"""Tests for errors that need to use a branch or repo."""
649
def test_no_public_branch(self):
650
b = self.make_branch('.')
651
error = errors.NoPublicBranch(b)
652
url = urlutils.unescape_for_display(b.base, 'ascii')
653
self.assertEqualDiff(
654
'There is no public branch set for "%s".' % url, str(error))
656
def test_no_repo(self):
657
dir = controldir.ControlDir.create(self.get_url())
658
error = errors.NoRepositoryPresent(dir)
659
self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
660
self.assertEqual(-1, str(error).find((dir.transport.base)))
662
def test_corrupt_repository(self):
663
repo = self.make_repository('.')
664
error = errors.CorruptRepository(repo)
665
self.assertEqualDiff("An error has been detected in the repository %s.\n"
666
"Please run brz reconcile on this repository." %
667
repo.controldir.root_transport.base,
670
def test_not_branch_bzrdir_with_repo(self):
671
controldir = self.make_repository('repo').controldir
672
err = errors.NotBranchError('path', controldir=controldir)
674
'Not a branch: "path": location is a repository.', str(err))
676
def test_not_branch_bzrdir_without_repo(self):
677
controldir = self.make_controldir('bzrdir')
678
err = errors.NotBranchError('path', controldir=controldir)
679
self.assertEqual('Not a branch: "path".', str(err))
681
def test_not_branch_laziness(self):
682
real_bzrdir = self.make_controldir('path')
683
class FakeBzrDir(object):
686
def open_repository(self):
687
self.calls.append('open_repository')
688
raise errors.NoRepositoryPresent(real_bzrdir)
689
fake_bzrdir = FakeBzrDir()
690
err = errors.NotBranchError('path', controldir=fake_bzrdir)
691
self.assertEqual([], fake_bzrdir.calls)
693
self.assertEqual(['open_repository'], fake_bzrdir.calls)
694
# Stringifying twice doesn't try to open a repository twice.
696
self.assertEqual(['open_repository'], fake_bzrdir.calls)