/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
16
17
"""Tests for the formatting and construction of errors."""
18
5050.8.1 by Parth Malwankar
added test to ensure that BzrError subclasses dont use "message" as a name
19
import inspect
20
import re
4634.1.2 by Martin Pool
Add test for CannotBindAddress
21
import socket
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
22
import sys
4634.1.2 by Martin Pool
Add test for CannotBindAddress
23
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
24
from .. import (
6472.2.2 by Jelmer Vernooij
Use controldir rather than bzrdir in a couple more places.
25
    controldir,
1948.1.6 by John Arbash Meinel
Make BzrNewError always return a str object
26
    errors,
3234.2.6 by Alexander Belchenko
because every mail client has different rules to compose command line we should encode arguments to 8 bit string only when needed.
27
    osutils,
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
28
    tests,
3200.2.1 by Robert Collins
* The ``register-branch`` command will now use the public url of the branch
29
    urlutils,
1948.1.6 by John Arbash Meinel
Make BzrNewError always return a str object
30
    )
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
31
from ..sixish import (
32
    text_type,
5579.3.1 by Jelmer Vernooij
Remove unused imports.
33
    )
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
34
35
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
36
class TestErrors(tests.TestCase):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
37
5050.8.1 by Parth Malwankar
added test to ensure that BzrError subclasses dont use "message" as a name
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]")
5050.8.3 by Parth Malwankar
use __subclasses__
47
        for c in errors.BzrError.__subclasses__():
48
            init = getattr(c, '__init__', None)
49
            fmt = getattr(c, '_fmt', None)
5050.8.1 by Parth Malwankar
added test to ensure that BzrError subclasses dont use "message" as a name
50
            if init:
51
                args = inspect.getargspec(init)[0]
52
                self.assertFalse('message' in args,
53
                    ('Argument name "message" not allowed for '
5050.8.3 by Parth Malwankar
use __subclasses__
54
                    '"errors.%s.__init__"' % c.__name__))
5050.8.1 by Parth Malwankar
added test to ensure that BzrError subclasses dont use "message" as a name
55
            if fmt and fmt_pattern.search(fmt):
56
                self.assertFalse(True, ('"message" not allowed in '
5050.8.3 by Parth Malwankar
use __subclasses__
57
                    '"errors.%s._fmt"' % c.__name__))
5050.8.1 by Parth Malwankar
added test to ensure that BzrError subclasses dont use "message" as a name
58
3287.20.2 by John Arbash Meinel
Raise a clear error about the offending filename when there is a filename with bad characters.
59
    def test_bad_filename_encoding(self):
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
60
        error = errors.BadFilenameEncoding(b'bad/filen\xe5me', 'UTF-8')
6670.3.2 by Martin
Avoid PendingDeprecationWarning from assertRegexpMatches
61
        self.assertContainsRe(
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
62
            str(error),
63
            "^Filename b?'bad/filen\\\\xe5me' is not valid in your current"
64
            " filesystem encoding UTF-8$")
3287.20.2 by John Arbash Meinel
Raise a clear error about the offending filename when there is a filename with bad characters.
65
3207.2.1 by jameinel
Add a test that _iter_changes raises a clearer error when we encounter an invalid rename.
66
    def test_corrupt_dirstate(self):
67
        error = errors.CorruptDirstate('path/to/dirstate', 'the reason why')
3221.1.3 by Martin Pool
Review cleanups for CorruptDirstate: use the path everywhere rather than the object, and use more standard phrasing.
68
        self.assertEqualDiff(
69
            "Inconsistency in dirstate file path/to/dirstate.\n"
70
            "Error: the reason why",
71
            str(error))
3207.2.1 by jameinel
Add a test that _iter_changes raises a clearer error when we encounter an invalid rename.
72
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
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
2018.5.24 by Andrew Bennetts
Setting NO_SMART_VFS in environment will disable VFS methods in the smart server. (Robert Collins, John Arbash Meinel, Andrew Bennetts)
80
    def test_disabled_method(self):
81
        error = errors.DisabledMethod("class name")
82
        self.assertEqualDiff(
83
            "The smart server method 'class name' is disabled.", str(error))
84
2255.7.16 by John Arbash Meinel
Make sure adding a duplicate file_id raises DuplicateFileId.
85
    def test_duplicate_file_id(self):
86
        error = errors.DuplicateFileId('a_file_id', 'foo')
87
        self.assertEqualDiff('File id {a_file_id} already exists in inventory'
88
                             ' as foo', str(error))
89
2432.1.19 by Robert Collins
Ensure each HelpIndex has a unique prefix.
90
    def test_duplicate_help_prefix(self):
91
        error = errors.DuplicateHelpPrefix('foo')
92
        self.assertEqualDiff('The prefix foo is in the help search path twice.',
93
            str(error))
94
3445.1.1 by John Arbash Meinel
Start working on a new Graph api to make finding revision numbers faster.
95
    def test_ghost_revisions_have_no_revno(self):
