/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: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
21
21
import socket
22
22
import sys
23
23
 
24
 
from bzrlib import (
 
24
from .. import (
25
25
    controldir,
26
26
    errors,
27
27
    osutils,
 
28
    tests,
28
29
    urlutils,
29
30
    )
30
 
from bzrlib.tests import (
31
 
    TestCase,
32
 
    TestCaseWithTransport,
33
 
    TestSkipped,
34
 
    )
35
 
 
36
 
 
37
 
class TestErrors(TestCaseWithTransport):
 
31
 
 
32
 
 
33
class TestErrors(tests.TestCase):
38
34
 
39
35
    def test_no_arg_named_message(self):
40
36
        """Ensure the __init__ and _fmt in errors do not have "message" arg.
44
40
        Python 2.5 uses a slot for StandardError.message.
45
41
        See bug #603461
46
42
        """
47
 
        fmt_pattern = re.compile("%\(message\)[sir]")
48
 
        subclasses_present = getattr(errors.BzrError, '__subclasses__', None)
49
 
        if not subclasses_present:
50
 
            raise TestSkipped('__subclasses__ attribute required for classes. '
51
 
                'Requires Python 2.5 or later.')
 
43
        fmt_pattern = re.compile("%\\(message\\)[sir]")
52
44
        for c in errors.BzrError.__subclasses__():
53
45
            init = getattr(c, '__init__', None)
54
46
            fmt = getattr(c, '_fmt', None)
55
47
            if init:
56
 
                args = inspect.getargspec(init)[0]
 
48
                args = inspect.getfullargspec(init)[0]
57
49
                self.assertFalse('message' in args,
58
 
                    ('Argument name "message" not allowed for '
59
 
                    '"errors.%s.__init__"' % c.__name__))
 
50
                                 ('Argument name "message" not allowed for '
 
51
                                  '"errors.%s.__init__"' % c.__name__))
60
52
            if fmt and fmt_pattern.search(fmt):
61
53
                self.assertFalse(True, ('"message" not allowed in '
62
 
                    '"errors.%s._fmt"' % c.__name__))
 
54
                                        '"errors.%s._fmt"' % c.__name__))
63
55
 
64
56
    def test_bad_filename_encoding(self):
65
 
        error = errors.BadFilenameEncoding('bad/filen\xe5me', 'UTF-8')
66
 
        self.assertEqualDiff(
67
 
            "Filename 'bad/filen\\xe5me' is not valid in your current"
68
 
            " filesystem encoding UTF-8",
69
 
            str(error))
70
 
 
71
 
    def test_corrupt_dirstate(self):
72
 
        error = errors.CorruptDirstate('path/to/dirstate', 'the reason why')
73
 
        self.assertEqualDiff(
74
 
            "Inconsistency in dirstate file path/to/dirstate.\n"
75
 
            "Error: the reason why",
76
 
            str(error))
77
 
 
78
 
    def test_dirstate_corrupt(self):
79
 
        error = errors.DirstateCorrupt('.bzr/checkout/dirstate',
80
 
                                       'trailing garbage: "x"')
81
 
        self.assertEqualDiff("The dirstate file (.bzr/checkout/dirstate)"
82
 
            " appears to be corrupt: trailing garbage: \"x\"",
83
 
            str(error))
84
 
 
85
 
    def test_disabled_method(self):
86
 
        error = errors.DisabledMethod("class name")
87
 
        self.assertEqualDiff(
88
 
            "The smart server method 'class name' is disabled.", str(error))
89
 
 
90
 
    def test_duplicate_file_id(self):
91
 
        error = errors.DuplicateFileId('a_file_id', 'foo')
92
 
        self.assertEqualDiff('File id {a_file_id} already exists in inventory'
93
 
                             ' as foo', str(error))
 
57
        error = errors.BadFilenameEncoding(b'bad/filen\xe5me', 'UTF-8')
 
58
        self.assertContainsRe(
 
59
            str(error),
 
60
            "^Filename b?'bad/filen\\\\xe5me' is not valid in your current"
 
61
            " filesystem encoding UTF-8$")
94
62
 
95
63
    def test_duplicate_help_prefix(self):
96
64
        error = errors.DuplicateHelpPrefix('foo')
