/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_errors.py

  • Committer: Jelmer Vernooij
  • Date: 2017-08-07 11:49:46 UTC
  • mto: (6747.3.4 avoid-set-revid-3)
  • mto: This revision was merged to the branch mainline in revision 6750.
  • Revision ID: jelmer@jelmer.uk-20170807114946-luclmxuawyzhpiot
Avoid setting revision_ids.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Tests for the formatting and construction of errors."""
 
18
 
 
19
import inspect
 
20
import re
 
21
import socket
 
22
import sys
 
23
 
 
24
from .. import (
 
25
    controldir,
 
26
    errors,
 
27
    osutils,
 
28
    tests,
 
29
    urlutils,
 
30
    )
 
31
from ..sixish import (
 
32
    text_type,
 
33
    )
 
34
 
 
35
 
 
36
class TestErrors(tests.TestCase):
 
37
 
 
38
    def test_no_arg_named_message(self):
 
39
        """Ensure the __init__ and _fmt in errors do not have "message" arg.
 
40
 
 
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.
 
44
        See bug #603461
 
45
        """
 
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)
 
50
            if init:
 
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__))
 
58
 
 
59
    def test_bad_filename_encoding(self):
 
60
        error = errors.BadFilenameEncoding(b'bad/filen\xe5me', 'UTF-8')
 
61
        self.assertContainsRe(
 
62
            str(error),
 
63
            "^Filename b?'bad/filen\\\\xe5me' is not valid in your current"
 
64
            " filesystem encoding UTF-8$")
 
65
 
 
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))
 
70
 
 
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.',
 
74
            str(error))
 
75
 
 
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}",
 
80
                             str(error))
 
81
 
 
82
    def test_incompatibleVersion(self):
 
83
        error = errors.IncompatibleVersion("module", [(4, 5, 6), (7, 8, 9)],
 
84
                (1, 2, 3))
 
85
        self.assertEqualDiff(
 
86
            'API module is not compatible; one of versions '
 
87
            '[(4, 5, 6), (7, 8, 9)] is required, but current version is '
 
88
            '(1, 2, 3).',
 
89
            str(error))
 
90
 
 
91
    def test_inconsistent_delta(self):
 
92
        error = errors.InconsistentDelta('path', 'file-id', 'reason for foo')
 
93
        self.assertEqualDiff(
 
94
            "An inconsistent delta was supplied involving 'path', 'file-id'\n"
 
95
            "reason: reason for foo",
 
96
            str(error))
 
97
 
 
98
    def test_inconsistent_delta_delta(self):
 
99
        error = errors.InconsistentDeltaDelta([], 'reason')
 
100
        self.assertEqualDiff(
 
101
            "An inconsistent delta was supplied: []\nreason: reason",
 
102
            str(error))
 
103
 
 
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.",
 
108
            str(error))
 
109
 
 
110
    def test_invalid_http_range(self):
 
111
        error = errors.InvalidHttpRange('path',
 
112
                                        'Content-Range: potatoes 0-00/o0oo0',
 
113
                                        'bad range')
 
114
        self.assertEqual("Invalid http range"
 
115
                         " 'Content-Range: potatoes 0-00/o0oo0'"
 
116
                         " for path: bad range",
 
117
                         str(error))
 
118
 
 
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",
 
122
                         str(error))
 
123
 
 
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.",
 
129
            str(error))
 
130
 
 
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'.",
 
135
            str(error))
 
136
 
 
137
    def test_lock_active(self):
 
138
        error = errors.LockActive("lock description")
 
139
        self.assertEqualDiff("The lock for 'lock description' is in use and "
 
140
            "cannot be broken.",
 
141
            str(error))
 
142
 
 
143
    def test_lock_corrupt(self):
 
144
        error = errors.LockCorrupt("corruption info")
 
145
        self.assertEqualDiff("Lock is apparently held, but corrupted: "
 
146
            "corruption info\n"
 
147
            "Use 'brz break-lock' to clear it",
 
148
            str(error))
 
149
 
 
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))
 
154
 
 
155
    def test_no_smart_medium(self):
 
156
        error = errors.NoSmartMedium("a transport")
 
157
        self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
 
158
            "smart protocol.",
 
159
            str(error))
 
160
 
 
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 "
 
164
            "atree.",
 
165
            str(error))
 
166
 
 
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)
 
172
 
 
173
    def test_not_stacked(self):
 
174
        error = errors.NotStacked('a branch')
 
175
        self.assertEqualDiff("The branch 'a branch' is not stacked.",
 
176
            str(error))
 
177
 
 
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 "
 
181
            "to be.",
 
182
            str(error))
 
183
 
 
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",
 
187
            str(error))
 
188
        self.assertFalse(error.internal_error)
 
189
 
 
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.",
 
195
            str(error))
 
196
 
 
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'.",
 
201
            str(error))
 
202
 
 
203
    def test_unstackable_location(self):
 
204
        error = errors.UnstackableLocationError('foo', 'bar')
 
205
        self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
 
206
            str(error))
 
207
 
 
208
    def test_unstackable_repository_format(self):
 
209
        format = u'foo'
 
210
        url = "/foo"
 
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.",
 
215
            str(error))
 
216
 
 
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))
 
222
 
 
223
    def test_read_error(self):
 
224
        # a unicode path to check that %r is being used.
 
225
        path = u'a path'
 
226
        error = errors.ReadError(path)
 
227
        self.assertContainsRe(str(error), "^Error reading from u?'a path'.$")
 
228
 
 
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.)
 
234
        try:
 
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))
 
238
 
 
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.",
 
244
            str(error))
 
245
 
 
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 "
 
250
            "anymore.",
 
251
            str(error))
 
252
 
 
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.",
 
258
            str(error))
 
259
 
 
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))
 
264
 
 
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))
 
269
 
 
270
    def test_socket_connection_error(self):
 
271
        """Test the formatting of SocketConnectionError"""
 
272
 
 
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',
 
277
            'ahost')
 
278
 
 
279
        # If port is None, we don't put :None
 
280
        self.assertSocketConnectionError(
 
281
            'Failed to connect to ahost',
 
282
            'ahost', port=None)
 
283
        # But if port is supplied we include it
 
284
        self.assertSocketConnectionError(
 
285
            'Failed to connect to ahost:22',
 
286
            'ahost', port=22)
 
287
 
 
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)
 
301
 
 
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')
 
307
 
 
308
    def test_target_not_branch(self):
 
309
        """Test the formatting of TargetNotBranch."""
 
310
        error = errors.TargetNotBranch('foo')
 
311
        self.assertEqual(
 
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: "
 
315
            "foo.", str(error))
 
316
 
 
317
    def test_unexpected_smart_server_response(self):
 
318
        e = errors.UnexpectedSmartServerResponse(('not yes',))
 
319
        self.assertEqual(
 
320
            "Could not understand response from smart server: ('not yes',)",
 
321
            str(e))
 
322
 
 
323
    def test_unknown_container_format(self):
 
324
        """Test the formatting of UnknownContainerFormatError."""
 
325
        e = errors.UnknownContainerFormatError('bad format string')
 
326
        self.assertEqual(
 
327
            "Unrecognised container format: 'bad format string'",
 
328
            str(e))
 
329
 
 
330
    def test_unexpected_end_of_container(self):
 
331
        """Test the formatting of UnexpectedEndOfContainerError."""
 
332
        e = errors.UnexpectedEndOfContainerError()
 
333
        self.assertEqual(
 
334
            "Unexpected end of container stream", str(e))
 
335
 
 
336
    def test_unknown_record_type(self):
 
337
        """Test the formatting of UnknownRecordTypeError."""
 
338
        e = errors.UnknownRecordTypeError("X")
 
339
        self.assertEqual(
 
340
            "Unknown record type: 'X'",
 
341
            str(e))
 
342
 
 
343
    def test_invalid_record(self):
 
344
        """Test the formatting of InvalidRecordError."""
 
345
        e = errors.InvalidRecordError("xxx")
 
346
        self.assertEqual(
 
347
            "Invalid record: xxx",
 
348
            str(e))
 
349
 
 
350
    def test_container_has_excess_data(self):
 
351
        """Test the formatting of ContainerHasExcessDataError."""
 
352
        e = errors.ContainerHasExcessDataError("excess bytes")
 
353
        self.assertEqual(
 
354
            "Container has data after end marker: 'excess bytes'",
 
355
            str(e))
 
356
 
 
357
    def test_duplicate_record_name_error(self):
 
358
        """Test the formatting of DuplicateRecordNameError."""
 
359
        e = errors.DuplicateRecordNameError(b"n\xc3\xa5me")
 
360
        self.assertEqual(
 
361
            u"Container has multiple records with the same name: n\xe5me",
 
362
            text_type(e))
 
363
 
 
364
    def test_check_error(self):
 
365
        e = errors.BzrCheckError('example check failure')
 
366
        self.assertEqual(
 
367
            "Internal check failed: example check failure",
 
368
            str(e))
 
369
        self.assertTrue(e.internal_error)
 
370
 
 
371
    def test_repository_data_stream_error(self):
 
372
        """Test the formatting of RepositoryDataStreamError."""
 
373
        e = errors.RepositoryDataStreamError(u"my reason")
 
374
        self.assertEqual(
 
375
            "Corrupt or incompatible data stream: my reason", str(e))
 
376
 
 
377
    def test_immortal_pending_deletion_message(self):
 
378
        err = errors.ImmortalPendingDeletion('foo')
 
379
        self.assertEqual(
 
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.",
 
383
            str(err))
 
384
 
 
385
    def test_unable_create_symlink(self):
 
386
        err = errors.UnableCreateSymlink()
 
387
        self.assertEqual(
 
388
            "Unable to create symlink on this platform",
 
389
            str(err))
 
390
        err = errors.UnableCreateSymlink(path=u'foo')
 
391
        self.assertEqual(
 
392
            "Unable to create symlink 'foo' on this platform",
 
393
            str(err))
 
394
        err = errors.UnableCreateSymlink(path=u'\xb5')
 
395
        self.assertEqual(
 
396
            "Unable to create symlink %s on this platform" % repr(u'\xb5'),
 
397
            str(err))
 
398
 
 
399
    def test_invalid_url_join(self):
 
400
        """Test the formatting of InvalidURLJoin."""
 
401
        e = urlutils.InvalidURLJoin('Reason', 'base path', ('args',))
 
402
        self.assertEqual(
 
403
            "Invalid URL join request: Reason: 'base path' + ('args',)",
 
404
            str(e))
 
405
 
 
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(),
 
410
                         str(err))
 
411
 
 
412
    def test_unknown_format(self):
 
413
        err = errors.UnknownFormatError('bar', kind='foo')
 
414
        self.assertEqual("Unknown foo format: 'bar'", str(err))
 
415
 
 
416
    def test_tip_change_rejected(self):
 
417
        err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
 
418
        self.assertEqual(
 
419
            u'Tip change rejected: Unicode message\N{INTERROBANG}',
 
420
            text_type(err))
 
421
 
 
422
    def test_error_from_smart_server(self):
 
423
        error_tuple = ('error', 'tuple')
 
424
        err = errors.ErrorFromSmartServer(error_tuple)
 
425
        self.assertEqual(
 
426
            "Error received from smart server: ('error', 'tuple')", str(err))
 
427
 
 
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)
 
432
        self.assertEqual(
 
433
            "Server sent an unexpected error: ('error', 'tuple')", str(err))
 
434
 
 
435
    def test_smart_message_handler_error(self):
 
436
        # Make an exc_info tuple.
 
437
        try:
 
438
            raise Exception("example error")
 
439
        except Exception:
 
440
            err = errors.SmartMessageHandlerError(sys.exc_info())
 
441
        # GZ 2010-11-08: Should not store exc_info in exception instances.
 
442
        try:
 
443
            self.assertStartsWith(
 
444
                str(err), "The message handler raised an exception:\n")
 
445
            self.assertEndsWith(str(err), "Exception: example error\n")
 
446
        finally:
 
447
            del err
 
448
 
 
449
    def test_unresumable_write_group(self):
 
450
        repo = "dummy repo"
 
451
        wg_tokens = ['token']
 
452
        reason = "a reason"
 
453
        err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
 
454
        self.assertEqual(
 
455
            "Repository dummy repo cannot resume write group "
 
456
            "['token']: a reason", str(err))
 
457
 
 
458
    def test_unsuspendable_write_group(self):
 
459
        repo = "dummy repo"
 
460
        err = errors.UnsuspendableWriteGroup(repo)
 
461
        self.assertEqual(
 
462
            'Repository dummy repo cannot suspend a write group.', str(err))
 
463
 
 
464
    def test_not_branch_no_args(self):
 
465
        err = errors.NotBranchError('path')
 
466
        self.assertEqual('Not a branch: "path".', str(err))
 
467
 
 
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))
 
476
 
 
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))
 
482
 
 
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)
 
487
        self.assertEqual(
 
488
            'Pack files have changed, reload and retry. context: '
 
489
            '{context} {exc value}', str(error))
 
490
 
 
491
 
 
492
class PassThroughError(errors.BzrError):
 
493
 
 
494
    _fmt = """Pass through %(foo)s and %(bar)s"""
 
495
 
 
496
    def __init__(self, foo, bar):
 
497
        errors.BzrError.__init__(self, foo=foo, bar=bar)
 
498
 
 
499
 
 
500
class ErrorWithBadFormat(errors.BzrError):
 
501
 
 
502
    _fmt = """One format specifier: %(thing)s"""
 
503
 
 
504
 
 
505
class ErrorWithNoFormat(errors.BzrError):
 
506
    __doc__ = """This class has a docstring but no format string."""
 
507
 
 
508
 
 
509
class TestErrorFormatting(tests.TestCase):
 
510
 
 
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
 
518
        s = str(e)
 
519
        self.assertEqual('Pass through \xc2\xb5 and bar', s)
 
520
 
 
521
    def test_missing_format_string(self):
 
522
        e = ErrorWithNoFormat(param='randomvalue')
 
523
        self.assertStartsWith(str(e),
 
524
                              "Unprintable exception ErrorWithNoFormat")
 
525
 
 
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')
 
533
 
 
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(
 
539
            str(e),
 
540
            r'Cannot bind address "example\.com:22":.*Permission denied')
 
541
 
 
542
    def test_transform_rename_failed(self):
 
543
        e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
 
544
        self.assertEqual(
 
545
            u"Failed to rename from to to: readonly file",
 
546
            str(e))
 
547
 
 
548
 
 
549
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
 
550
    """Tests for errors that need to use a branch or repo."""
 
551
 
 
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))
 
558
 
 
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)))
 
564
 
 
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,
 
571
                             str(error))
 
572
 
 
573
    def test_not_branch_bzrdir_with_repo(self):
 
574
        controldir = self.make_repository('repo').controldir
 
575
        err = errors.NotBranchError('path', controldir=controldir)
 
576
        self.assertEqual(
 
577
            'Not a branch: "path": location is a repository.', str(err))
 
578
 
 
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))
 
583
 
 
584
    def test_not_branch_laziness(self):
 
585
        real_bzrdir = self.make_controldir('path')
 
586
        class FakeBzrDir(object):
 
587
            def __init__(self):
 
588
                self.calls = []
 
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)
 
595
        str(err)
 
596
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
 
597
        # Stringifying twice doesn't try to open a repository twice.
 
598
        str(err)
 
599
        self.assertEqual(['open_repository'], fake_bzrdir.calls)