/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-07-23 15:59:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6740.
  • Revision ID: jelmer@jelmer.uk-20170723155957-rw4kqurf44fqx4x0
Move AlreadyBuilding/NotBuilding errors.

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_corrupt_dirstate(self):
 
67
        error = errors.CorruptDirstate('path/to/dirstate', 'the reason why')
 
68
        self.assertEqualDiff(
 
69
            "Inconsistency in dirstate file path/to/dirstate.\n"
 
70
            "Error: the reason why",
 
71
            str(error))
 
72
 
 
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\"",
 
78
            str(error))
 
79
 
 
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))
 
84
 
 
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.',
 
88
            str(error))
 
89
 
 
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}",
 
94
                             str(error))
 
95
 
 
96
    def test_incompatibleVersion(self):
 
97
        error = errors.IncompatibleVersion("module", [(4, 5, 6), (7, 8, 9)],
 
98
                (1, 2, 3))
 
99
        self.assertEqualDiff(
 
100
            'API module is not compatible; one of versions '
 
101
            '[(4, 5, 6), (7, 8, 9)] is required, but current version is '
 
102
            '(1, 2, 3).',
 
103
            str(error))
 
104
 
 
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",
 
110
            str(error))
 
111
 
 
112
    def test_inconsistent_delta_delta(self):
 
113
        error = errors.InconsistentDeltaDelta([], 'reason')
 
114
        self.assertEqualDiff(
 
115
            "An inconsistent delta was supplied: []\nreason: reason",
 
116
            str(error))
 
117
 
 
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.",
 
122
            str(error))
 
123
 
 
124
    def test_invalid_http_range(self):
 
125
        error = errors.InvalidHttpRange('path',
 
126
                                        'Content-Range: potatoes 0-00/o0oo0',
 
127
                                        'bad range')
 
128
        self.assertEqual("Invalid http range"
 
129
                         " 'Content-Range: potatoes 0-00/o0oo0'"
 
130
                         " for path: bad range",
 
131
                         str(error))
 
132
 
 
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",
 
136
                         str(error))
 
137
 
 
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.",
 
143
            str(error))
 
144
 
 
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'.",
 
149
            str(error))
 
150
 
 
151
    def test_lock_active(self):
 
152
        error = errors.LockActive("lock description")
 
153
        self.assertEqualDiff("The lock for 'lock description' is in use and "
 
154
            "cannot be broken.",
 
155
            str(error))
 
156
 
 
157
    def test_lock_corrupt(self):
 
158
        error = errors.LockCorrupt("corruption info")
 
159
        self.assertEqualDiff("Lock is apparently held, but corrupted: "
 
160
            "corruption info\n"
 
161
            "Use 'brz break-lock' to clear it",
 
162
            str(error))
 
163
 
 
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))
 
170
 
 
171
    def test_knit_data_stream_unknown(self):
 
172
        error = errors.KnitDataStreamUnknown(
 
173
            'stream format')
 
174
        self.assertEqual('Cannot parse knit data stream of format '
 
175
                         '"stream format".', str(error))
 
176
 
 
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))
 
181
 
 
182
    def test_knit_index_unknown_method(self):
 
183
        error = errors.KnitIndexUnknownMethod('http://host/foo.kndx',
 
184
                                              ['bad', 'no-eol'])
 
185
        self.assertEqual("Knit index http://host/foo.kndx does not have a"
 
186
                         " known method in options: ['bad', 'no-eol']",
 
187
                         str(error))
 
188
 
 
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))
 
193
 
 
194
    def test_no_smart_medium(self):
 
195
        error = errors.NoSmartMedium("a transport")
 
196
        self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
 
197
            "smart protocol.",
 
198
            str(error))
 
199
 
 
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 "
 
203
            "atree.",
 
204
            str(error))
 
205
 
 
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)
 
211
 
 
212
    def test_not_stacked(self):
 
213
        error = errors.NotStacked('a branch')
 
214
        self.assertEqualDiff("The branch 'a branch' is not stacked.",
 
215
            str(error))
 
216
 
 
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 "
 
220
            "to be.",
 
221
            str(error))
 
222
 
 
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",
 
226
            str(error))
 
227
        self.assertFalse(error.internal_error)
 
228
 
 
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.",
 
234
            str(error))
 
235
 
 
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'.",
 