97
65
        self.assertEqualDiff('The prefix foo is in the help search path twice.',
98
 
            str(error))
 
66
                             str(error))
99
67
 
100
68
    def test_ghost_revisions_have_no_revno(self):
101
69
        error = errors.GhostRevisionsHaveNoRevno('target', 'ghost_rev')
103
71
                             " its ancestry shows a ghost at {ghost_rev}",
104
72
                             str(error))
105
73
 
106
 
    def test_incompatibleAPI(self):
107
 
        error = errors.IncompatibleAPI("module", (1, 2, 3), (4, 5, 6), (7, 8, 9))
 
74
    def test_incompatibleVersion(self):
 
75
        error = errors.IncompatibleVersion("module", [(4, 5, 6), (7, 8, 9)],
 
76
                                           (1, 2, 3))
108
77
        self.assertEqualDiff(
109
 
            'The API for "module" is not compatible with "(1, 2, 3)". '
110
 
            'It supports versions "(4, 5, 6)" to "(7, 8, 9)".',
 
78
            'API module is not compatible; one of versions '
 
79
            '[(4, 5, 6), (7, 8, 9)] is required, but current version is '
 
80
            '(1, 2, 3).',
111
81
            str(error))
112
82
 
113
83
    def test_inconsistent_delta(self):
133
103
        error = errors.InvalidHttpRange('path',
134
104
                                        'Content-Range: potatoes 0-00/o0oo0',
135
105
                                        'bad range')
136
 
        self.assertEquals("Invalid http range"
137
 
                          " 'Content-Range: potatoes 0-00/o0oo0'"
138
 
                          " for path: bad range",
139
 
                          str(error))
 
106
        self.assertEqual("Invalid http range"
 
107
                         " 'Content-Range: potatoes 0-00/o0oo0'"
 
108
                         " for path: bad range",
 
109
                         str(error))
140
110
 
141
111
    def test_invalid_range(self):
142
112
        error = errors.InvalidRange('path', 12, 'bad range')
143
 
        self.assertEquals("Invalid range access in path at 12: bad range",
144
 
                          str(error))
145
 
 
146
 
    def test_inventory_modified(self):
147
 
        error = errors.InventoryModified("a tree to be repred")
148
 
        self.assertEqualDiff("The current inventory for the tree 'a tree to "
149
 
            "be repred' has been modified, so a clean inventory cannot be "
150
 
            "read without data loss.",
151
 
            str(error))
 
113
        self.assertEqual("Invalid range access in path at 12: bad range",
 
114
                         str(error))
152
115
 
153
116
    def test_jail_break(self):
154
117
        error = errors.JailBreak("some url")
155
118
        self.assertEqualDiff("An attempt to access a url outside the server"
156
 
            " jail was made: 'some url'.",
157
 
            str(error))
 
119
                             " jail was made: 'some url'.",
 
120
                             str(error))
158
121
 
159
122
    def test_lock_active(self):
160
123
        error = errors.LockActive("lock description")
161
124
        self.assertEqualDiff("The lock for 'lock description' is in use and "
162
 
            "cannot be broken.",
163
 
            str(error))
 
125
                             "cannot be broken.",
 
126
                             str(error))
164
127
 
165
128
    def test_lock_corrupt(self):
166
129
        error = errors.LockCorrupt("corruption info")
167
130
        self.assertEqualDiff("Lock is apparently held, but corrupted: "
168
 
            "corruption info\n"
169
 
            "Use 'bzr break-lock' to clear it",
170
 
            str(error))
171
 
 
172
 
    def test_knit_data_stream_incompatible(self):
173
 
        error = errors.KnitDataStreamIncompatible(
174
 
            'stream format', 'target format')
175
 
        self.assertEqual('Cannot insert knit data stream of format '
176
 
                         '"stream format" into knit of format '
177
 
                         '"target format".', str(error))
178
 
 
179
 
    def test_knit_data_stream_unknown(self):
180
 
        error = errors.KnitDataStreamUnknown(
181
 
            'stream format')
182
 
        self.assertEqual('Cannot parse knit data stream of format '
183
 
                         '"stream format".', str(error))
184
 
 
185
 
    def test_knit_header_error(self):
186
 
        error = errors.KnitHeaderError('line foo\n', 'path/to/file')
