/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
2018.2.3 by Andrew Bennetts
Starting factoring out the smart server client "medium" from the protocol.
169
    def test_medium_not_connected(self):
170
        error = errors.MediumNotConnected("a medium")
171
        self.assertEqualDiff(
172
            "The medium 'a medium' is not connected.", str(error))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
173
2018.2.3 by Andrew Bennetts
Starting factoring out the smart server client "medium" from the protocol.
174
    def test_no_smart_medium(self):
175
        error = errors.NoSmartMedium("a transport")
176
        self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
177
            "smart protocol.",
178
            str(error))
179
2432.1.4 by Robert Collins
Add an explicit error for missing help topics.
180
    def test_no_help_topic(self):
181
        error = errors.NoHelpTopic("topic")
182
        self.assertEqualDiff("No help could be found for 'topic'. "
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
183
            "Please use 'brz help topics' to obtain a list of topics.",
2432.1.4 by Robert Collins
Add an explicit error for missing help topics.
184
            str(error))
185
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
186
    def test_no_such_id(self):
187
        error = errors.NoSuchId("atree", "anid")
2745.3.2 by Daniel Watkins
Updated tests to reflect new error text.
188
        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.
189
            "atree.",
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
190
            str(error))
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
191
1908.11.1 by Robert Collins
Add a new method ``Tree.revision_tree`` which allows access to cached
192
    def test_no_such_revision_in_tree(self):
193
        error = errors.NoSuchRevisionInTree("atree", "anid")
2745.3.3 by Daniel Watkins
Changed to remove need for escaping of quotes.
194
        self.assertEqualDiff("The revision id {anid} is not present in the"
195
                             " tree atree.", str(error))
1908.11.1 by Robert Collins
Add a new method ``Tree.revision_tree`` which allows access to cached
196
        self.assertIsInstance(error, errors.NoSuchRevision)
197
3221.11.2 by Robert Collins
Create basic stackable branch facility.
198
    def test_not_stacked(self):
199
        error = errors.NotStacked('a branch')
200
        self.assertEqualDiff("The branch 'a branch' is not stacked.",
201
            str(error))
202
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
203
    def test_not_write_locked(self):
204
        error = errors.NotWriteLocked('a thing to repr')
205
        self.assertEqualDiff("'a thing to repr' is not write locked but needs "
206
            "to be.",
207
            str(error))
208
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
209
    def test_lock_failed(self):
210
        error = errors.LockFailed('http://canonical.com/', 'readonly transport')
211
        self.assertEqualDiff("Cannot lock http://canonical.com/: readonly transport",
212
            str(error))
213
        self.assertFalse(error.internal_error)
214
2018.2.4 by Robert Collins
separate out the client medium from the client encoding protocol for the smart server.
215
    def test_too_many_concurrent_requests(self):
216
        error = errors.TooManyConcurrentRequests("a medium")
217
        self.assertEqualDiff("The medium 'a medium' has reached its concurrent "
218
            "request limit. Be sure to finish_writing and finish_reading on "
2018.5.134 by Andrew Bennetts
Fix the TooManyConcurrentRequests error message.
219
            "the currently open request.",
2018.2.4 by Robert Collins
separate out the client medium from the client encoding protocol for the smart server.
220
            str(error))
221
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
222
    def test_unavailable_representation(self):
223
        error = errors.UnavailableRepresentation(('key',), "mpdiff", "fulltext")
224
        self.assertEqualDiff("The encoding 'mpdiff' is not available for key "
225
            "('key',) which is encoded as 'fulltext'.",
226
            str(error))
227
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
228
    def test_unknown_hook(self):
229
        error = errors.UnknownHook("branch", "foo")
230
        self.assertEqualDiff("The branch hook 'foo' is unknown in this version"
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
231
            " of breezy.",
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
232
            str(error))
233
        error = errors.UnknownHook("tree", "bar")
