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