187
 
        self.assertEqual("Knit header error: 'line foo\\n' unexpected"
188
 
                         " for file \"path/to/file\".", str(error))
189
 
 
190
 
    def test_knit_index_unknown_method(self):
191
 
        error = errors.KnitIndexUnknownMethod('http://host/foo.kndx',
192
 
                                              ['bad', 'no-eol'])
193
 
        self.assertEqual("Knit index http://host/foo.kndx does not have a"
194
 
                         " known method in options: ['bad', 'no-eol']",
195
 
                         str(error))
 
131
                             "corruption info\n"
 
132
                             "Use 'brz break-lock' to clear it",
 
133
                             str(error))
196
134
 
197
135
    def test_medium_not_connected(self):
198
136
        error = errors.MediumNotConnected("a medium")
199
137
        self.assertEqualDiff(
200
138
            "The medium 'a medium' is not connected.", str(error))
201
139
 
202
 
    def test_no_public_branch(self):
203
 
        b = self.make_branch('.')
204
 
        error = errors.NoPublicBranch(b)
205
 
        url = urlutils.unescape_for_display(b.base, 'ascii')
206
 
        self.assertEqualDiff(
207
 
            'There is no public branch set for "%s".' % url, str(error))
208
 
 
209
 
    def test_no_repo(self):
210
 
        dir = controldir.ControlDir.create(self.get_url())
211
 
        error = errors.NoRepositoryPresent(dir)
212
 
        self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
213
 
        self.assertEqual(-1, str(error).find((dir.transport.base)))
214
 
 
215
140
    def test_no_smart_medium(self):
216
141
        error = errors.NoSmartMedium("a transport")
217
142
        self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
218
 
            "smart protocol.",
219
 
            str(error))
220
 
 
221
 
    def test_no_help_topic(self):
222
 
        error = errors.NoHelpTopic("topic")
223
 
        self.assertEqualDiff("No help could be found for 'topic'. "
224
 
            "Please use 'bzr help topics' to obtain a list of topics.",
225
 
            str(error))
 
143
                             "smart protocol.",
 
144
                             str(error))
226
145
 
227
146
    def test_no_such_id(self):
228
147
        error = errors.NoSuchId("atree", "anid")
229
148
        self.assertEqualDiff("The file id \"anid\" is not present in the tree "
230
 
            "atree.",
231
 
            str(error))
 
149
                             "atree.",
 
150
                             str(error))
232
151
 
233
152
    def test_no_such_revision_in_tree(self):
234
153
        error = errors.NoSuchRevisionInTree("atree", "anid")
239
158
    def test_not_stacked(self):
240
159
        error = errors.NotStacked('a branch')
241
160
        self.assertEqualDiff("The branch 'a branch' is not stacked.",
242
 
            str(error))
 
161
                             str(error))
243
162
 
244
163
    def test_not_write_locked(self):
245
164
        error = errors.NotWriteLocked('a thing to repr')
246
165
        self.assertEqualDiff("'a thing to repr' is not write locked but needs "
247
 
            "to be.",
248
 
            str(error))
 
166
                             "to be.",
 
167
                             str(error))
249
168
 
250
169
    def test_lock_failed(self):
251
 
        error = errors.LockFailed('http://canonical.com/', 'readonly transport')
 
170
        error = errors.LockFailed(
 
171
            'http://canonical.com/', 'readonly transport')
252
172
        self.assertEqualDiff("Cannot lock http://canonical.com/: readonly transport",
253
 
            str(error))
 
173
                             str(error))
254
174
        self.assertFalse(error.internal_error)
255
175
 
256
176
    def test_too_many_concurrent_requests(self):
257
177
        error = errors.TooManyConcurrentRequests("a medium")
258
178
        self.assertEqualDiff("The medium 'a medium' has reached its concurrent "
259
 
            "request limit. Be sure to finish_writing and finish_reading on "
260
 
            "the currently open request.",
261
 
            str(error))
262
 
 
263
 
    def test_unavailable_representation(self):
264
 
        error = errors.UnavailableRepresentation(('key',), "mpdiff", "fulltext")
265
 
        self.assertEqualDiff("The encoding 'mpdiff' is not available for key "
266
 
            "('key',) which is encoded as 'fulltext'.",
267
 
            str(error))