234
        self.assertEqualDiff("The tree hook 'bar' is unknown in this version"
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
235
            " of breezy.",
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
236
            str(error))
237
3221.11.2 by Robert Collins
Create basic stackable branch facility.
238
    def test_unstackable_branch_format(self):
239
        format = u'foo'
240
        url = "/foo"
241
        error = errors.UnstackableBranchFormat(format, url)
242
        self.assertEqualDiff(
243
            "The branch '/foo'(foo) is not a stackable format. "
244
            "You will need to upgrade the branch to permit branch stacking.",
245
            str(error))
246
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.
247
    def test_unstackable_location(self):
248
        error = errors.UnstackableLocationError('foo', 'bar')
249
        self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
250
            str(error))
251
3221.11.2 by Robert Collins
Create basic stackable branch facility.
252
    def test_unstackable_repository_format(self):
253
        format = u'foo'
254
        url = "/foo"
255
        error = errors.UnstackableRepositoryFormat(format, url)
256
        self.assertEqualDiff(
257
            "The repository '/foo'(foo) is not a stackable format. "
258
            "You will need to upgrade the repository to permit branch stacking.",
259
            str(error))
260
1534.5.7 by Robert Collins
Start factoring out the upgrade policy logic.
261
    def test_up_to_date(self):
5582.10.51 by Jelmer Vernooij
Remove use of BzrDirFormat4 in test_errors.
262
        error = errors.UpToDateFormat("someformat")
263
        self.assertEqualDiff(
264
            "The branch format someformat is already at the most "
265
            "recent format.", str(error))
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
266
2052.6.1 by Robert Collins
``Transport.get`` has had its interface made more clear for ease of use.
267
    def test_read_error(self):
268
        # a unicode path to check that %r is being used.
269
        path = u'a path'
270
        error = errors.ReadError(path)
6670.3.2 by Martin
Avoid PendingDeprecationWarning from assertRegexpMatches
271
        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.
272
2592.1.7 by Robert Collins
A validate that goes boom.
273
    def test_bad_index_format_signature(self):
274
        error = errors.BadIndexFormatSignature("foo", "bar")
275
        self.assertEqual("foo is not an index of type bar.",
276
            str(error))
2052.6.2 by Robert Collins
Merge bzr.dev.
277
2592.1.11 by Robert Collins
Detect truncated indices.
278
    def test_bad_index_data(self):
279
        error = errors.BadIndexData("foo")
280
        self.assertEqual("Error in data for index foo.",
281
            str(error))
282
2592.1.15 by Robert Collins
Detect duplicate key insertion.
283
    def test_bad_index_duplicate_key(self):
284
        error = errors.BadIndexDuplicateKey("foo", "bar")
285
        self.assertEqual("The key 'foo' is already in index 'bar'.",
286
            str(error))
287
2592.1.12 by Robert Collins
Handle basic node adds.
288
    def test_bad_index_key(self):
289
        error = errors.BadIndexKey("foo")
290
        self.assertEqual("The key 'foo' is not a valid key.",
291
            str(error))
292
2592.1.10 by Robert Collins
Make validate detect node reference parsing errors.
293
    def test_bad_index_options(self):
294
        error = errors.BadIndexOptions("foo")
295
        self.assertEqual("Could not parse options for index foo.",
296
            str(error))
297
2592.1.12 by Robert Collins
Handle basic node adds.
298
    def test_bad_index_value(self):
299
        error = errors.BadIndexValue("foo")
300
        self.assertEqual("The value 'foo' is not a valid value.",
301
            str(error))
302
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
303
    def test_bzrerror_from_literal_string(self):
304
        # Some code constructs BzrError from a literal string, in which case
305
        # no further formatting is done.  (I'm not sure raising the base class
306
        # is a great idea, but if the exception is not intended to be caught
307
        # perhaps no more is needed.)
308
        try:
309
            raise errors.BzrError('this is my errors; %d is not expanded')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