96
        error = errors.GhostRevisionsHaveNoRevno('target', 'ghost_rev')
97
        self.assertEqualDiff("Could not determine revno for {target} because"
98
                             " its ancestry shows a ghost at {ghost_rev}",
99
                             str(error))
100
6672.1.2 by Jelmer Vernooij
Remove breezy.api.
101
    def test_incompatibleVersion(self):
102
        error = errors.IncompatibleVersion("module", [(4, 5, 6), (7, 8, 9)],
103
                (1, 2, 3))
2550.2.3 by Robert Collins
Add require_api API.
104
        self.assertEqualDiff(
6672.1.2 by Jelmer Vernooij
Remove breezy.api.
105
            'API module is not compatible; one of versions '
106
            '[(4, 5, 6), (7, 8, 9)] is required, but current version is '
107
            '(1, 2, 3).',
2550.2.3 by Robert Collins
Add require_api API.
108
            str(error))
109
3207.2.2 by John Arbash Meinel
Fix bug #187169, when an invalid delta is supplied to update_basis_by_delta
110
    def test_inconsistent_delta(self):
111
        error = errors.InconsistentDelta('path', 'file-id', 'reason for foo')
112
        self.assertEqualDiff(
3221.1.8 by Martin Pool
Update error format in test_inconsistent_delta
113
            "An inconsistent delta was supplied involving 'path', 'file-id'\n"
3207.2.2 by John Arbash Meinel
Fix bug #187169, when an invalid delta is supplied to update_basis_by_delta
114
            "reason: reason for foo",
115
            str(error))
116
4505.5.1 by Robert Collins
Add more generic InconsistentDeltaDelta error class for use when the exact cause of an inconsistent delta isn't trivially accessible.
117
    def test_inconsistent_delta_delta(self):
118
        error = errors.InconsistentDeltaDelta([], 'reason')
119
        self.assertEqualDiff(
120
            "An inconsistent delta was supplied: []\nreason: reason",
121
            str(error))
122
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
123
    def test_in_process_transport(self):
124
        error = errors.InProcessTransport('fpp')
125
        self.assertEqualDiff(
126
            "The transport 'fpp' is only accessible within this process.",
127
            str(error))
128
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
129
    def test_invalid_http_range(self):
130
        error = errors.InvalidHttpRange('path',
131
                                        'Content-Range: potatoes 0-00/o0oo0',
132
                                        'bad range')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
133
        self.assertEqual("Invalid http range"
134
                         " 'Content-Range: potatoes 0-00/o0oo0'"
135
                         " for path: bad range",
136
                         str(error))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
137
138
    def test_invalid_range(self):
139
        error = errors.InvalidRange('path', 12, 'bad range')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
140
        self.assertEqual("Invalid range access in path at 12: bad range",
141
                         str(error))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
142
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
143
    def test_inventory_modified(self):
144
        error = errors.InventoryModified("a tree to be repred")
145
        self.assertEqualDiff("The current inventory for the tree 'a tree to "
146
            "be repred' has been modified, so a clean inventory cannot be "
147
            "read without data loss.",
148
            str(error))
149
4294.2.8 by Robert Collins
Reduce round trips pushing new branches substantially.
150
    def test_jail_break(self):
151
        error = errors.JailBreak("some url")
152
        self.assertEqualDiff("An attempt to access a url outside the server"
153
            " jail was made: 'some url'.",
154
            str(error))
155
2255.2.145 by Robert Collins
Support unbreakable locks for trees.
156
    def test_lock_active(self):
157
        error = errors.LockActive("lock description")
158
        self.assertEqualDiff("The lock for 'lock description' is in use and "
159
            "cannot be broken.",
160
            str(error))
161
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
162
    def test_lock_corrupt(self):
163
        error = errors.LockCorrupt("corruption info")
164
        self.assertEqualDiff("Lock is apparently held, but corrupted: "
165
            "corruption info\n"
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
166
            "Use 'brz break-lock' to clear it",
4634.161.1 by Andrew Bennetts
Add LockCorrupt error, and use it to provide nicer handling of unparseable lock/held/info files.
167
            str(error))
168
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
169
    def test_knit_data_stream_incompatible(self):
170
        error = errors.KnitDataStreamIncompatible(
171
            'stream format', 'target format')
172
        self.assertEqual('Cannot insert knit data stream of format '
173
                         '"stream format" into knit of format '
174
                         '"target format".', str(error))
175
3052.2.1 by Robert Collins
Add a new KnitDataStreamUnknown error class for showing formats we can't understand.
176
    def test_knit_data_stream_unknown(self):
177
        error = errors.KnitDataStreamUnknown(
178
            'stream format')
179
        self.assertEqual('Cannot parse knit data stream of format '
180
                         '"stream format".', str(error))
181
2171.1.1 by John Arbash Meinel
Knit index files should ignore empty indexes rather than consider them corrupt.
182
    def test_knit_header_error(self):
183
        error = errors.KnitHeaderError('line foo\n', 'path/to/file')
