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