240
            str(error))
 
241
 
 
242
    def test_unknown_hook(self):
 
243
        error = errors.UnknownHook("branch", "foo")
 
244
        self.assertEqualDiff("The branch hook 'foo' is unknown in this version"
 
245
            " of breezy.",
 
246
            str(error))
 
247
        error = errors.UnknownHook("tree", "bar")
 
248
        self.assertEqualDiff("The tree hook 'bar' is unknown in this version"
 
249
            " of breezy.",
 
250
            str(error))
 
251
 
 
252
    def test_unstackable_branch_format(self):
 
253
        format = u'foo'
 
254
        url = "/foo"
 
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.",
 
259
            str(error))
 
260
 
 
261
    def test_unstackable_location(self):
 
262
        error = errors.UnstackableLocationError('foo', 'bar')
 
263
        self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
 
264
            str(error))
 
265
 
 
266
    def test_unstackable_repository_format(self):
 
267
        format = u'foo'
 
268
        url = "/foo"
 
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.",
 
273
            str(error))
 
274
 
 
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))
 
280
 
 
281
    def test_read_error(self):
 
282
        # a unicode path to check that %r is being used.
 
283
        path = u'a path'
 
284
        error = errors.ReadError(path)
 
285
        self.assertContainsRe(str(error), "^Error reading from u?'a path'.$")
 
286
 
 
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.",
 
290
            str(error))
 
291
 
 
292
    def test_bad_index_data(self):
 
293
        error = errors.BadIndexData("foo")
 
294
        self.assertEqual("Error in data for index foo.",
 
295
            str(error))
 
296
 
 
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'.",
 
300
            str(error))
 
301
 
 
302
    def test_bad_index_key(self):
 
303
        error = errors.BadIndexKey("foo")
 
304
        self.assertEqual("The key 'foo' is not a valid key.",
 
305
            str(error))
 
306
 
 
307
    def test_bad_index_options(self):
 
308
        error = errors.BadIndexOptions("foo")
 
309
        self.assertEqual("Could not parse options for index foo.",
 
310
            str(error))
 
311
 
 
312
    def test_bad_index_value(self):
 
313
        error = errors.BadIndexValue("foo")
 
314
        self.assertEqual("The value 'foo' is not a valid value.",
 
315
            str(error))
 
316
 
 
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.)
 
322
        try:
 
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))
 
326
 
 
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.",
 
332
            str(error))
 
333
 
 
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 "
 
338
            "anymore.",
 
339
            str(error))
 
340
 
 
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.",
 
346
            str(error))
 
347
 
 
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))
 
352
 
 
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))
 
357
 
 
358
    def test_socket_connection_error(self):
 
359
        """Test the formatting of SocketConnectionError"""
 
360
 
 
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',
 
365
            'ahost')
 
366
 
 
367
        # If port is None, we don't put :None
 
368
        self.assertSocketConnectionError(
 
369
            'Failed to connect to ahost',
 
370
            'ahost', port=None)
 
371
        # But if port is supplied we include it
 
372
        self.assertSocketConnectionError(
 
373
            'Failed to connect to ahost:22',
 
374
            'ahost', port=22)
 
375
 
 
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)
 
389
 
 
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')
 
395
 
 
396
    def test_target_not_branch(self):
 
397
        """Test the formatting of TargetNotBranch."""
 
398
        error = errors.TargetNotBranch('foo')
 
399
        self.assertEqual(
 
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: "
 
403
            "foo.", str(error))
 
404
 
 
405
    def test_unexpected_smart_server_response(self):
 
406
        e = errors.UnexpectedSmartServerResponse(('not yes',))
 
407
        self.assertEqual(
 
408
            "Could not understand response from smart server: ('not yes',)",
 
409
            str(e))
 
410
 
 
411
    def test_unknown_container_format(self):
 
412
        """Test the formatting of UnknownContainerFormatError."""
 
413
        e = errors.UnknownContainerFormatError('bad format string')
 
414
        self.assertEqual(
 
415
            "Unrecognised container format: 'bad format string'",
 
416
            str(e))
 
417
 
 
418
    def test_unexpected_end_of_container(self):
 
419
        """Test the formatting of UnexpectedEndOfContainerError."""
 
420
        e = errors.UnexpectedEndOfContainerError()
 
