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_duplicate_file_id(self):
67
error = errors.DuplicateFileId('a_file_id', 'foo')
68
self.assertEqualDiff('File id {a_file_id} already exists in inventory'
69
' as foo', str(error))
71
def test_duplicate_help_prefix(self):
72
error = errors.DuplicateHelpPrefix('foo')
73
self.assertEqualDiff('The prefix foo is in the help search path twice.',
76
def test_ghost_revisions_have_no_revno(self):
77
error = errors.GhostRevisionsHaveNoRevno('target', 'ghost_rev')
78
self.assertEqualDiff("Could not determine revno for {target} because"
79
" its ancestry shows a ghost at {ghost_rev}",
82
def test_incompatibleVersion(self):
83
error = errors.IncompatibleVersion("module", [(4, 5, 6), (7, 8, 9)],
86
'API module is not compatible; one of versions '
87
'[(4, 5, 6), (7, 8, 9)] is required, but current version is '
91
def test_inconsistent_delta(self):
92
error = errors.InconsistentDelta('path', 'file-id', 'reason for foo')
94
"An inconsistent delta was supplied involving 'path', 'file-id'\n"
95
"reason: reason for foo",
98
def test_inconsistent_delta_delta(self):
99
error = errors.InconsistentDeltaDelta([], 'reason')
100
self.assertEqualDiff(
101
"An inconsistent delta was supplied: []\nreason: reason",
104
def test_in_process_transport(self):
105
error = errors.InProcessTransport('fpp')
106
self.assertEqualDiff(
107
"The transport 'fpp' is only accessible within this process.",
110
def test_invalid_http_range(self):
111
error = errors.InvalidHttpRange('path',
112
'Content-Range: potatoes 0-00/o0oo0',
114
self.assertEqual("Invalid http range"
115
" 'Content-Range: potatoes 0-00/o0oo0'"
116
" for path: bad range",
119
def test_invalid_range(self):
120
error = errors.InvalidRange('path', 12, 'bad range')
121
self.assertEqual("Invalid range access in path at 12: bad range",
124
def test_inventory_modified(self):
125
error = errors.InventoryModified("a tree to be repred")
126
self.assertEqualDiff("The current inventory for the tree 'a tree to "
127
"be repred' has been modified, so a clean inventory cannot be "
128
"read without data loss.",
131
def test_jail_break(self):
132
error = errors.JailBreak("some url")
133
self.assertEqualDiff("An attempt to access a url outside the server"
134
" jail was made: 'some url'.",
137
def test_lock_active(self):
138
error = errors.LockActive("lock description")
139
self.assertEqualDiff("The lock for 'lock description' is in use and "
143
def test_lock_corrupt(self):
144
error = errors.LockCorrupt("corruption info")
145
self.assertEqualDiff("Lock is apparently held, but corrupted: "
147
"Use 'brz break-lock' to clear it",
150
def test_medium_not_connected(self):
151
error = errors.MediumNotConnected("a medium")
152
self.assertEqualDiff(
153
"The medium 'a medium' is not connected.", str(error))
155
def test_no_smart_medium(self):
156
error = errors.NoSmartMedium("a transport")
157
self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
161
def test_no_such_id(self):
162
error = errors.NoSuchId("atree", "anid")
163
self.assertEqualDiff("The file id \"anid\" is not present in the tree "
167
def test_no_such_revision_in_tree(self):
168
error = errors.NoSuchRevisionInTree("atree", "anid")
169
self.assertEqualDiff("The revision id {anid} is not present in the"
170
" tree atree.", str(error))
171
self.assertIsInstance(error, errors.NoSuchRevision)
173
def test_not_stacked(self):
174
error = errors.NotStacked('a branch')
175
self.assertEqualDiff("The branch 'a branch' is not stacked.",
178
def test_not_write_locked(self):
179
error = errors.NotWriteLocked('a thing to repr')
180
self.assertEqualDiff("'a thing to repr' is not write locked but needs "
184
def test_lock_failed(self):
185
error = errors.LockFailed('http://canonical.com/', 'readonly transport')
186
self.assertEqualDiff("Cannot lock http://canonical.com/: readonly transport",
188
self.assertFalse(error.internal_error)
190
def test_too_many_concurrent_requests(self):
191
error = errors.TooManyConcurrentRequests("a medium")
192
self.assertEqualDiff("The medium 'a medium' has reached its concurrent "
193
"request limit. Be sure to finish_writing and finish_reading on "
194
"the currently open request.",
197
def test_unavailable_representation(self):
198
error = errors.UnavailableRepresentation(('key',), "mpdiff", "fulltext")
199
self.assertEqualDiff("The encoding 'mpdiff' is not available for key "
200
"('key',) which is encoded as 'fulltext'.",
203
def test_unstackable_location(self):
204
error = errors.UnstackableLocationError('foo', 'bar')
205
self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
208
def test_unstackable_repository_format(self):
211
error = errors.UnstackableRepositoryFormat(format, url)
212
self.assertEqualDiff(
213
"The repository '/foo'(foo) is not a stackable format. "
214
"You will need to upgrade the repository to permit branch stacking.",
217
def test_up_to_date(self):
218
error = errors.UpToDateFormat("someformat")
219
self.assertEqualDiff(
220
"The branch format someformat is already at the most "
221
"recent format.", str(error))
223
def test_read_error(self):
224
# a unicode path to check that %r is being used.
226
error = errors.ReadError(path)
227
self.assertContainsRe(str(error), "^Error reading from u?'a path'.$")
229
def test_bzrerror_from_literal_string(self):
230
# Some code constructs BzrError from a literal string, in which case
231
# no further formatting is done. (I'm not sure raising the base class
232
# is a great idea, but if the exception is not intended to be caught
233
# perhaps no more is needed.)
235
raise errors.BzrError('this is my errors; %d is not expanded')
236
except errors.BzrError as e:
237
self.assertEqual('this is my errors; %d is not expanded', str(e))
239
def test_reading_completed(self):
240
error = errors.ReadingCompleted("a request")
241
self.assertEqualDiff("The MediumRequest 'a request' has already had "
242
"finish_reading called upon it - the request has been completed and"
243
" no more data may be read.",
246
def test_writing_completed(self):
247
error = errors.WritingCompleted("a request")
248
self.assertEqualDiff("The MediumRequest 'a request' has already had "
249
"finish_writing called upon it - accept bytes may not be called "
253
def test_writing_not_completed(self):
254
error = errors.WritingNotComplete("a request")
255
self.assertEqualDiff("The MediumRequest 'a request' has not has "
256
"finish_writing called upon it - until the write phase is complete"
257
" no data may be read.",
260
def test_transport_not_possible(self):
261
error = errors.TransportNotPossible('readonly', 'original error')
262
self.assertEqualDiff('Transport operation not possible:'
263
' readonly original error', str(error))
265
def assertSocketConnectionError(self, expected, *args, **kwargs):
266
"""Check the formatting of a SocketConnectionError exception"""
267
e = errors.SocketConnectionError(*args, **kwargs)
268
self.assertEqual(expected, str(e))
270
def test_socket_connection_error(self):
271
"""Test the formatting of SocketConnectionError"""
273
# There should be a default msg about failing to connect
274
# we only require a host name.
275
self.assertSocketConnectionError(
276
'Failed to connect to ahost',
279
# If port is None, we don't put :None
280
self.assertSocketConnectionError(
281
'Failed to connect to ahost',
283
# But if port is supplied we include it
284
self.assertSocketConnectionError(
285
'Failed to connect to ahost:22',
288
# We can also supply extra information about the error
289
# with or without a port
290
self.assertSocketConnectionError(
291
'Failed to connect to ahost:22; bogus error',
292
'ahost', port=22, orig_error='bogus error')
293
self.assertSocketConnectionError(
294
'Failed to connect to ahost; bogus error',
295
'ahost', orig_error='bogus error')
296
# An exception object can be passed rather than a string
297
orig_error = ValueError('bad value')
298
self.assertSocketConnectionError(
299
'Failed to connect to ahost; %s' % (str(orig_error),),
300
host='ahost', orig_error=orig_error)
302
# And we can supply a custom failure message
303
self.assertSocketConnectionError(
304
'Unable to connect to ssh host ahost:444; my_error',
305
host='ahost', port=444, msg='Unable to connect to ssh host',
306
orig_error='my_error')
308
def test_target_not_branch(self):
309
"""Test the formatting of TargetNotBranch."""
310
error = errors.TargetNotBranch('foo')
312
"Your branch does not have all of the revisions required in "
313
"order to merge this merge directive and the target "
314
"location specified in the merge directive is not a branch: "
317
def test_unexpected_smart_server_response(self):
318
e = errors.UnexpectedSmartServerResponse(('not yes',))
320
"Could not understand response from smart server: ('not yes',)",
323
def test_unknown_container_format(self):
324
"""Test the formatting of UnknownContainerFormatError."""
325
e = errors.UnknownContainerFormatError('bad format string')
327
"Unrecognised container format: 'bad format string'",
330
def test_unexpected_end_of_container(self):
331
"""Test the formatting of UnexpectedEndOfContainerError."""
332
e = errors.UnexpectedEndOfContainerError()
334
"Unexpected end of container stream", str(e))
336
def test_unknown_record_type(self):
337
"""Test the formatting of UnknownRecordTypeError."""
338
e = errors.UnknownRecordTypeError("X")
340
"Unknown record type: 'X'",
343
def test_invalid_record(self):
344
"""Test the formatting of InvalidRecordError."""
345
e = errors.InvalidRecordError("xxx")
347
"Invalid record: xxx",
350
def test_container_has_excess_data(self):
351
"""Test the formatting of ContainerHasExcessDataError."""
352
e = errors.ContainerHasExcessDataError("excess bytes")
354
"Container has data after end marker: 'excess bytes'",
357
def test_duplicate_record_name_error(self):
358
"""Test the formatting of DuplicateRecordNameError."""
359
e = errors.DuplicateRecordNameError(b"n\xc3\xa5me")
361
u"Container has multiple records with the same name: n\xe5me",
364
def test_check_error(self):
365
e = errors.BzrCheckError('example check failure')
367
"Internal check failed: example check failure",
369
self.assertTrue(e.internal_error)
371
def test_repository_data_stream_error(self):
372
"""Test the formatting of RepositoryDataStreamError."""
373
e = errors.RepositoryDataStreamError(u"my reason")
375
"Corrupt or incompatible data stream: my reason", str(e))
377
def test_immortal_pending_deletion_message(self):
378
err = errors.ImmortalPendingDeletion('foo')
380
"Unable to delete transform temporary directory foo. "
381
"Please examine foo to see if it contains any files "
382
"you wish to keep, and delete it when you are done.",
385
def test_unable_create_symlink(self):
386
err = errors.UnableCreateSymlink()
388
"Unable to create symlink on this platform",
390
err = errors.UnableCreateSymlink(path=u'foo')
392
"Unable to create symlink 'foo' on this platform",
394
err = errors.UnableCreateSymlink(path=u'\xb5')
396
"Unable to create symlink %s on this platform" % repr(u'\xb5'),
399
def test_invalid_url_join(self):
400
"""Test the formatting of InvalidURLJoin."""
401
e = urlutils.InvalidURLJoin('Reason', 'base path', ('args',))
403
"Invalid URL join request: Reason: 'base path' + ('args',)",
406
def test_unable_encode_path(self):
407
err = errors.UnableEncodePath('foo', 'executable')
408
self.assertEqual("Unable to encode executable path 'foo' in "
409
"user encoding " + osutils.get_user_encoding(),
412
def test_unknown_format(self):
413
err = errors.UnknownFormatError('bar', kind='foo')
414
self.assertEqual("Unknown foo format: 'bar'", str(err))
416
def test_tip_change_rejected(self):
417
err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
419
u'Tip change rejected: Unicode message\N{INTERROBANG}',
422
def test_error_from_smart_server(self):
423
error_tuple = ('error', 'tuple')
424
err = errors.ErrorFromSmartServer(error_tuple)
426
"Error received from smart server: ('error', 'tuple')", str(err))
428
def test_untranslateable_error_from_smart_server(self):
429
error_tuple = ('error', 'tuple')
430
orig_err = errors.ErrorFromSmartServer(error_tuple)
431
err = errors.UnknownErrorFromSmartServer(orig_err)
433
"Server sent an unexpected error: ('error', 'tuple')", str(err))
435
def test_smart_message_handler_error(self):
436
# Make an exc_info tuple.
438
raise Exception("example error")
440
err = errors.SmartMessageHandlerError(sys.exc_info())
441
# GZ 2010-11-08: Should not store exc_info in exception instances.
443
self.assertStartsWith(
444
str(err), "The message handler raised an exception:\n")
445
self.assertEndsWith(str(err), "Exception: example error\n")
449
def test_unresumable_write_group(self):
451
wg_tokens = ['token']
453
err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
455
"Repository dummy repo cannot resume write group "
456
"['token']: a reason", str(err))
458
def test_unsuspendable_write_group(self):
460
err = errors.UnsuspendableWriteGroup(repo)
462
'Repository dummy repo cannot suspend a write group.', str(err))
464
def test_not_branch_no_args(self):
465
err = errors.NotBranchError('path')
466
self.assertEqual('Not a branch: "path".', str(err))
468
def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
469
class FakeBzrDir(object):
470
def open_repository(self):
471
# str() on the NotBranchError will trigger a call to this,
472
# which in turn will another, identical NotBranchError.
473
raise errors.NotBranchError('path', controldir=FakeBzrDir())
474
err = errors.NotBranchError('path', controldir=FakeBzrDir())
475
self.assertEqual('Not a branch: "path": NotBranchError.', str(err))
477
def test_recursive_bind(self):
478
error = errors.RecursiveBind('foo_bar_branch')
479
msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
480
'Please use `brz unbind` to fix.')
481
self.assertEqualDiff(msg, str(error))
483
def test_retry_with_new_packs(self):
484
fake_exc_info = ('{exc type}', '{exc value}', '{exc traceback}')
485
error = errors.RetryWithNewPacks(
486
'{context}', reload_occurred=False, exc_info=fake_exc_info)
488
'Pack files have changed, reload and retry. context: '
489
'{context} {exc value}', str(error))
492
class PassThroughError(errors.BzrError):
494
_fmt = """Pass through %(foo)s and %(bar)s"""
496
def __init__(self, foo, bar):
497
errors.BzrError.__init__(self, foo=foo, bar=bar)
500
class ErrorWithBadFormat(errors.BzrError):
502
_fmt = """One format specifier: %(thing)s"""
505
class ErrorWithNoFormat(errors.BzrError):
506
__doc__ = """This class has a docstring but no format string."""
509
class TestErrorFormatting(tests.TestCase):
511
def test_always_str(self):
512
e = PassThroughError(u'\xb5', 'bar')
513
self.assertIsInstance(e.__str__(), str)
514
# In Python str(foo) *must* return a real byte string
515
# not a Unicode string. The following line would raise a
516
# Unicode error, because it tries to call str() on the string
517
# returned from e.__str__(), and it has non ascii characters
519
self.assertEqual('Pass through \xc2\xb5 and bar', s)
521
def test_missing_format_string(self):
522
e = ErrorWithNoFormat(param='randomvalue')
523
self.assertStartsWith(str(e),
524
"Unprintable exception ErrorWithNoFormat")
526
def test_mismatched_format_args(self):
527
# Even though ErrorWithBadFormat's format string does not match the
528
# arguments we constructing it with, we can still stringify an instance
529
# of this exception. The resulting string will say its unprintable.
530
e = ErrorWithBadFormat(not_thing='x')
531
self.assertStartsWith(
532
str(e), 'Unprintable exception ErrorWithBadFormat')
534
def test_cannot_bind_address(self):
535
# see <https://bugs.launchpad.net/bzr/+bug/286871>
536
e = errors.CannotBindAddress('example.com', 22,
537
socket.error(13, 'Permission denied'))
538
self.assertContainsRe(
540
r'Cannot bind address "example\.com:22":.*Permission denied')
542
def test_transform_rename_failed(self):
543
e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
545
u"Failed to rename from to to: readonly file",
549
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
550
"""Tests for errors that need to use a branch or repo."""
552
def test_no_public_branch(self):
553
b = self.make_branch('.')
554
error = errors.NoPublicBranch(b)
555
url = urlutils.unescape_for_display(b.base, 'ascii')
556
self.assertEqualDiff(
557
'There is no public branch set for "%s".' % url, str(error))
559
def test_no_repo(self):
560
dir = controldir.ControlDir.create(self.get_url())
561
error = errors.NoRepositoryPresent(dir)
562
self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
563
self.assertEqual(-1, str(error).find((dir.transport.base)))
565
def test_corrupt_repository(self):
566
repo = self.make_repository('.')
567
error = errors.CorruptRepository(repo)
568
self.assertEqualDiff("An error has been detected in the repository %s.\n"
569
"Please run brz reconcile on this repository." %
570
repo.controldir.root_transport.base,
573
def test_not_branch_bzrdir_with_repo(self):
574
controldir = self.make_repository('repo').controldir
575
err = errors.NotBranchError('path', controldir=controldir)
577
'Not a branch: "path": location is a repository.', str(err))
579
def test_not_branch_bzrdir_without_repo(self):
580
controldir = self.make_controldir('bzrdir')
581
err = errors.NotBranchError('path', controldir=controldir)
582
self.assertEqual('Not a branch: "path".', str(err))
584
def test_not_branch_laziness(self):
585
real_bzrdir = self.make_controldir('path')
586
class FakeBzrDir(object):
589
def open_repository(self):
590
self.calls.append('open_repository')
591
raise errors.NoRepositoryPresent(real_bzrdir)
592
fake_bzrdir = FakeBzrDir()
593
err = errors.NotBranchError('path', controldir=fake_bzrdir)
594
self.assertEqual([], fake_bzrdir.calls)
596
self.assertEqual(['open_repository'], fake_bzrdir.calls)
597
# Stringifying twice doesn't try to open a repository twice.
599
self.assertEqual(['open_repository'], fake_bzrdir.calls)