268
 
 
269
 
    def test_unknown_hook(self):
270
 
        error = errors.UnknownHook("branch", "foo")
271
 
        self.assertEqualDiff("The branch hook 'foo' is unknown in this version"
272
 
            " of bzrlib.",
273
 
            str(error))
274
 
        error = errors.UnknownHook("tree", "bar")
275
 
        self.assertEqualDiff("The tree hook 'bar' is unknown in this version"
276
 
            " of bzrlib.",
277
 
            str(error))
278
 
 
279
 
    def test_unstackable_branch_format(self):
280
 
        format = u'foo'
281
 
        url = "/foo"
282
 
        error = errors.UnstackableBranchFormat(format, url)
283
 
        self.assertEqualDiff(
284
 
            "The branch '/foo'(foo) is not a stackable format. "
285
 
            "You will need to upgrade the branch to permit branch stacking.",
286
 
            str(error))
 
179
                             "request limit. Be sure to finish_writing and finish_reading on "
 
180
                             "the currently open request.",
 
181
                             str(error))
287
182
 
288
183
    def test_unstackable_location(self):
289
184
        error = errors.UnstackableLocationError('foo', 'bar')
290
185
        self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
291
 
            str(error))
 
186
                             str(error))
292
187
 
293
188
    def test_unstackable_repository_format(self):
294
189
        format = u'foo'
305
200
            "The branch format someformat is already at the most "
306
201
            "recent format.", str(error))
307
202
 
308
 
    def test_corrupt_repository(self):
309
 
        repo = self.make_repository('.')
310
 
        error = errors.CorruptRepository(repo)
311
 
        self.assertEqualDiff("An error has been detected in the repository %s.\n"
312
 
                             "Please run bzr reconcile on this repository." %
313
 
                             repo.bzrdir.root_transport.base,
314
 
                             str(error))
315
 
 
316
203
    def test_read_error(self):
317
204
        # a unicode path to check that %r is being used.
318
205
        path = u'a path'
319
206
        error = errors.ReadError(path)
320
 
        self.assertEqualDiff("Error reading from u'a path'.", str(error))
321
 
 
322
 
    def test_bad_index_format_signature(self):
323
 
        error = errors.BadIndexFormatSignature("foo", "bar")
324
 
        self.assertEqual("foo is not an index of type bar.",
325
 
            str(error))
326
 
 
327
 
    def test_bad_index_data(self):
328
 
        error = errors.BadIndexData("foo")
329
 
        self.assertEqual("Error in data for index foo.",
330
 
            str(error))
331
 
 
332
 
    def test_bad_index_duplicate_key(self):
333
 
        error = errors.BadIndexDuplicateKey("foo", "bar")
334
 
        self.assertEqual("The key 'foo' is already in index 'bar'.",
335
 
            str(error))
336
 
 
337
 
    def test_bad_index_key(self):
338
 
        error = errors.BadIndexKey("foo")
339
 
        self.assertEqual("The key 'foo' is not a valid key.",
340
 
            str(error))
341
 
 
342
 
    def test_bad_index_options(self):
343
 
        error = errors.BadIndexOptions("foo")
344
 
        self.assertEqual("Could not parse options for index foo.",
345
 
            str(error))
346
 
 
347
 
    def test_bad_index_value(self):
348
 
        error = errors.BadIndexValue("foo")
349
 
        self.assertEqual("The value 'foo' is not a valid value.",
350
 
            str(error))
 
207
        self.assertContainsRe(str(error), "^Error reading from u?'a path'.$")
351
208
 
352
209
    def test_bzrerror_from_literal_string(self):
353
210
        # Some code constructs BzrError from a literal string, in which case
356
213
        # perhaps no more is needed.)
357
214
        try:
358
215
            raise errors.BzrError('this is my errors; %d is not expanded')
359
 
        except errors.BzrError, e:
 
216
        except errors.BzrError as e:
360
217
            self.assertEqual('this is my errors; %d is not expanded', str(e))
361
218
 
362
219
    def test_reading_completed(self):
363
220
        error = errors.ReadingCompleted("a request")
364
221
        self.assertEqualDiff("The MediumRequest 'a request' has already had "
365
 
            "finish_reading called upon it - the request has been completed and"
366
 
            " no more data may be read.",
367
 
            str(error))
 