184
        self.assertEqual("Knit header error: 'line foo\\n' unexpected"
2745.3.2 by Daniel Watkins
Updated tests to reflect new error text.
185
                         " for file \"path/to/file\".", str(error))
2171.1.1 by John Arbash Meinel
Knit index files should ignore empty indexes rather than consider them corrupt.
186
2196.2.5 by John Arbash Meinel
Add an exception class when the knit index storage method is unknown, and properly test for it
187
    def test_knit_index_unknown_method(self):
188
        error = errors.KnitIndexUnknownMethod('http://host/foo.kndx',
189
                                              ['bad', 'no-eol'])
190
        self.assertEqual("Knit index http://host/foo.kndx does not have a"
191
                         " known method in options: ['bad', 'no-eol']",
192
                         str(error))
193
2018.2.3 by Andrew Bennetts
Starting factoring out the smart server client "medium" from the protocol.
194
    def test_medium_not_connected(self):
195
        error = errors.MediumNotConnected("a medium")
196
        self.assertEqualDiff(
197
            "The medium 'a medium' is not connected.", str(error))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
198
2018.2.3 by Andrew Bennetts
Starting factoring out the smart server client "medium" from the protocol.
199
    def test_no_smart_medium(self):
200
        error = errors.NoSmartMedium("a transport")
201
        self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
202
            "smart protocol.",
203
            str(error))
204
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
205
    def test_no_such_id(self):
206
        error = errors.NoSuchId("atree", "anid")
2745.3.2 by Daniel Watkins
Updated tests to reflect new error text.
207
        self.assertEqualDiff("The file id \"anid\" is not present in the tree "
2745.3.3 by Daniel Watkins
Changed to remove need for escaping of quotes.
208
            "atree.",
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
209
            str(error))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
210
1908.11.1 by Robert Collins
Add a new method ``Tree.revision_tree`` which allows access to cached
211
    def test_no_such_revision_in_tree(self):
212
        error = errors.NoSuchRevisionInTree("atree", "anid")
2745.3.3 by Daniel Watkins
Changed to remove need for escaping of quotes.
213
        self.assertEqualDiff("The revision id {anid} is not present in the"
214
                             " tree atree.", str(error))
1908.11.1 by Robert Collins
Add a new method ``Tree.revision_tree`` which allows access to cached
215
        self.assertIsInstance(error, errors.NoSuchRevision)
216
3221.11.2 by Robert Collins
Create basic stackable branch facility.
217
    def test_not_stacked(self):
218
        error = errors.NotStacked('a branch')
219
        self.assertEqualDiff("The branch 'a branch' is not stacked.",
220
            str(error))
221
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
222
    def test_not_write_locked(self):
223
        error = errors.NotWriteLocked('a thing to repr')
224
        self.assertEqualDiff("'a thing to repr' is not write locked but needs "
225
            "to be.",
226
            str(error))
227
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
228
    def test_lock_failed(self):
229
        error = errors.LockFailed('http://canonical.com/', 'readonly transport')
230
        self.assertEqualDiff("Cannot lock http://canonical.com/: readonly transport",
231
            str(error))
232
        self.assertFalse(error.internal_error)
233
2018.2.4 by Robert Collins
separate out the client medium from the client encoding protocol for the smart server.
234
    def test_too_many_concurrent_requests(self):
235
        error = errors.TooManyConcurrentRequests("a medium")
236
        self.assertEqualDiff("The medium 'a medium' has reached its concurrent "
237
            "request limit. Be sure to finish_writing and finish_reading on "
2018.5.134 by Andrew Bennetts
Fix the TooManyConcurrentRequests error message.
238
            "the currently open request.",
2018.2.4 by Robert Collins
separate out the client medium from the client encoding protocol for the smart server.
239
            str(error))
240
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
241
    def test_unavailable_representation(self):
242
        error = errors.UnavailableRepresentation(('key',), "mpdiff", "fulltext")
243
        self.assertEqualDiff("The encoding 'mpdiff' is not available for key "
244
            "('key',) which is encoded as 'fulltext'.",
245
            str(error))
246
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
247
    def test_unknown_hook(self):
248
        error = errors.UnknownHook("branch", "foo")
249
        self.assertEqualDiff("The branch hook 'foo' is unknown in this version"
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
250
            " of breezy.",
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
251
            str(error))
252
        error = errors.UnknownHook("tree", "bar")
253
        self.assertEqualDiff("The tree hook 'bar' is unknown in this version"
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
254
            " of breezy.",
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
255
            str(error))
256
3221.11.2 by Robert Collins
Create basic stackable branch facility.
257
    def test_unstackable_branch_format(self):
258
        format = u'foo'
259
        url = "/foo"
260
        error = errors.UnstackableBranchFormat(format, url)
261
        self.assertEqualDiff(
262
            "The branch '/foo'(foo) is not a stackable format. "
263
            "You will need to upgrade the branch to permit branch stacking.",
264
            str(error))
