1
# Copyright (C) 2006-2010 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 bzrlib.tests import TestCase, TestCaseWithTransport, TestSkipped
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\"",
82
def test_disabled_method(self):
83
error = errors.DisabledMethod("class name")
85
"The smart server method 'class name' is disabled.", str(error))
87
def test_duplicate_file_id(self):
88
error = errors.DuplicateFileId('a_file_id', 'foo')
89
self.assertEqualDiff('File id {a_file_id} already exists in inventory'
90
' as foo', str(error))
92
def test_duplicate_help_prefix(self):
93
error = errors.DuplicateHelpPrefix('foo')
94
self.assertEqualDiff('The prefix foo is in the help search path twice.',
97
def test_ghost_revisions_have_no_revno(self):
98
error = errors.GhostRevisionsHaveNoRevno('target', 'ghost_rev')
99
self.assertEqualDiff("Could not determine revno for {target} because"
100
" its ancestry shows a ghost at {ghost_rev}",
103
def test_incompatibleAPI(self):
104
error = errors.IncompatibleAPI("module", (1, 2, 3), (4, 5, 6), (7, 8, 9))
105
self.assertEqualDiff(
106
'The API for "module" is not compatible with "(1, 2, 3)". '
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",
123
def test_in_process_transport(self):
124
error = errors.InProcessTransport('fpp')
125
self.assertEqualDiff(
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",
143
def test_inventory_modified(self):
144
error = errors.InventoryModified("a tree to be repred")
145
self.assertEqualDiff("The current inventory for the tree 'a tree to "
146
"be repred' has been modified, so a clean inventory cannot be "
147
"read without data loss.",
150
def test_jail_break(self):
151
error = errors.JailBreak("some url")
152
self.assertEqualDiff("An attempt to access a url outside the server"
153
" jail was made: 'some url'.",
156
def test_lock_active(self):
157
error = errors.LockActive("lock description")
158
self.assertEqualDiff("The lock for 'lock description' is in use and "
162
def test_lock_corrupt(self):
163
error = errors.LockCorrupt("corruption info")
164
self.assertEqualDiff("Lock is apparently held, but corrupted: "
166
"Use 'bzr break-lock' to clear it",
169
def test_knit_data_stream_incompatible(self):
170
error = errors.KnitDataStreamIncompatible(
171
'stream format', 'target format')
172
self.assertEqual('Cannot insert knit data stream of format '
173
'"stream format" into knit of format '
174
'"target format".', str(error))
176
def test_knit_data_stream_unknown(self):
177
error = errors.KnitDataStreamUnknown(
179
self.assertEqual('Cannot parse knit data stream of format '
180
'"stream format".', str(error))
182
def test_knit_header_error(self):
183
error = errors.KnitHeaderError('line foo\n', 'path/to/file')
184
self.assertEqual("Knit header error: 'line foo\\n' unexpected"
185
" for file \"path/to/file\".", str(error))
187
def test_knit_index_unknown_method(self):
188
error = errors.KnitIndexUnknownMethod('http://host/foo.kndx',
190
self.assertEqual("Knit index http://host/foo.kndx does not have a"
191
" known method in options: ['bad', 'no-eol']",
194
def test_medium_not_connected(self):
195
error = errors.MediumNotConnected("a medium")
196
self.assertEqualDiff(
197
"The medium 'a medium' is not connected.", str(error))
199
def test_no_public_branch(self):
200
b = self.make_branch('.')
201
error = errors.NoPublicBranch(b)
202
url = urlutils.unescape_for_display(b.base, 'ascii')
203
self.assertEqualDiff(
204
'There is no public branch set for "%s".' % url, str(error))
206
def test_no_repo(self):
207
dir = bzrdir.BzrDir.create(self.get_url())
208
error = errors.NoRepositoryPresent(dir)
209
self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
210
self.assertEqual(-1, str(error).find((dir.transport.base)))
212
def test_no_smart_medium(self):
213
error = errors.NoSmartMedium("a transport")
214
self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
218
def test_no_help_topic(self):
219
error = errors.NoHelpTopic("topic")
220
self.assertEqualDiff("No help could be found for 'topic'. "
221
"Please use 'bzr help topics' to obtain a list of topics.",
224
def test_no_such_id(self):
225
error = errors.NoSuchId("atree", "anid")
226
self.assertEqualDiff("The file id \"anid\" is not present in the tree "
230
def test_no_such_revision_in_tree(self):
231
error = errors.NoSuchRevisionInTree("atree", "anid")
232
self.assertEqualDiff("The revision id {anid} is not present in the"
233
" tree atree.", str(error))
234
self.assertIsInstance(error, errors.NoSuchRevision)
236
def test_not_stacked(self):
237
error = errors.NotStacked('a branch')
238
self.assertEqualDiff("The branch 'a branch' is not stacked.",
241
def test_not_write_locked(self):
242
error = errors.NotWriteLocked('a thing to repr')
243
self.assertEqualDiff("'a thing to repr' is not write locked but needs "
247
def test_lock_failed(self):
248
error = errors.LockFailed('http://canonical.com/', 'readonly transport')
249
self.assertEqualDiff("Cannot lock http://canonical.com/: readonly transport",
251
self.assertFalse(error.internal_error)
253
def test_too_many_concurrent_requests(self):
254
error = errors.TooManyConcurrentRequests("a medium")
255
self.assertEqualDiff("The medium 'a medium' has reached its concurrent "
256
"request limit. Be sure to finish_writing and finish_reading on "
257
"the currently open request.",
260
def test_unavailable_representation(self):
261
error = errors.UnavailableRepresentation(('key',), "mpdiff", "fulltext")
262
self.assertEqualDiff("The encoding 'mpdiff' is not available for key "
263
"('key',) which is encoded as 'fulltext'.",
266
def test_unknown_hook(self):
267
error = errors.UnknownHook("branch", "foo")
268
self.assertEqualDiff("The branch hook 'foo' is unknown in this version"
271
error = errors.UnknownHook("tree", "bar")
272
self.assertEqualDiff("The tree hook 'bar' is unknown in this version"
276
def test_unstackable_branch_format(self):
279
error = errors.UnstackableBranchFormat(format, url)
280
self.assertEqualDiff(
281
"The branch '/foo'(foo) is not a stackable format. "
282
"You will need to upgrade the branch to permit branch stacking.",
285
def test_unstackable_location(self):
286
error = errors.UnstackableLocationError('foo', 'bar')
287
self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
290
def test_unstackable_repository_format(self):
293
error = errors.UnstackableRepositoryFormat(format, url)
294
self.assertEqualDiff(
295
"The repository '/foo'(foo) is not a stackable format. "
296
"You will need to upgrade the repository to permit branch stacking.",
299
def test_up_to_date(self):
300
error = errors.UpToDateFormat(bzrdir.BzrDirFormat4())
301
self.assertEqualDiff("The branch format All-in-one "
302
"format 4 is already at the most "
306
def test_corrupt_repository(self):
307
repo = self.make_repository('.')
308
error = errors.CorruptRepository(repo)
309
self.assertEqualDiff("An error has been detected in the repository %s.\n"
310
"Please run bzr reconcile on this repository." %
311
repo.bzrdir.root_transport.base,
314
def test_read_error(self):
315
# a unicode path to check that %r is being used.
317
error = errors.ReadError(path)
318
self.assertEqualDiff("Error reading from u'a path'.", str(error))
320
def test_bad_index_format_signature(self):
321
error = errors.BadIndexFormatSignature("foo", "bar")
322
self.assertEqual("foo is not an index of type bar.",
325
def test_bad_index_data(self):
326
error = errors.BadIndexData("foo")
327
self.assertEqual("Error in data for index foo.",
330
def test_bad_index_duplicate_key(self):
331
error = errors.BadIndexDuplicateKey("foo", "bar")
332
self.assertEqual("The key 'foo' is already in index 'bar'.",
335
def test_bad_index_key(self):
336
error = errors.BadIndexKey("foo")
337
self.assertEqual("The key 'foo' is not a valid key.",
340
def test_bad_index_options(self):
341
error = errors.BadIndexOptions("foo")
342
self.assertEqual("Could not parse options for index foo.",
345
def test_bad_index_value(self):
346
error = errors.BadIndexValue("foo")
347
self.assertEqual("The value 'foo' is not a valid value.",
350
def test_bzrnewerror_is_deprecated(self):
351
class DeprecatedError(errors.BzrNewError):
353
self.callDeprecated(['BzrNewError was deprecated in bzr 0.13; '
354
'please convert DeprecatedError to use BzrError instead'],
357
def test_bzrerror_from_literal_string(self):
358
# Some code constructs BzrError from a literal string, in which case
359
# no further formatting is done. (I'm not sure raising the base class
360
# is a great idea, but if the exception is not intended to be caught
361
# perhaps no more is needed.)
363
raise errors.BzrError('this is my errors; %d is not expanded')
364
except errors.BzrError, e:
365
self.assertEqual('this is my errors; %d is not expanded', str(e))
367
def test_reading_completed(self):
368
error = errors.ReadingCompleted("a request")
369
self.assertEqualDiff("The MediumRequest 'a request' has already had "
370
"finish_reading called upon it - the request has been completed and"
371
" no more data may be read.",
374
def test_writing_completed(self):
375
error = errors.WritingCompleted("a request")
376
self.assertEqualDiff("The MediumRequest 'a request' has already had "
377
"finish_writing called upon it - accept bytes may not be called "
381
def test_writing_not_completed(self):
382
error = errors.WritingNotComplete("a request")
383
self.assertEqualDiff("The MediumRequest 'a request' has not has "
384
"finish_writing called upon it - until the write phase is complete"
385
" no data may be read.",
388
def test_transport_not_possible(self):
389
error = errors.TransportNotPossible('readonly', 'original error')
390
self.assertEqualDiff('Transport operation not possible:'
391
' readonly original error', str(error))
393
def assertSocketConnectionError(self, expected, *args, **kwargs):
394
"""Check the formatting of a SocketConnectionError exception"""
395
e = errors.SocketConnectionError(*args, **kwargs)
396
self.assertEqual(expected, str(e))
398
def test_socket_connection_error(self):
399
"""Test the formatting of SocketConnectionError"""
401
# There should be a default msg about failing to connect
402
# we only require a host name.
403
self.assertSocketConnectionError(
404
'Failed to connect to ahost',
407
# If port is None, we don't put :None
408
self.assertSocketConnectionError(
409
'Failed to connect to ahost',
411
# But if port is supplied we include it
412
self.assertSocketConnectionError(
413
'Failed to connect to ahost:22',
416
# We can also supply extra information about the error
417
# with or without a port
418
self.assertSocketConnectionError(
419
'Failed to connect to ahost:22; bogus error',
420
'ahost', port=22, orig_error='bogus error')
421
self.assertSocketConnectionError(
422
'Failed to connect to ahost; bogus error',
423
'ahost', orig_error='bogus error')
424
# An exception object can be passed rather than a string
425
orig_error = ValueError('bad value')
426
self.assertSocketConnectionError(
427
'Failed to connect to ahost; %s' % (str(orig_error),),
428
host='ahost', orig_error=orig_error)
430
# And we can supply a custom failure message
431
self.assertSocketConnectionError(
432
'Unable to connect to ssh host ahost:444; my_error',
433
host='ahost', port=444, msg='Unable to connect to ssh host',
434
orig_error='my_error')
436
def test_target_not_branch(self):
437
"""Test the formatting of TargetNotBranch."""
438
error = errors.TargetNotBranch('foo')
440
"Your branch does not have all of the revisions required in "
441
"order to merge this merge directive and the target "
442
"location specified in the merge directive is not a branch: "
445
def test_malformed_bug_identifier(self):
446
"""Test the formatting of MalformedBugIdentifier."""
447
error = errors.MalformedBugIdentifier('bogus', 'reason for bogosity')
449
'Did not understand bug identifier bogus: reason for bogosity. '
450
'See "bzr help bugs" for more information on this feature.',
453
def test_unknown_bug_tracker_abbreviation(self):
454
"""Test the formatting of UnknownBugTrackerAbbreviation."""
455
branch = self.make_branch('some_branch')
456
error = errors.UnknownBugTrackerAbbreviation('xxx', branch)
458
"Cannot find registered bug tracker called xxx on %s" % branch,
461
def test_unexpected_smart_server_response(self):
462
e = errors.UnexpectedSmartServerResponse(('not yes',))
464
"Could not understand response from smart server: ('not yes',)",
467
def test_unknown_container_format(self):
468
"""Test the formatting of UnknownContainerFormatError."""
469
e = errors.UnknownContainerFormatError('bad format string')
471
"Unrecognised container format: 'bad format string'",
474
def test_unexpected_end_of_container(self):
475
"""Test the formatting of UnexpectedEndOfContainerError."""
476
e = errors.UnexpectedEndOfContainerError()
478
"Unexpected end of container stream", str(e))
480
def test_unknown_record_type(self):
481
"""Test the formatting of UnknownRecordTypeError."""
482
e = errors.UnknownRecordTypeError("X")
484
"Unknown record type: 'X'",
487
def test_invalid_record(self):
488
"""Test the formatting of InvalidRecordError."""
489
e = errors.InvalidRecordError("xxx")
491
"Invalid record: xxx",
494
def test_container_has_excess_data(self):
495
"""Test the formatting of ContainerHasExcessDataError."""
496
e = errors.ContainerHasExcessDataError("excess bytes")
498
"Container has data after end marker: 'excess bytes'",
501
def test_duplicate_record_name_error(self):
502
"""Test the formatting of DuplicateRecordNameError."""
503
e = errors.DuplicateRecordNameError(u"n\xe5me".encode('utf-8'))
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))
704
class PassThroughError(errors.BzrError):
706
_fmt = """Pass through %(foo)s and %(bar)s"""
708
def __init__(self, foo, bar):
709
errors.BzrError.__init__(self, foo=foo, bar=bar)
712
class ErrorWithBadFormat(errors.BzrError):
714
_fmt = """One format specifier: %(thing)s"""
717
class ErrorWithNoFormat(errors.BzrError):
718
__doc__ = """This class has a docstring but no format string."""
721
class TestErrorFormatting(TestCase):
723
def test_always_str(self):
724
e = PassThroughError(u'\xb5', 'bar')
725
self.assertIsInstance(e.__str__(), str)
726
# In Python str(foo) *must* return a real byte string
727
# not a Unicode string. The following line would raise a
728
# Unicode error, because it tries to call str() on the string
729
# returned from e.__str__(), and it has non ascii characters
731
self.assertEqual('Pass through \xc2\xb5 and bar', s)
733
def test_missing_format_string(self):
734
e = ErrorWithNoFormat(param='randomvalue')
735
s = self.callDeprecated(
736
['ErrorWithNoFormat uses its docstring as a format, it should use _fmt instead'],
740
"This class has a docstring but no format string.")
742
def test_mismatched_format_args(self):
743
# Even though ErrorWithBadFormat's format string does not match the
744
# arguments we constructing it with, we can still stringify an instance
745
# of this exception. The resulting string will say its unprintable.
746
e = ErrorWithBadFormat(not_thing='x')
747
self.assertStartsWith(
748
str(e), 'Unprintable exception ErrorWithBadFormat')
750
def test_cannot_bind_address(self):
751
# see <https://bugs.launchpad.net/bzr/+bug/286871>
752
e = errors.CannotBindAddress('example.com', 22,
753
socket.error(13, 'Permission denied'))
754
self.assertContainsRe(str(e),
755
r'Cannot bind address "example\.com:22":.*Permission denied')
757
def test_file_timestamp_unavailable(self):
758
e = errors.FileTimestampUnavailable("/path/foo")
759
self.assertEquals("The filestamp for /path/foo is not available.",
762
def test_transform_rename_failed(self):
763
e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
765
u"Failed to rename from to to: readonly file",