421
        self.assertEqual(
 
422
            "Unexpected end of container stream", str(e))
 
423
 
 
424
    def test_unknown_record_type(self):
 
425
        """Test the formatting of UnknownRecordTypeError."""
 
426
        e = errors.UnknownRecordTypeError("X")
 
427
        self.assertEqual(
 
428
            "Unknown record type: 'X'",
 
429
            str(e))
 
430
 
 
431
    def test_invalid_record(self):
 
432
        """Test the formatting of InvalidRecordError."""
 
433
        e = errors.InvalidRecordError("xxx")
 
434
        self.assertEqual(
 
435
            "Invalid record: xxx",
 
436
            str(e))
 
437
 
 
438
    def test_container_has_excess_data(self):
 
439
        """Test the formatting of ContainerHasExcessDataError."""
 
440
        e = errors.ContainerHasExcessDataError("excess bytes")
 
441
        self.assertEqual(
 
442
            "Container has data after end marker: 'excess bytes'",
 
443
            str(e))
 
444
 
 
445
    def test_duplicate_record_name_error(self):
 
446
        """Test the formatting of DuplicateRecordNameError."""
 
447
        e = errors.DuplicateRecordNameError(b"n\xc3\xa5me")
 
448
        self.assertEqual(
 
449
            u"Container has multiple records with the same name: n\xe5me",
 
450
            text_type(e))
 
451
 
 
452
    def test_check_error(self):
 
453
        e = errors.BzrCheckError('example check failure')
 
454
        self.assertEqual(
 
455
            "Internal check failed: example check failure",
 
456
            str(e))
 
457
        self.assertTrue(e.internal_error)
 
458
 
 
459
    def test_repository_data_stream_error(self):
 
460
        """Test the formatting of RepositoryDataStreamError."""
 
461
        e = errors.RepositoryDataStreamError(u"my reason")
 
462
        self.assertEqual(
 
463
            "Corrupt or incompatible data stream: my reason", str(e))
 
464
 
 
465
    def test_immortal_pending_deletion_message(self):
 
466
        err = errors.ImmortalPendingDeletion('foo')
 
467
        self.assertEqual(
 
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.",
 
471
            str(err))
 
472
 
 
473
    def test_unable_create_symlink(self):
 
474
        err = errors.UnableCreateSymlink()
 
475
        self.assertEqual(
 
476
            "Unable to create symlink on this platform",
 
477
            str(err))
 
478
        err = errors.UnableCreateSymlink(path=u'foo')
 
479
        self.assertEqual(
 
480
            "Unable to create symlink 'foo' on this platform",
 
481
            str(err))
 
482
        err = errors.UnableCreateSymlink(path=u'\xb5')
 
483
        self.assertEqual(
 
484
            "Unable to create symlink %s on this platform" % repr(u'\xb5'),
 
485
            str(err))
 
486
 
 
487
    def test_invalid_url_join(self):
 
488
        """Test the formatting of InvalidURLJoin."""
 
489
        e = errors.InvalidURLJoin('Reason', 'base path', ('args',))
 
490
        self.assertEqual(
 
491
            "Invalid URL join request: Reason: 'base path' + ('args',)",
 
492
            str(e))
 
493
 
 
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(),
 
498
                         str(err))
 
499
 
 
500
    def test_unknown_format(self):
 
501
        err = errors.UnknownFormatError('bar', kind='foo')
 
502
        self.assertEqual("Unknown foo format: 'bar'", str(err))
 
503
 
 
504
    def test_unknown_rules(self):
 
505
        err = errors.UnknownRules(['foo', 'bar'])
 
506
        self.assertEqual("Unknown rules detected: foo, bar.", str(err))
 
507
 
 
508
    def test_tip_change_rejected(self):
 
509
        err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
 
510
        self.assertEqual(
 
511
            u'Tip change rejected: Unicode message\N{INTERROBANG}',
 
512
            text_type(err))
 
513
 
 
514
    def test_error_from_smart_server(self):
 
515
        error_tuple = ('error', 'tuple')
 
516
        err = errors.ErrorFromSmartServer(error_tuple)
 
517
        self.assertEqual(
 
518
            "Error received from smart server: ('error', 'tuple')", str(err))
 
519
 
 
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)
 