265
4462.3.2 by Robert Collins
Do not stack on the same branch/repository anymore. This was never supported and would generally result in infinite recursion. Fixes bug 376243.
266
    def test_unstackable_location(self):
267
        error = errors.UnstackableLocationError('foo', 'bar')
268
        self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
269
            str(error))
270
3221.11.2 by Robert Collins
Create basic stackable branch facility.
271
    def test_unstackable_repository_format(self):
272
        format = u'foo'
273
        url = "/foo"
274
        error = errors.UnstackableRepositoryFormat(format, url)
275
        self.assertEqualDiff(
276
            "The repository '/foo'(foo) is not a stackable format. "
277
            "You will need to upgrade the repository to permit branch stacking.",
278
            str(error))
279
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
280
    def test_up_to_date(self):
5582.10.51 by Jelmer Vernooij
Remove use of BzrDirFormat4 in test_errors.
281
        error = errors.UpToDateFormat("someformat")
282
        self.assertEqualDiff(
283
            "The branch format someformat is already at the most "
284
            "recent format.", str(error))
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
285
2052.6.1 by Robert Collins
``Transport.get`` has had its interface made more clear for ease of use.
286
    def test_read_error(self):
287
        # a unicode path to check that %r is being used.
288
        path = u'a path'
289
        error = errors.ReadError(path)
6670.3.2 by Martin
Avoid PendingDeprecationWarning from assertRegexpMatches
290
        self.assertContainsRe(str(error), "^Error reading from u?'a path'.$")
2052.6.1 by Robert Collins
``Transport.get`` has had its interface made more clear for ease of use.
291
2592.1.7 by Robert Collins
A validate that goes boom.
292
    def test_bad_index_format_signature(self):
293
        error = errors.BadIndexFormatSignature("foo", "bar")
294
        self.assertEqual("foo is not an index of type bar.",
295
            str(error))
2052.6.2 by Robert Collins
Merge bzr.dev.
296
2592.1.11 by Robert Collins
Detect truncated indices.
297
    def test_bad_index_data(self):
298
        error = errors.BadIndexData("foo")
299
        self.assertEqual("Error in data for index foo.",
300
            str(error))
301
2592.1.15 by Robert Collins
Detect duplicate key insertion.
302
    def test_bad_index_duplicate_key(self):
303
        error = errors.BadIndexDuplicateKey("foo", "bar")
304
        self.assertEqual("The key 'foo' is already in index 'bar'.",
305
            str(error))
306
2592.1.12 by Robert Collins
Handle basic node adds.
307
    def test_bad_index_key(self):
308
        error = errors.BadIndexKey("foo")
309
        self.assertEqual("The key 'foo' is not a valid key.",
310
            str(error))
311
2592.1.10 by Robert Collins
Make validate detect node reference parsing errors.
312
    def test_bad_index_options(self):
313
        error = errors.BadIndexOptions("foo")
314
        self.assertEqual("Could not parse options for index foo.",
315
            str(error))
316
2592.1.12 by Robert Collins
Handle basic node adds.
317
    def test_bad_index_value(self):
318
        error = errors.BadIndexValue("foo")
319
        self.assertEqual("The value 'foo' is not a valid value.",
320
            str(error))
321
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
322
    def test_bzrerror_from_literal_string(self):
323
        # Some code constructs BzrError from a literal string, in which case
324
        # no further formatting is done.  (I'm not sure raising the base class
325
        # is a great idea, but if the exception is not intended to be caught
326
        # perhaps no more is needed.)
327
        try:
328
            raise errors.BzrError('this is my errors; %d is not expanded')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
329
        except errors.BzrError as e:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
330
            self.assertEqual('this is my errors; %d is not expanded', str(e))
331
2018.2.4 by Robert Collins
separate out the client medium from the client encoding protocol for the smart server.
332
    def test_reading_completed(self):
333
        error = errors.ReadingCompleted("a request")
334
        self.assertEqualDiff("The MediumRequest 'a request' has already had "
335
            "finish_reading called upon it - the request has been completed and"
336
            " no more data may be read.",
337
            str(error))
338
339
    def test_writing_completed(self):
340
        error = errors.WritingCompleted("a request")
341
        self.assertEqualDiff("The MediumRequest 'a request' has already had "
342
            "finish_writing called upon it - accept bytes may not be called "
343
            "anymore.",
344
            str(error))
345
346
    def test_writing_not_completed(self):
347
        error = errors.WritingNotComplete("a request")
348
        self.assertEqualDiff("The MediumRequest 'a request' has not has "
349
            "finish_writing called upon it - until the write phase is complete"
350
            " no data may be read.",
351
            str(error))
352
2052.6.1 by Robert Collins
``Transport.get`` has had its interface made more clear for ease of use.
353
    def test_transport_not_possible(self):
354
        error = errors.TransportNotPossible('readonly', 'original error')
355
        self.assertEqualDiff('Transport operation not possible:'
356
                         ' readonly original error', str(error))
2052.4.4 by John Arbash Meinel
Create a SocketConnectionError to make creating nice errors easier
357
358
    def assertSocketConnectionError(self, expected, *args, **kwargs):