310
        except errors.BzrError as e:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
311
            self.assertEqual('this is my errors; %d is not expanded', str(e))
312
2018.2.4 by Robert Collins
separate out the client medium from the client encoding protocol for the smart server.
313
    def test_reading_completed(self):
314
        error = errors.ReadingCompleted("a request")
315
        self.assertEqualDiff("The MediumRequest 'a request' has already had "
316
            "finish_reading called upon it - the request has been completed and"
317
            " no more data may be read.",
318
            str(error))
319
320
    def test_writing_completed(self):
321
        error = errors.WritingCompleted("a request")
322
        self.assertEqualDiff("The MediumRequest 'a request' has already had "
323
            "finish_writing called upon it - accept bytes may not be called "
324
            "anymore.",
325
            str(error))
326
327
    def test_writing_not_completed(self):
328
        error = errors.WritingNotComplete("a request")
329
        self.assertEqualDiff("The MediumRequest 'a request' has not has "
330
            "finish_writing called upon it - until the write phase is complete"
331
            " no data may be read.",
332
            str(error))
333
2052.6.1 by Robert Collins
``Transport.get`` has had its interface made more clear for ease of use.
334
    def test_transport_not_possible(self):
335
        error = errors.TransportNotPossible('readonly', 'original error')
336
        self.assertEqualDiff('Transport operation not possible:'
337
                         ' readonly original error', str(error))
2052.4.4 by John Arbash Meinel
Create a SocketConnectionError to make creating nice errors easier
338
339
    def assertSocketConnectionError(self, expected, *args, **kwargs):
340
        """Check the formatting of a SocketConnectionError exception"""
341
        e = errors.SocketConnectionError(*args, **kwargs)
342
        self.assertEqual(expected, str(e))
343
344
    def test_socket_connection_error(self):
345
        """Test the formatting of SocketConnectionError"""
346
347
        # There should be a default msg about failing to connect
348
        # we only require a host name.
349
        self.assertSocketConnectionError(
350
            'Failed to connect to ahost',
351
            'ahost')
352
353
        # If port is None, we don't put :None
354
        self.assertSocketConnectionError(
355
            'Failed to connect to ahost',
356
            'ahost', port=None)
357
        # But if port is supplied we include it
358
        self.assertSocketConnectionError(
359
            'Failed to connect to ahost:22',
360
            'ahost', port=22)
361
362
        # We can also supply extra information about the error
363
        # with or without a port
364
        self.assertSocketConnectionError(
365
            'Failed to connect to ahost:22; bogus error',
366
            'ahost', port=22, orig_error='bogus error')
367
        self.assertSocketConnectionError(
368
            'Failed to connect to ahost; bogus error',
369
            'ahost', orig_error='bogus error')
370
        # An exception object can be passed rather than a string
371
        orig_error = ValueError('bad value')
372
        self.assertSocketConnectionError(
373
            'Failed to connect to ahost; %s' % (str(orig_error),),
374
            host='ahost', orig_error=orig_error)
375
376
        # And we can supply a custom failure message
377
        self.assertSocketConnectionError(
378
            'Unable to connect to ssh host ahost:444; my_error',
379
            host='ahost', port=444, msg='Unable to connect to ssh host',
380
            orig_error='my_error')
381
3535.8.2 by James Westby
Incorporate spiv's feedback.
382
    def test_target_not_branch(self):
383
        """Test the formatting of TargetNotBranch."""
384
        error = errors.TargetNotBranch('foo')
385
        self.assertEqual(
386
            "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.
387
            "order to merge this merge directive and the target "
3535.8.3 by James Westby
Use location instead of branch as suggested by Robert.
388
            "location specified in the merge directive is not a branch: "
3535.8.2 by James Westby
Incorporate spiv's feedback.
389
            "foo.", str(error))
390
2376.4.26 by Jonathan Lange
Tests for MalformedBugIdentifier and new error UnknownBugTrackerAbbreviation.
391
    def test_malformed_bug_identifier(self):