222
                             "finish_reading called upon it - the request has been completed and"
 
223
                             " no more data may be read.",
 
224
                             str(error))
368
225
 
369
226
    def test_writing_completed(self):
370
227
        error = errors.WritingCompleted("a request")
371
228
        self.assertEqualDiff("The MediumRequest 'a request' has already had "
372
 
            "finish_writing called upon it - accept bytes may not be called "
373
 
            "anymore.",
374
 
            str(error))
 
229
                             "finish_writing called upon it - accept bytes may not be called "
 
230
                             "anymore.",
 
231
                             str(error))
375
232
 
376
233
    def test_writing_not_completed(self):
377
234
        error = errors.WritingNotComplete("a request")
378
235
        self.assertEqualDiff("The MediumRequest 'a request' has not has "
379
 
            "finish_writing called upon it - until the write phase is complete"
380
 
            " no data may be read.",
381
 
            str(error))
 
236
                             "finish_writing called upon it - until the write phase is complete"
 
237
                             " no data may be read.",
 
238
                             str(error))
382
239
 
383
240
    def test_transport_not_possible(self):
384
241
        error = errors.TransportNotPossible('readonly', 'original error')
385
242
        self.assertEqualDiff('Transport operation not possible:'
386
 
                         ' readonly original error', str(error))
 
243
                             ' readonly original error', str(error))
387
244
 
388
245
    def assertSocketConnectionError(self, expected, *args, **kwargs):
389
246
        """Check the formatting of a SocketConnectionError exception"""
437
294
            "location specified in the merge directive is not a branch: "
438
295
            "foo.", str(error))
439
296
 
440
 
    def test_malformed_bug_identifier(self):
441
 
        """Test the formatting of MalformedBugIdentifier."""
442
 
        error = errors.MalformedBugIdentifier('bogus', 'reason for bogosity')
443
 
        self.assertEqual(
444
 
            'Did not understand bug identifier bogus: reason for bogosity. '
445
 
            'See "bzr help bugs" for more information on this feature.',
446
 
            str(error))
447
 
 
448
 
    def test_unknown_bug_tracker_abbreviation(self):
449
 
        """Test the formatting of UnknownBugTrackerAbbreviation."""
450
 
        branch = self.make_branch('some_branch')
451
 
        error = errors.UnknownBugTrackerAbbreviation('xxx', branch)
452
 
        self.assertEqual(
453
 
            "Cannot find registered bug tracker called xxx on %s" % branch,
454
 
            str(error))
455
 
 
456
297
    def test_unexpected_smart_server_response(self):
457
298
        e = errors.UnexpectedSmartServerResponse(('not yes',))