359
        """Check the formatting of a SocketConnectionError exception"""
360
        e = errors.SocketConnectionError(*args, **kwargs)
361
        self.assertEqual(expected, str(e))
362
363
    def test_socket_connection_error(self):
364
        """Test the formatting of SocketConnectionError"""
365
366
        # There should be a default msg about failing to connect
367
        # we only require a host name.
368
        self.assertSocketConnectionError(
369
            'Failed to connect to ahost',
370
            'ahost')
371
372
        # If port is None, we don't put :None
373
        self.assertSocketConnectionError(
374
            'Failed to connect to ahost',
375
            'ahost', port=None)
376
        # But if port is supplied we include it
377
        self.assertSocketConnectionError(
378
            'Failed to connect to ahost:22',
379
            'ahost', port=22)
380
381
        # We can also supply extra information about the error
382
        # with or without a port
383
        self.assertSocketConnectionError(
384
            'Failed to connect to ahost:22; bogus error',
385
            'ahost', port=22, orig_error='bogus error')
386
        self.assertSocketConnectionError(
387
            'Failed to connect to ahost; bogus error',
388
            'ahost', orig_error='bogus error')
389
        # An exception object can be passed rather than a string
390
        orig_error = ValueError('bad value')
391
        self.assertSocketConnectionError(
392
            'Failed to connect to ahost; %s' % (str(orig_error),),
393
            host='ahost', orig_error=orig_error)
394
395
        # And we can supply a custom failure message
396
        self.assertSocketConnectionError(
397
            'Unable to connect to ssh host ahost:444; my_error',
398
            host='ahost', port=444, msg='Unable to connect to ssh host',
399
            orig_error='my_error')
400
3535.8.2 by James Westby
Incorporate spiv's feedback.
401
    def test_target_not_branch(self):
402
        """Test the formatting of TargetNotBranch."""
403
        error = errors.TargetNotBranch('foo')
404
        self.assertEqual(
405
            "Your branch does not have all of the revisions required in "
3535.8.4 by James Westby
Replace "however" with "and" at John's request.
406
            "order to merge this merge directive and the target "
3535.8.3 by James Westby
Use location instead of branch as suggested by Robert.
407
            "location specified in the merge directive is not a branch: "
3535.8.2 by James Westby
Incorporate spiv's feedback.
408
            "foo.", str(error))
409
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
410
    def test_unexpected_smart_server_response(self):
411
        e = errors.UnexpectedSmartServerResponse(('not yes',))
412
        self.assertEqual(
413
            "Could not understand response from smart server: ('not yes',)",
414
            str(e))
2052.4.4 by John Arbash Meinel
Create a SocketConnectionError to make creating nice errors easier
415
2506.2.1 by Andrew Bennetts
Start implementing container format reading and writing.
416
    def test_unknown_container_format(self):
417
        """Test the formatting of UnknownContainerFormatError."""
418
        e = errors.UnknownContainerFormatError('bad format string')
419
        self.assertEqual(
420
            "Unrecognised container format: 'bad format string'",
421
            str(e))
422
423
    def test_unexpected_end_of_container(self):
424
        """Test the formatting of UnexpectedEndOfContainerError."""
425
        e = errors.UnexpectedEndOfContainerError()
426
        self.assertEqual(
427
            "Unexpected end of container stream", str(e))
428
429
    def test_unknown_record_type(self):
430
        """Test the formatting of UnknownRecordTypeError."""
431
        e = errors.UnknownRecordTypeError("X")
432
        self.assertEqual(
433
            "Unknown record type: 'X'",
434
            str(e))
435
2506.3.1 by Andrew Bennetts
More progress:
436
    def test_invalid_record(self):
437
        """Test the formatting of InvalidRecordError."""
438
        e = errors.InvalidRecordError("xxx")
439
        self.assertEqual(
440
            "Invalid record: xxx",
441
            str(e))
442
2506.2.6 by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader.
443
    def test_container_has_excess_data(self):
444
        """Test the formatting of ContainerHasExcessDataError."""
445
        e = errors.ContainerHasExcessDataError("excess bytes")
446
        self.assertEqual(
447
            "Container has data after end marker: 'excess bytes'",
448
            str(e))
449
2506.6.1 by Andrew Bennetts
Return a callable instead of a str from read, and add more validation.
450
    def test_duplicate_record_name_error(self):
451
        """Test the formatting of DuplicateRecordNameError."""
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
452
        e = errors.DuplicateRecordNameError(b"n\xc3\xa5me")
2506.6.1 by Andrew Bennetts
Return a callable instead of a str from read, and add more validation.
453
        self.assertEqual(
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
454
            u"Container has multiple records with the same name: n\xe5me",
455
            text_type(e))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
456
2854.1.1 by Martin Pool
Fix "unprintable error" message for BzrCheckError and others
457
    def test_check_error(self):
458
        e = errors.BzrCheckError('example check failure')