392
        """Test the formatting of MalformedBugIdentifier."""
393
        error = errors.MalformedBugIdentifier('bogus', 'reason for bogosity')
394
        self.assertEqual(
3535.10.1 by James Westby
Point to "bzr help bugs" from MalformedBugIdentifier.
395
            'Did not understand bug identifier bogus: reason for bogosity. '
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
396
            'See "brz help bugs" for more information on this feature.',
2376.4.26 by Jonathan Lange
Tests for MalformedBugIdentifier and new error UnknownBugTrackerAbbreviation.
397
            str(error))
398
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
399
    def test_unexpected_smart_server_response(self):
400
        e = errors.UnexpectedSmartServerResponse(('not yes',))
401
        self.assertEqual(
402
            "Could not understand response from smart server: ('not yes',)",
403
            str(e))
2052.4.4 by John Arbash Meinel
Create a SocketConnectionError to make creating nice errors easier
404
2506.2.1 by Andrew Bennetts
Start implementing container format reading and writing.
405
    def test_unknown_container_format(self):
406
        """Test the formatting of UnknownContainerFormatError."""
407
        e = errors.UnknownContainerFormatError('bad format string')
408
        self.assertEqual(
409
            "Unrecognised container format: 'bad format string'",
410
            str(e))
411
412
    def test_unexpected_end_of_container(self):
413
        """Test the formatting of UnexpectedEndOfContainerError."""
414
        e = errors.UnexpectedEndOfContainerError()
415
        self.assertEqual(
416
            "Unexpected end of container stream", str(e))
417
418
    def test_unknown_record_type(self):
419
        """Test the formatting of UnknownRecordTypeError."""
420
        e = errors.UnknownRecordTypeError("X")
421
        self.assertEqual(
422
            "Unknown record type: 'X'",
423
            str(e))
424
2506.3.1 by Andrew Bennetts
More progress:
425
    def test_invalid_record(self):
426
        """Test the formatting of InvalidRecordError."""
427
        e = errors.InvalidRecordError("xxx")
428
        self.assertEqual(
429
            "Invalid record: xxx",
430
            str(e))
431
2506.2.6 by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader.
432
    def test_container_has_excess_data(self):
433
        """Test the formatting of ContainerHasExcessDataError."""
434
        e = errors.ContainerHasExcessDataError("excess bytes")
435
        self.assertEqual(
436
            "Container has data after end marker: 'excess bytes'",
437
            str(e))
438
2506.6.1 by Andrew Bennetts
Return a callable instead of a str from read, and add more validation.
439
    def test_duplicate_record_name_error(self):
440
        """Test the formatting of DuplicateRecordNameError."""
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
441
        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.
442
        self.assertEqual(
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
443
            u"Container has multiple records with the same name: n\xe5me",
444
            text_type(e))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
445
2854.1.1 by Martin Pool
Fix "unprintable error" message for BzrCheckError and others
446
    def test_check_error(self):
447
        e = errors.BzrCheckError('example check failure')
448
        self.assertEqual(
449
            "Internal check failed: example check failure",
450
            str(e))
451
        self.assertTrue(e.internal_error)
2506.6.1 by Andrew Bennetts
Return a callable instead of a str from read, and add more validation.
452
2535.3.40 by Andrew Bennetts
Tidy up more XXXs.
453
    def test_repository_data_stream_error(self):
454
        """Test the formatting of RepositoryDataStreamError."""
455
        e = errors.RepositoryDataStreamError(u"my reason")
456
        self.assertEqual(
457
            "Corrupt or incompatible data stream: my reason", str(e))
458
2978.2.1 by Alexander Belchenko
fix formatting of ImmortalPendingDeletion error message.
459
    def test_immortal_pending_deletion_message(self):