458
299
        self.assertEqual(
495
336
 
496
337
    def test_duplicate_record_name_error(self):
497
338
        """Test the formatting of DuplicateRecordNameError."""
498
 
        e = errors.DuplicateRecordNameError(u"n\xe5me".encode('utf-8'))
 
339
        e = errors.DuplicateRecordNameError(b"n\xc3\xa5me")
499
340
        self.assertEqual(
500
 
            "Container has multiple records with the same name: n\xc3\xa5me",
 
341
            u"Container has multiple records with the same name: n\xe5me",
501
342
            str(e))
502
343
 
503
344
    def test_check_error(self):
504
 
        # This has a member called 'message', which is problematic in
505
 
        # python2.5 because that is a slot on the base Exception class
506
345
        e = errors.BzrCheckError('example check failure')
507
346
        self.assertEqual(
508
347
            "Internal check failed: example check failure",
517
356
 
518
357
    def test_immortal_pending_deletion_message(self):
519
358
        err = errors.ImmortalPendingDeletion('foo')
520
 
        self.assertEquals(
 
359
        self.assertEqual(
521
360
            "Unable to delete transform temporary directory foo.  "
522
361
            "Please examine foo to see if it contains any files "
523
362
            "you wish to keep, and delete it when you are done.",
524
363
            str(err))
525
364
 
526
 
    def test_unable_create_symlink(self):
527
 
        err = errors.UnableCreateSymlink()
528
 
        self.assertEquals(
529
 
            "Unable to create symlink on this platform",
530
 
            str(err))
531
 
        err = errors.UnableCreateSymlink(path=u'foo')
532
 
        self.assertEquals(
533
 
            "Unable to create symlink 'foo' on this platform",
534
 
            str(err))
535
 
        err = errors.UnableCreateSymlink(path=u'\xb5')
536
 
        self.assertEquals(
537
 
            "Unable to create symlink u'\\xb5' on this platform",
538
 
            str(err))
539
 
 
540
365
    def test_invalid_url_join(self):
541
366
        """Test the formatting of InvalidURLJoin."""
542
 
        e = errors.InvalidURLJoin('Reason', 'base path', ('args',))
 
367
        e = urlutils.InvalidURLJoin('Reason', 'base path', ('args',))
543
368
        self.assertEqual(
544
369
            "Invalid URL join request: Reason: 'base path' + ('args',)",
545
370
            str(e))
546
371
 
547
 
    def test_incorrect_url(self):
548
 
        err = errors.InvalidBugTrackerURL('foo', 'http://bug.com/')
549
 
        self.assertEquals(
550
 
            ("The URL for bug tracker \"foo\" doesn't contain {id}: "
551
 
             "http://bug.com/"),
552
 
            str(err))
553
 
 
554
372
    def test_unable_encode_path(self):
555
373
        err = errors.UnableEncodePath('foo', 'executable')
556
 
        self.assertEquals("Unable to encode executable path 'foo' in "
557
 
            "user encoding " + osutils.get_user_encoding(),
558
 
            str(err))
 
374
        self.assertEqual("Unable to encode executable path 'foo' in "
 
375
                         "user encoding " + osutils.get_user_encoding(),
 
376
                         str(err))
559
377
 
560
378
    def test_unknown_format(self):
561
379
        err = errors.UnknownFormatError('bar', kind='foo')
562
 
        self.assertEquals("Unknown foo format: 'bar'", str(err))
563
 
 
564
 
    def test_unknown_rules(self):
565
 
        err = errors.UnknownRules(['foo', 'bar'])
566
 
        self.assertEquals("Unknown rules detected: foo, bar.", str(err))
 
380
        self.assertEqual("Unknown foo format: 'bar'", str(err))
567
381
 
568
382
    def test_tip_change_rejected(self):
569
383
        err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
570
 
        self.assertEquals(
 
384
        self.assertEqual(
571
385
            u'Tip change rejected: Unicode message\N{INTERROBANG}',
572
 
            unicode(err))
573
 
        self.assertEquals(
574
 
            'Tip change rejected: Unicode message\xe2\x80\xbd',
575
386
            str(err))
576
387
 
577
388
    def test_error_from_smart_server(self):
578
389
        error_tuple = ('error', 'tuple')
579
390
        err = errors.ErrorFromSmartServer(error_tuple)
580
 
        self.assertEquals(
 
391
        self.assertEqual(
581
392
            "Error received from smart server: ('error', 'tuple')", str(err))
582
393
 
583
394
    def test_untranslateable_error_from_smart_server(self):
584
395
        error_tuple = ('error', 'tuple')
585
396
        orig_err = errors.ErrorFromSmartServer(error_tuple)
586
397
        err = errors.UnknownErrorFromSmartServer(orig_err)
587
 
        self.assertEquals(
 
398
        self.assertEqual(
588
399
            "Server sent an unexpected error: ('error', 'tuple')", str(err))
589
400
 
590
401
    def test_smart_message_handler_error(self):
601
412
        finally:
602
413
            del err
603
414
 
604
 
    def test_must_have_working_tree(self):
605
 
        err = errors.MustHaveWorkingTree('foo', 'bar')
606
 
        self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
607
 
                                   " working tree.")
608
 
 
609
 
    def test_no_such_view(self):
610
 
        err = errors.NoSuchView('foo')
611
 
        self.assertEquals("No such view: foo.", str(err))
612
 
 
613
 
    def test_views_not_supported(self):
614
 
        err = errors.ViewsNotSupported('atree')
615
 
        err_str = str(err)
616
 
        self.assertStartsWith(err_str, "Views are not supported by ")
617
 
        self.assertEndsWith(err_str, "; use 'bzr upgrade' to change your "
618
 
            "tree to a later format.")
619
 
 
620
 
    def test_file_outside_view(self):
621
 
        err = errors.FileOutsideView('baz', ['foo', 'bar'])
622
 
        self.assertEquals('Specified file "baz" is outside the current view: '
623
 
            'foo, bar', str(err))
624
 
 
625
 
    def test_invalid_shelf_id(self):
626
 
        invalid_id = "foo"
627
 
        err = errors.InvalidShelfId(invalid_id)
628
 
        self.assertEqual('"foo" is not a valid shelf id, '
629
 
            'try a number instead.', str(err))
630
 
 
631
415
    def test_unresumable_write_group(self):
632
416
        repo = "dummy repo"
633
417
        wg_tokens = ['token']
647
431
        err = errors.NotBranchError('path')
648
432
        self.assertEqual('Not a branch: "path".', str(err))
649
433
 
650
 
    def test_not_branch_bzrdir_with_repo(self):
651
 
        bzrdir = self.make_repository('repo').bzrdir
652
 
        err = errors.NotBranchError('path', bzrdir=bzrdir)
653
 
        self.assertEqual(
654
 
            'Not a branch: "path": location is a repository.', str(err))
655
 
 
656
 
    def test_not_branch_bzrdir_without_repo(self):
657
 
        bzrdir = self.make_bzrdir('bzrdir')
658
 
        err = errors.NotBranchError('path', bzrdir=bzrdir)
659
 
        self.assertEqual('Not a branch: "path".', str(err))
660
 
 
661
434
    def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
662
435
        class FakeBzrDir(object):
663
436
            def open_repository(self):
664
437
                # str() on the NotBranchError will trigger a call to this,
665
438
                # which in turn will another, identical NotBranchError.
666
 
                raise errors.NotBranchError('path', bzrdir=FakeBzrDir())
667
 
        err = errors.NotBranchError('path', bzrdir=FakeBzrDir())
668
 
        self.assertEqual('Not a branch: "path".', str(err))
669
 
 
670
 
    def test_not_branch_laziness(self):
671
 
        real_bzrdir = self.make_bzrdir('path')
672
 
        class FakeBzrDir(object):
673
 
            def __init__(self):
674
 
                self.calls = []
675
 
            def open_repository(self):
676
 
                self.calls.append('open_repository')
677
 
                raise errors.NoRepositoryPresent(real_bzrdir)
678
 
        fake_bzrdir = FakeBzrDir()
679
 
        err = errors.NotBranchError('path', bzrdir=fake_bzrdir)
680
 
        self.assertEqual([], fake_bzrdir.calls)
681
 
        str(err)
682
 
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
683
 
        # Stringifying twice doesn't try to open a repository twice.
684
 
        str(err)
685
 
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
686
 
 
687
 
    def test_invalid_pattern(self):
688
 
        error = errors.InvalidPattern('Bad pattern msg.')
689
 
        self.assertEqualDiff("Invalid pattern(s) found. Bad pattern msg.",
690
 
            str(error))
 
439
                raise errors.NotBranchError('path', controldir=FakeBzrDir())
 
440
        err = errors.NotBranchError('path', controldir=FakeBzrDir())
 
441
        self.assertEqual('Not a branch: "path": NotBranchError.', str(err))
691
442
 
692
443
    def test_recursive_bind(self):
693
444
        error = errors.RecursiveBind('foo_bar_branch')
694
445
        msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
695
 
            'Please use `bzr unbind` to fix.')
 
446
               'Please use `brz unbind` to fix.')
696
447
        self.assertEqualDiff(msg, str(error))
697
448
 
698
449
    def test_retry_with_new_packs(self):
721
472
    __doc__ = """This class has a docstring but no format string."""
722
473
 
723
474
 
724
 
class TestErrorFormatting(TestCase):
 
475
class TestErrorFormatting(tests.TestCase):
725
476
 
726
477
    def test_always_str(self):
727
478
        e = PassThroughError(u'\xb5', 'bar')
728
479
        self.assertIsInstance(e.__str__(), str)
729
 
        # In Python str(foo) *must* return a real byte string
 
480
        # In Python 2 str(foo) *must* return a real byte string
730
481
        # not a Unicode string. The following line would raise a
731
482
        # Unicode error, because it tries to call str() on the string
732
483
        # returned from e.__str__(), and it has non ascii characters
733
484
        s = str(e)
734
 
        self.assertEqual('Pass through \xc2\xb5 and bar', s)
 
485
        self.assertEqual('Pass through \xb5 and bar', s)
735
486
 
736
487
    def test_missing_format_string(self):
737
488
        e = ErrorWithNoFormat(param='randomvalue')
738
489
        self.assertStartsWith(str(e),
739
 
            "Unprintable exception ErrorWithNoFormat")
 
490
                              "Unprintable exception ErrorWithNoFormat")
740
491
 
741
492
    def test_mismatched_format_args(self):
742
493
        # Even though ErrorWithBadFormat's format string does not match the
749
500
    def test_cannot_bind_address(self):
750
501
        # see <https://bugs.launchpad.net/bzr/+bug/286871>
751
502
        e = errors.CannotBindAddress('example.com', 22,
752
 
            socket.error(13, 'Permission denied'))
753
 
        self.assertContainsRe(str(e),
 
503
                                     socket.error(13, 'Permission denied'))
 
504
        self.assertContainsRe(
 
505
            str(e),
754
506
            r'Cannot bind address "example\.com:22":.*Permission denied')
755
507
 
756
 
    def test_file_timestamp_unavailable(self):            
757
 
        e = errors.FileTimestampUnavailable("/path/foo")
758
 
        self.assertEquals("The filestamp for /path/foo is not available.",
759
 
            str(e))
760
 
            
761
 
    def test_transform_rename_failed(self):
762
 
        e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
763
 
        self.assertEquals(
764
 
            u"Failed to rename from to to: readonly file",
765
 
            str(e))
 
508
 
 
509
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
 
510
    """Tests for errors that need to use a branch or repo."""
 
511
 
 
512
    def test_no_public_branch(self):
 
513
        b = self.make_branch('.')
 
514
        error = errors.NoPublicBranch(b)
 
515
        url = urlutils.unescape_for_display(b.base, 'ascii')
 
516
        self.assertEqualDiff(
 
517
            'There is no public branch set for "%s".' % url, str(error))
 
518
 
 
519
    def test_no_repo(self):
 
520
        dir = controldir.ControlDir.create(self.get_url())
 
521
        error = errors.NoRepositoryPresent(dir)
 
522
        self.assertNotEqual(-1,
 
523
                            str(error).find((dir.transport.clone('..').base)))
 
524
        self.assertEqual(-1, str(error).find((dir.transport.base)))
 
525
 
 
526
    def test_corrupt_repository(self):
 
527
        repo = self.make_repository('.')
 
528
        error = errors.CorruptRepository(repo)
 
529
        self.assertEqualDiff("An error has been detected in the repository %s.\n"
 
530
                             "Please run brz reconcile on this repository." %
 
531
                             repo.controldir.root_transport.base,
 
532
                             str(error))
 
533
 
 
534
    def test_not_branch_bzrdir_with_repo(self):
 
535
        controldir = self.make_repository('repo').controldir
 
536
        err = errors.NotBranchError('path', controldir=controldir)
 
537
        self.assertEqual(
 
538
            'Not a branch: "path": location is a repository.', str(err))
 
539
 
 
540
    def test_not_branch_bzrdir_without_repo(self):
 
541
        controldir = self.make_controldir('bzrdir')
 
542
        err = errors.NotBranchError('path', controldir=controldir)
 
543
        self.assertEqual('Not a branch: "path".', str(err))
 
544
 
 
545
    def test_not_branch_laziness(self):
 
546
        real_bzrdir = self.make_controldir('path')
 
547
 
 
548
        class FakeBzrDir(object):
 
549
            def __init__(self):
 
550
                self.calls = []
 
551
 
 
552
            def open_repository(self):
 
553
                self.calls.append('open_repository')
 
554
                raise errors.NoRepositoryPresent(real_bzrdir)
 
555
        fake_bzrdir = FakeBzrDir()
 
556
        err = errors.NotBranchError('path', controldir=fake_bzrdir)
 
557
        self.assertEqual([], fake_bzrdir.calls)
 
558
        str(err)
 
559
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
 
560
        # Stringifying twice doesn't try to open a repository twice.
 
561
        str(err)
 
562
        self.assertEqual(['open_repository'], fake_bzrdir.calls)