524
        self.assertEqual(
 
525
            "Server sent an unexpected error: ('error', 'tuple')", str(err))
 
526
 
 
527
    def test_smart_message_handler_error(self):
 
528
        # Make an exc_info tuple.
 
529
        try:
 
530
            raise Exception("example error")
 
531
        except Exception:
 
532
            err = errors.SmartMessageHandlerError(sys.exc_info())
 
533
        # GZ 2010-11-08: Should not store exc_info in exception instances.
 
534
        try:
 
535
            self.assertStartsWith(
 
536
                str(err), "The message handler raised an exception:\n")
 
537
            self.assertEndsWith(str(err), "Exception: example error\n")
 
538
        finally:
 
539
            del err
 
540
 
 
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"
 
544
                                   " working tree.")
 
545
 
 
546
    def test_unresumable_write_group(self):
 
547
        repo = "dummy repo"
 
548
        wg_tokens = ['token']
 
549
        reason = "a reason"
 
550
        err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
 
551
        self.assertEqual(
 
552
            "Repository dummy repo cannot resume write group "
 
553
            "['token']: a reason", str(err))
 
554
 
 
555
    def test_unsuspendable_write_group(self):
 
556
        repo = "dummy repo"
 
557
        err = errors.UnsuspendableWriteGroup(repo)
 
558
        self.assertEqual(
 
559
            'Repository dummy repo cannot suspend a write group.', str(err))
 
560
 
 
561
    def test_not_branch_no_args(self):
 
562
        err = errors.NotBranchError('path')
 
563
        self.assertEqual('Not a branch: "path".', str(err))
 
564
 
 
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))
 
573
 
 
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))
 
579
 
 
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)
 
584
        self.assertEqual(
 
585
            'Pack files have changed, reload and retry. context: '
 
586
            '{context} {exc value}', str(error))
 
587
 
 
588
 
 
589
class PassThroughError(errors.BzrError):
 
590
 
 
591
    _fmt = """Pass through %(foo)s and %(bar)s"""
 
592
 
 
593
    def __init__(self, foo, bar):
 
594
        errors.BzrError.__init__(self, foo=foo, bar=bar)
 
595
 
 
596
 
 
597
class ErrorWithBadFormat(errors.BzrError):
 
598
 
 
599
    _fmt = """One format specifier: %(thing)s"""
 
600
 
 
601
 
 
602
class ErrorWithNoFormat(errors.BzrError):
 
603
    __doc__ = """This class has a docstring but no format string."""
 
604
 
 
605
 
 
606
class TestErrorFormatting(tests.TestCase):
 
607
 
 
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
 
615
        s = str(e)
 
616
        self.assertEqual('Pass through \xc2\xb5 and bar', s)
 
617
 
 
618
    def test_missing_format_string(self):
 
619
        e = ErrorWithNoFormat(param='randomvalue')
 
620
        self.assertStartsWith(str(e),
 
621
                              "Unprintable exception ErrorWithNoFormat")
 
622
 
 
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')
 
630
 
 
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(
 
636
            str(e),
 
637
            r'Cannot bind address "example\.com:22":.*Permission denied')
 
638
 
 
639
    def test_transform_rename_failed(self):
 
640
        e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
 
641
        self.assertEqual(
 
642
            u"Failed to rename from to to: readonly file",
 
643
            str(e))
 
644
 
 
645
 
 
646
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
 
647
    """Tests for errors that need to use a branch or repo."""
 
648
 
 
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))
 
655
 
 
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)))
 
661
 
 
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,
 
668
                             str(error))
 
669
 
 
670
    def test_not_branch_bzrdir_with_repo(self):
 
671
        controldir = self.make_repository('repo').controldir
 
672
        err = errors.NotBranchError('path', controldir=controldir)
 
673
        self.assertEqual(
 
674
            'Not a branch: "path": location is a repository.', str(err))
 
675
 
 
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))
 
680
 
 
681
    def test_not_branch_laziness(self):
 
682
        real_bzrdir = self.make_controldir('path')
 
683
        class FakeBzrDir(object):
 
684
            def __init__(self):
 
685
                self.calls = []
 
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)
 
692
        str(err)
 
693
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
 
694
        # Stringifying twice doesn't try to open a repository twice.
 
695
        str(err)
 
696
        self.assertEqual(['open_repository'], fake_bzrdir.calls)