459
        self.assertEqual(
460
            "Internal check failed: example check failure",
461
            str(e))
462
        self.assertTrue(e.internal_error)
2506.6.1 by Andrew Bennetts
Return a callable instead of a str from read, and add more validation.
463
2535.3.40 by Andrew Bennetts
Tidy up more XXXs.
464
    def test_repository_data_stream_error(self):
465
        """Test the formatting of RepositoryDataStreamError."""
466
        e = errors.RepositoryDataStreamError(u"my reason")
467
        self.assertEqual(
468
            "Corrupt or incompatible data stream: my reason", str(e))
469
2978.2.1 by Alexander Belchenko
fix formatting of ImmortalPendingDeletion error message.
470
    def test_immortal_pending_deletion_message(self):
471
        err = errors.ImmortalPendingDeletion('foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
472
        self.assertEqual(
2978.2.1 by Alexander Belchenko
fix formatting of ImmortalPendingDeletion error message.
473
            "Unable to delete transform temporary directory foo.  "
474
            "Please examine foo to see if it contains any files "
475
            "you wish to keep, and delete it when you are done.",
476
            str(err))
477
3006.2.2 by Alexander Belchenko
tests added.
478
    def test_unable_create_symlink(self):
479
        err = errors.UnableCreateSymlink()
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
480
        self.assertEqual(
3006.2.2 by Alexander Belchenko
tests added.
481
            "Unable to create symlink on this platform",
482
            str(err))
483
        err = errors.UnableCreateSymlink(path=u'foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
484
        self.assertEqual(
3006.2.2 by Alexander Belchenko
tests added.
485
            "Unable to create symlink 'foo' on this platform",
486
            str(err))
487
        err = errors.UnableCreateSymlink(path=u'\xb5')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
488
        self.assertEqual(
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
489
            "Unable to create symlink %s on this platform" % repr(u'\xb5'),
3006.2.2 by Alexander Belchenko
tests added.
490
            str(err))
491
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
492
    def test_invalid_url_join(self):
493
        """Test the formatting of InvalidURLJoin."""
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
494
        e = urlutils.InvalidURLJoin('Reason', 'base path', ('args',))
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
495
        self.assertEqual(
496
            "Invalid URL join request: Reason: 'base path' + ('args',)",
497
            str(e))
498
3234.2.6 by Alexander Belchenko
because every mail client has different rules to compose command line we should encode arguments to 8 bit string only when needed.
499
    def test_unable_encode_path(self):
500
        err = errors.UnableEncodePath('foo', 'executable')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
501
        self.assertEqual("Unable to encode executable path 'foo' in "
502
                         "user encoding " + osutils.get_user_encoding(),
503
                         str(err))
3234.2.6 by Alexander Belchenko
because every mail client has different rules to compose command line we should encode arguments to 8 bit string only when needed.
504
3246.3.4 by Daniel Watkins
Added test.
505
    def test_unknown_format(self):
506
        err = errors.UnknownFormatError('bar', kind='foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
507
        self.assertEqual("Unknown foo format: 'bar'", str(err))
3246.3.4 by Daniel Watkins
Added test.
508
3398.1.29 by Ian Clatworthy
add UnknownRules class & test
509
    def test_unknown_rules(self):
510
        err = errors.UnknownRules(['foo', 'bar'])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
511
        self.assertEqual("Unknown rules detected: foo, bar.", str(err))
3398.1.29 by Ian Clatworthy
add UnknownRules class & test
512
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
513
    def test_tip_change_rejected(self):
514
        err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
515
        self.assertEqual(
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
516
            u'Tip change rejected: Unicode message\N{INTERROBANG}',
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
517
            text_type(err))
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
518
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
519
    def test_error_from_smart_server(self):
520
        error_tuple = ('error', 'tuple')
521
        err = errors.ErrorFromSmartServer(error_tuple)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
522
        self.assertEqual(
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
523
            "Error received from smart server: ('error', 'tuple')", str(err))
524
525
    def test_untranslateable_error_from_smart_server(self):
526
        error_tuple = ('error', 'tuple')
527
        orig_err = errors.ErrorFromSmartServer(error_tuple)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
528
        err = errors.UnknownErrorFromSmartServer(orig_err)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
529
        self.assertEqual(
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
530
            "Server sent an unexpected error: ('error', 'tuple')", str(err))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
531
3883.2.3 by Andrew Bennetts
Add test, tweak traceback formatting.
532
    def test_smart_message_handler_error(self):
533
        # Make an exc_info tuple.
534
        try:
535
            raise Exception("example error")
536
        except Exception:
5340.15.2 by John Arbash Meinel
supercede 2.4-613247-cleanup-tests
537
            err = errors.SmartMessageHandlerError(sys.exc_info())
538
        # GZ 2010-11-08: Should not store exc_info in exception instances.
539
        try:
540
            self.assertStartsWith(
541
                str(err), "The message handler raised an exception:\n")
542
            self.assertEndsWith(str(err), "Exception: example error\n")
543
        finally:
544
            del err
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
545
3983.1.8 by Daniel Watkins
Added MustHaveWorkingTree error and accompanying test.
546
    def test_must_have_working_tree(self):
547
        err = errors.MustHaveWorkingTree('foo', 'bar')
3983.1.10 by Daniel Watkins
Made exception message slightly better.
548
        self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
549
                                   " working tree.")
3983.1.8 by Daniel Watkins
Added MustHaveWorkingTree error and accompanying test.
550
3586.1.1 by Ian Clatworthy
add view-related errors and tests
551
    def test_no_such_view(self):
552
        err = errors.NoSuchView('foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
553
        self.assertEqual("No such view: foo.", str(err))
3586.1.1 by Ian Clatworthy
add view-related errors and tests
554
555
    def test_views_not_supported(self):
556
        err = errors.ViewsNotSupported('atree')
557
        err_str = str(err)
558
        self.assertStartsWith(err_str, "Views are not supported by ")
6622.1.30 by Jelmer Vernooij
Some more test fixes.
559
        self.assertEndsWith(err_str, "; use 'brz upgrade' to change your "
3586.1.1 by Ian Clatworthy
add view-related errors and tests
560
            "tree to a later format.")
561
3586.1.9 by Ian Clatworthy
first cut at view command
562
    def test_file_outside_view(self):
563
        err = errors.FileOutsideView('baz', ['foo', 'bar'])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
564
        self.assertEqual('Specified file "baz" is outside the current view: '
565
                         'foo, bar', str(err))
3586.1.9 by Ian Clatworthy
first cut at view command
566
3990.2.2 by Daniel Watkins
Added InvalidShelfId error and accompanying test.
567
    def test_invalid_shelf_id(self):
568
        invalid_id = "foo"
569
        err = errors.InvalidShelfId(invalid_id)
3999.1.1 by Ian Clatworthy
Improve shelf documentation & fix backtrace (Daniel Watkins)
570
        self.assertEqual('"foo" is not a valid shelf id, '
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
571
                         'try a number instead.', str(err))
3990.2.2 by Daniel Watkins
Added InvalidShelfId error and accompanying test.
572
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
573
    def test_unresumable_write_group(self):
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
574
        repo = "dummy repo"
575
        wg_tokens = ['token']
576
        reason = "a reason"
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
577
        err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
578
        self.assertEqual(
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
579
            "Repository dummy repo cannot resume write group "
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
580
            "['token']: a reason", str(err))
581
582
    def test_unsuspendable_write_group(self):
583
        repo = "dummy repo"
584
        err = errors.UnsuspendableWriteGroup(repo)
585
        self.assertEqual(
586
            'Repository dummy repo cannot suspend a write group.', str(err))
587
4734.4.9 by Andrew Bennetts
More tests and comments.
588
    def test_not_branch_no_args(self):
589
        err = errors.NotBranchError('path')
590
        self.assertEqual('Not a branch: "path".', str(err))
591
5050.46.1 by Andrew Bennetts
Suppress unexpected errors during NotBranchError's call to open_repository.
592
    def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
593
        class FakeBzrDir(object):
594
            def open_repository(self):
595
                # str() on the NotBranchError will trigger a call to this,
596
                # which in turn will another, identical NotBranchError.
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
597
                raise errors.NotBranchError('path', controldir=FakeBzrDir())
598
        err = errors.NotBranchError('path', controldir=FakeBzrDir())
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
599
        self.assertEqual('Not a branch: "path": NotBranchError.', str(err))
4734.4.9 by Andrew Bennetts
More tests and comments.
600
5050.7.6 by Parth Malwankar
fixed test name
601
    def test_recursive_bind(self):
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
602
        error = errors.RecursiveBind('foo_bar_branch')
603
        msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
604
            'Please use `brz unbind` to fix.')
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
605
        self.assertEqualDiff(msg, str(error))
606
5609.58.1 by Andrew Bennetts
Fix 'Unprintable exception' when displaying RetryWithNewPacks error.
607
    def test_retry_with_new_packs(self):
608
        fake_exc_info = ('{exc type}', '{exc value}', '{exc traceback}')
609
        error = errors.RetryWithNewPacks(
610
            '{context}', reload_occurred=False, exc_info=fake_exc_info)
611
        self.assertEqual(
612
            'Pack files have changed, reload and retry. context: '
613
            '{context} {exc value}', str(error))
614
2116.3.1 by John Arbash Meinel
Cleanup error tests
615
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
616
class PassThroughError(errors.BzrError):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
617
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
618
    _fmt = """Pass through %(foo)s and %(bar)s"""
2116.3.1 by John Arbash Meinel
Cleanup error tests
619
620
    def __init__(self, foo, bar):
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
621
        errors.BzrError.__init__(self, foo=foo, bar=bar)
622
623
624
class ErrorWithBadFormat(errors.BzrError):
625
626
    _fmt = """One format specifier: %(thing)s"""
627
628
629
class ErrorWithNoFormat(errors.BzrError):
5131.2.6 by Martin
Fix more tests which were failing under -OO that had been missed earlier
630
    __doc__ = """This class has a docstring but no format string."""
2116.3.1 by John Arbash Meinel
Cleanup error tests
631
632
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
633
class TestErrorFormatting(tests.TestCase):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
634
2116.3.1 by John Arbash Meinel
Cleanup error tests
635
    def test_always_str(self):
636
        e = PassThroughError(u'\xb5', 'bar')
637
        self.assertIsInstance(e.__str__(), str)
638
        # In Python str(foo) *must* return a real byte string
639
        # not a Unicode string. The following line would raise a
640
        # Unicode error, because it tries to call str() on the string
641
        # returned from e.__str__(), and it has non ascii characters
642
        s = str(e)
643
        self.assertEqual('Pass through \xc2\xb5 and bar', s)
644
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
645
    def test_missing_format_string(self):
646
        e = ErrorWithNoFormat(param='randomvalue')
6318.2.1 by Martin Packman
Remove deprecated classes and practices from bzrlib.errors
647
        self.assertStartsWith(str(e),
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
648
                              "Unprintable exception ErrorWithNoFormat")
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
649
2116.3.1 by John Arbash Meinel
Cleanup error tests
650
    def test_mismatched_format_args(self):
651
        # Even though ErrorWithBadFormat's format string does not match the
652
        # arguments we constructing it with, we can still stringify an instance
653
        # of this exception. The resulting string will say its unprintable.
654
        e = ErrorWithBadFormat(not_thing='x')
655
        self.assertStartsWith(
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
656
            str(e), 'Unprintable exception ErrorWithBadFormat')
4634.1.2 by Martin Pool
Add test for CannotBindAddress
657
658
    def test_cannot_bind_address(self):
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
659
        # see <https://bugs.launchpad.net/bzr/+bug/286871>
4634.1.2 by Martin Pool
Add test for CannotBindAddress
660
        e = errors.CannotBindAddress('example.com', 22,
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
661
                                     socket.error(13, 'Permission denied'))
662
        self.assertContainsRe(
663
            str(e),
4634.1.2 by Martin Pool
Add test for CannotBindAddress
664
            r'Cannot bind address "example\.com:22":.*Permission denied')
4976.1.1 by Jelmer Vernooij
Add FileTimestampUnavailable exception.
665
5186.2.6 by Martin Pool
Add formatting test for TransformRenameFailed
666
    def test_transform_rename_failed(self):
5186.2.7 by Martin Pool
Update other cases where transform detects failure to rename
667
        e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
668
        self.assertEqual(
5186.2.6 by Martin Pool
Add formatting test for TransformRenameFailed
669
            u"Failed to rename from to to: readonly file",
670
            str(e))
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
671
672
673
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
674
    """Tests for errors that need to use a branch or repo."""
675
676
    def test_no_public_branch(self):
677
        b = self.make_branch('.')
678
        error = errors.NoPublicBranch(b)
679
        url = urlutils.unescape_for_display(b.base, 'ascii')
680
        self.assertEqualDiff(
681
            'There is no public branch set for "%s".' % url, str(error))
682
683
    def test_no_repo(self):
684
        dir = controldir.ControlDir.create(self.get_url())
685
        error = errors.NoRepositoryPresent(dir)
686
        self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
687
        self.assertEqual(-1, str(error).find((dir.transport.base)))
688
689
    def test_corrupt_repository(self):
690
        repo = self.make_repository('.')
691
        error = errors.CorruptRepository(repo)
692
        self.assertEqualDiff("An error has been detected in the repository %s.\n"
693
                             "Please run brz reconcile on this repository." %
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
694
                             repo.controldir.root_transport.base,
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
695
                             str(error))
696
697
    def test_not_branch_bzrdir_with_repo(self):
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
698
        controldir = self.make_repository('repo').controldir
699
        err = errors.NotBranchError('path', controldir=controldir)
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
700
        self.assertEqual(
701
            'Not a branch: "path": location is a repository.', str(err))
702
703
    def test_not_branch_bzrdir_without_repo(self):
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
704
        controldir = self.make_controldir('bzrdir')
705
        err = errors.NotBranchError('path', controldir=controldir)
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
706
        self.assertEqual('Not a branch: "path".', str(err))
707
708
    def test_not_branch_laziness(self):
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
709
        real_bzrdir = self.make_controldir('path')
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
710
        class FakeBzrDir(object):
711
            def __init__(self):
712
                self.calls = []
713
            def open_repository(self):
714
                self.calls.append('open_repository')
715
                raise errors.NoRepositoryPresent(real_bzrdir)
716
        fake_bzrdir = FakeBzrDir()
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
717
        err = errors.NotBranchError('path', controldir=fake_bzrdir)
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
718
        self.assertEqual([], fake_bzrdir.calls)
719
        str(err)
720
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
721
        # Stringifying twice doesn't try to open a repository twice.
722
        str(err)
723
        self.assertEqual(['open_repository'], fake_bzrdir.calls)