460
        err = errors.ImmortalPendingDeletion('foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
461
        self.assertEqual(
2978.2.1 by Alexander Belchenko
fix formatting of ImmortalPendingDeletion error message.
462
            "Unable to delete transform temporary directory foo.  "
463
            "Please examine foo to see if it contains any files "
464
            "you wish to keep, and delete it when you are done.",
465
            str(err))
466
3006.2.2 by Alexander Belchenko
tests added.
467
    def test_unable_create_symlink(self):
468
        err = errors.UnableCreateSymlink()
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
469
        self.assertEqual(
3006.2.2 by Alexander Belchenko
tests added.
470
            "Unable to create symlink on this platform",
471
            str(err))
472
        err = errors.UnableCreateSymlink(path=u'foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
473
        self.assertEqual(
3006.2.2 by Alexander Belchenko
tests added.
474
            "Unable to create symlink 'foo' on this platform",
475
            str(err))
476
        err = errors.UnableCreateSymlink(path=u'\xb5')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
477
        self.assertEqual(
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
478
            "Unable to create symlink %s on this platform" % repr(u'\xb5'),
3006.2.2 by Alexander Belchenko
tests added.
479
            str(err))
480
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
481
    def test_invalid_url_join(self):
482
        """Test the formatting of InvalidURLJoin."""
483
        e = errors.InvalidURLJoin('Reason', 'base path', ('args',))
484
        self.assertEqual(
485
            "Invalid URL join request: Reason: 'base path' + ('args',)",
486
            str(e))
487
3035.3.2 by Lukáš Lalinský
Add tests for InvalidBugTrackerURL.
488
    def test_incorrect_url(self):
489
        err = errors.InvalidBugTrackerURL('foo', 'http://bug.com/')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
490
        self.assertEqual(
3035.3.2 by Lukáš Lalinský
Add tests for InvalidBugTrackerURL.
491
            ("The URL for bug tracker \"foo\" doesn't contain {id}: "
492
             "http://bug.com/"),
493
            str(err))
494
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.
495
    def test_unable_encode_path(self):
496
        err = errors.UnableEncodePath('foo', 'executable')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
497
        self.assertEqual("Unable to encode executable path 'foo' in "
498
                         "user encoding " + osutils.get_user_encoding(),
499
                         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.
500
3246.3.4 by Daniel Watkins
Added test.
501
    def test_unknown_format(self):
502
        err = errors.UnknownFormatError('bar', kind='foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
503
        self.assertEqual("Unknown foo format: 'bar'", str(err))
3246.3.4 by Daniel Watkins
Added test.
504
3398.1.29 by Ian Clatworthy
add UnknownRules class & test
505
    def test_unknown_rules(self):
506
        err = errors.UnknownRules(['foo', 'bar'])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
507
        self.assertEqual("Unknown rules detected: foo, bar.", str(err))
3398.1.29 by Ian Clatworthy
add UnknownRules class & test
508
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
509
    def test_tip_change_rejected(self):
510
        err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
511
        self.assertEqual(
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
512
            u'Tip change rejected: Unicode message\N{INTERROBANG}',
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
513
            text_type(err))
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
514
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
515
    def test_error_from_smart_server(self):
516
        error_tuple = ('error', 'tuple')
517
        err = errors.ErrorFromSmartServer(error_tuple)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
518
        self.assertEqual(
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
519
            "Error received from smart server: ('error', 'tuple')", str(err))
520
521
    def test_untranslateable_error_from_smart_server(self):
522
        error_tuple = ('error', 'tuple')
523
        orig_err = errors.ErrorFromSmartServer(error_tuple)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
524
        err = errors.UnknownErrorFromSmartServer(orig_err)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
525
        self.assertEqual(
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
526
            "Server sent an unexpected error: ('error', 'tuple')", str(err))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
527
3883.2.3 by Andrew Bennetts
Add test, tweak traceback formatting.
528
    def test_smart_message_handler_error(self):
529
        # Make an exc_info tuple.
530
        try:
531
            raise Exception("example error")
532
        except Exception:
5340.15.2 by John Arbash Meinel
supercede 2.4-613247-cleanup-tests
533
            err = errors.SmartMessageHandlerError(sys.exc_info())
534
        # GZ 2010-11-08: Should not store exc_info in exception instances.
535
        try:
536
            self.assertStartsWith(
537
                str(err), "The message handler raised an exception:\n")
538
            self.assertEndsWith(str(err), "Exception: example error\n")
539
        finally:
540
            del err
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
541
3983.1.8 by Daniel Watkins
Added MustHaveWorkingTree error and accompanying test.
542
    def test_must_have_working_tree(self):
543
        err = errors.MustHaveWorkingTree('foo', 'bar')
3983.1.10 by Daniel Watkins
Made exception message slightly better.
544
        self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
545
                                   " working tree.")
3983.1.8 by Daniel Watkins
Added MustHaveWorkingTree error and accompanying test.
546
3586.1.1 by Ian Clatworthy
add view-related errors and tests
547
    def test_no_such_view(self):
548
        err = errors.NoSuchView('foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
549
        self.assertEqual("No such view: foo.", str(err))
3586.1.1 by Ian Clatworthy
add view-related errors and tests
550
551
    def test_views_not_supported(self):
552
        err = errors.ViewsNotSupported('atree')
553
        err_str = str(err)
554
        self.assertStartsWith(err_str, "Views are not supported by ")
6622.1.30 by Jelmer Vernooij
Some more test fixes.
555
        self.assertEndsWith(err_str, "; use 'brz upgrade' to change your "
3586.1.1 by Ian Clatworthy
add view-related errors and tests
556
            "tree to a later format.")
557
3586.1.9 by Ian Clatworthy
first cut at view command
558
    def test_file_outside_view(self):
559
        err = errors.FileOutsideView('baz', ['foo', 'bar'])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
560
        self.assertEqual('Specified file "baz" is outside the current view: '
561
                         'foo, bar', str(err))
3586.1.9 by Ian Clatworthy
first cut at view command
562
3990.2.2 by Daniel Watkins
Added InvalidShelfId error and accompanying test.
563
    def test_invalid_shelf_id(self):
564
        invalid_id = "foo"
565
        err = errors.InvalidShelfId(invalid_id)
3999.1.1 by Ian Clatworthy
Improve shelf documentation & fix backtrace (Daniel Watkins)
566
        self.assertEqual('"foo" is not a valid shelf id, '
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
567
                         'try a number instead.', str(err))
3990.2.2 by Daniel Watkins
Added InvalidShelfId error and accompanying test.
568
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
569
    def test_unresumable_write_group(self):
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
570
        repo = "dummy repo"
571
        wg_tokens = ['token']
572
        reason = "a reason"
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
573
        err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
574
        self.assertEqual(
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
575
            "Repository dummy repo cannot resume write group "
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
576
            "['token']: a reason", str(err))
577
578
    def test_unsuspendable_write_group(self):
579
        repo = "dummy repo"
580
        err = errors.UnsuspendableWriteGroup(repo)
581
        self.assertEqual(
582
            'Repository dummy repo cannot suspend a write group.', str(err))
583
4734.4.9 by Andrew Bennetts
More tests and comments.
584
    def test_not_branch_no_args(self):
585
        err = errors.NotBranchError('path')
586
        self.assertEqual('Not a branch: "path".', str(err))
587
5050.46.1 by Andrew Bennetts
Suppress unexpected errors during NotBranchError's call to open_repository.
588
    def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
589
        class FakeBzrDir(object):
590
            def open_repository(self):
591
                # str() on the NotBranchError will trigger a call to this,
592
                # which in turn will another, identical NotBranchError.
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
593
                raise errors.NotBranchError('path', controldir=FakeBzrDir())
594
        err = errors.NotBranchError('path', controldir=FakeBzrDir())
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
595
        self.assertEqual('Not a branch: "path": NotBranchError.', str(err))
4734.4.9 by Andrew Bennetts
More tests and comments.
596
5339.1.1 by Parth Malwankar
fixes errors.InvalidPattern to work on Python2.5
597
    def test_invalid_pattern(self):
598
        error = errors.InvalidPattern('Bad pattern msg.')
599
        self.assertEqualDiff("Invalid pattern(s) found. Bad pattern msg.",
600
            str(error))
601
5050.7.6 by Parth Malwankar
fixed test name
602
    def test_recursive_bind(self):
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
603
        error = errors.RecursiveBind('foo_bar_branch')
604
        msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
605
            'Please use `brz unbind` to fix.')
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
606
        self.assertEqualDiff(msg, str(error))
607
5609.58.1 by Andrew Bennetts
Fix 'Unprintable exception' when displaying RetryWithNewPacks error.
608
    def test_retry_with_new_packs(self):
609
        fake_exc_info = ('{exc type}', '{exc value}', '{exc traceback}')
610
        error = errors.RetryWithNewPacks(
611
            '{context}', reload_occurred=False, exc_info=fake_exc_info)
612
        self.assertEqual(
613
            'Pack files have changed, reload and retry. context: '
614
            '{context} {exc value}', str(error))
615
2116.3.1 by John Arbash Meinel
Cleanup error tests
616
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
617
class PassThroughError(errors.BzrError):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
618
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
619
    _fmt = """Pass through %(foo)s and %(bar)s"""
2116.3.1 by John Arbash Meinel
Cleanup error tests
620
621
    def __init__(self, foo, bar):
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
622
        errors.BzrError.__init__(self, foo=foo, bar=bar)
623
624
625
class ErrorWithBadFormat(errors.BzrError):
626
627
    _fmt = """One format specifier: %(thing)s"""
628
629
630
class ErrorWithNoFormat(errors.BzrError):
5131.2.6 by Martin
Fix more tests which were failing under -OO that had been missed earlier
631
    __doc__ = """This class has a docstring but no format string."""
2116.3.1 by John Arbash Meinel
Cleanup error tests
632
633
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
634
class TestErrorFormatting(tests.TestCase):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
635
2116.3.1 by John Arbash Meinel
Cleanup error tests
636
    def test_always_str(self):
637
        e = PassThroughError(u'\xb5', 'bar')
638
        self.assertIsInstance(e.__str__(), str)
639
        # In Python str(foo) *must* return a real byte string
640
        # not a Unicode string. The following line would raise a
641
        # Unicode error, because it tries to call str() on the string
642
        # returned from e.__str__(), and it has non ascii characters
643
        s = str(e)
644
        self.assertEqual('Pass through \xc2\xb5 and bar', s)
645
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
646
    def test_missing_format_string(self):
647
        e = ErrorWithNoFormat(param='randomvalue')
6318.2.1 by Martin Packman
Remove deprecated classes and practices from bzrlib.errors
648
        self.assertStartsWith(str(e),
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
649
                              "Unprintable exception ErrorWithNoFormat")
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
650
2116.3.1 by John Arbash Meinel
Cleanup error tests
651
    def test_mismatched_format_args(self):
652
        # Even though ErrorWithBadFormat's format string does not match the
653
        # arguments we constructing it with, we can still stringify an instance
654
        # of this exception. The resulting string will say its unprintable.
655
        e = ErrorWithBadFormat(not_thing='x')
656
        self.assertStartsWith(
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
657
            str(e), 'Unprintable exception ErrorWithBadFormat')
4634.1.2 by Martin Pool
Add test for CannotBindAddress
658
659
    def test_cannot_bind_address(self):
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
660
        # see <https://bugs.launchpad.net/bzr/+bug/286871>
4634.1.2 by Martin Pool
Add test for CannotBindAddress
661
        e = errors.CannotBindAddress('example.com', 22,
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
662
                                     socket.error(13, 'Permission denied'))
663
        self.assertContainsRe(
664
            str(e),
4634.1.2 by Martin Pool
Add test for CannotBindAddress
665
            r'Cannot bind address "example\.com:22":.*Permission denied')
4976.1.1 by Jelmer Vernooij
Add FileTimestampUnavailable exception.
666
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
667
    def test_file_timestamp_unavailable(self):
4976.1.1 by Jelmer Vernooij
Add FileTimestampUnavailable exception.
668
        e = errors.FileTimestampUnavailable("/path/foo")
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
669
        self.assertEqual("The filestamp for /path/foo is not available.",
670
                         str(e))
671
5186.2.6 by Martin Pool
Add formatting test for TransformRenameFailed
672
    def test_transform_rename_failed(self):
5186.2.7 by Martin Pool
Update other cases where transform detects failure to rename
673
        e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
674
        self.assertEqual(
5186.2.6 by Martin Pool
Add formatting test for TransformRenameFailed
675
            u"Failed to rename from to to: readonly file",
676
            str(e))
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
677
678
679
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
680
    """Tests for errors that need to use a branch or repo."""
681
682
    def test_no_public_branch(self):
683
        b = self.make_branch('.')
684
        error = errors.NoPublicBranch(b)
685
        url = urlutils.unescape_for_display(b.base, 'ascii')
686
        self.assertEqualDiff(
687
            'There is no public branch set for "%s".' % url, str(error))
688
689
    def test_no_repo(self):
690
        dir = controldir.ControlDir.create(self.get_url())
691
        error = errors.NoRepositoryPresent(dir)
692
        self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
693
        self.assertEqual(-1, str(error).find((dir.transport.base)))
694
695
    def test_corrupt_repository(self):
696
        repo = self.make_repository('.')
697
        error = errors.CorruptRepository(repo)
698
        self.assertEqualDiff("An error has been detected in the repository %s.\n"
699
                             "Please run brz reconcile on this repository." %
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
700
                             repo.controldir.root_transport.base,
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
701
                             str(error))
702
703
    def test_unknown_bug_tracker_abbreviation(self):
704
        """Test the formatting of UnknownBugTrackerAbbreviation."""
705
        branch = self.make_branch('some_branch')
706
        error = errors.UnknownBugTrackerAbbreviation('xxx', branch)
707
        self.assertEqual(
708
            "Cannot find registered bug tracker called xxx on %s" % branch,
709
            str(error))
710
711
    def test_not_branch_bzrdir_with_repo(self):
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
712
        controldir = self.make_repository('repo').controldir
713
        err = errors.NotBranchError('path', controldir=controldir)
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
714
        self.assertEqual(
715
            'Not a branch: "path": location is a repository.', str(err))
716
717
    def test_not_branch_bzrdir_without_repo(self):
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
718
        controldir = self.make_controldir('bzrdir')
719
        err = errors.NotBranchError('path', controldir=controldir)
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
720
        self.assertEqual('Not a branch: "path".', str(err))
721
722
    def test_not_branch_laziness(self):
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
723
        real_bzrdir = self.make_controldir('path')
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
724
        class FakeBzrDir(object):
725
            def __init__(self):
726
                self.calls = []
727
            def open_repository(self):
728
                self.calls.append('open_repository')
729
                raise errors.NoRepositoryPresent(real_bzrdir)
730
        fake_bzrdir = FakeBzrDir()
6653.6.6 by Jelmer Vernooij
Fix remaining tests.
731
        err = errors.NotBranchError('path', controldir=fake_bzrdir)
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
732
        self.assertEqual([], fake_bzrdir.calls)
733
        str(err)
734
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
735
        # Stringifying twice doesn't try to open a repository twice.
736
        str(err)
737
        self.assertEqual(['open_repository'], fake_bzrdir.calls)