/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
2376.4.26 by Jonathan Lange
Tests for MalformedBugIdentifier and new error UnknownBugTrackerAbbreviation.
416
    def test_malformed_bug_identifier(self):
417
        """Test the formatting of MalformedBugIdentifier."""
418
        error = errors.MalformedBugIdentifier('bogus', 'reason for bogosity')
419
        self.assertEqual(
3535.10.1 by James Westby
Point to "bzr help bugs" from MalformedBugIdentifier.
420
            'Did not understand bug identifier bogus: reason for bogosity. '
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
421
            'See "brz help bugs" for more information on this feature.',
2376.4.26 by Jonathan Lange
Tests for MalformedBugIdentifier and new error UnknownBugTrackerAbbreviation.
422
            str(error))
423
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
424
    def test_unexpected_smart_server_response(self):
425
        e = errors.UnexpectedSmartServerResponse(('not yes',))
426
        self.assertEqual(
427
            "Could not understand response from smart server: ('not yes',)",
428
            str(e))
2052.4.4 by John Arbash Meinel
Create a SocketConnectionError to make creating nice errors easier
429
2506.2.1 by Andrew Bennetts
Start implementing container format reading and writing.
430
    def test_unknown_container_format(self):
431
        """Test the formatting of UnknownContainerFormatError."""
432
        e = errors.UnknownContainerFormatError('bad format string')
433
        self.assertEqual(
434
            "Unrecognised container format: 'bad format string'",
435
            str(e))
436
437
    def test_unexpected_end_of_container(self):
438
        """Test the formatting of UnexpectedEndOfContainerError."""
439
        e = errors.UnexpectedEndOfContainerError()
440
        self.assertEqual(
441
            "Unexpected end of container stream", str(e))
442
443
    def test_unknown_record_type(self):
444
        """Test the formatting of UnknownRecordTypeError."""
445
        e = errors.UnknownRecordTypeError("X")
446
        self.assertEqual(
447
            "Unknown record type: 'X'",
448
            str(e))
449
2506.3.1 by Andrew Bennetts
More progress:
450
    def test_invalid_record(self):
451
        """Test the formatting of InvalidRecordError."""
452
        e = errors.InvalidRecordError("xxx")
453
        self.assertEqual(
454
            "Invalid record: xxx",
455
            str(e))
456
2506.2.6 by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader.
457
    def test_container_has_excess_data(self):
458
        """Test the formatting of ContainerHasExcessDataError."""
459
        e = errors.ContainerHasExcessDataError("excess bytes")
460
        self.assertEqual(
461
            "Container has data after end marker: 'excess bytes'",
462
            str(e))
463
2506.6.1 by Andrew Bennetts
Return a callable instead of a str from read, and add more validation.
464
    def test_duplicate_record_name_error(self):
465
        """Test the formatting of DuplicateRecordNameError."""
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
466
        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.
467
        self.assertEqual(
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
468
            u"Container has multiple records with the same name: n\xe5me",
469
            text_type(e))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
470
2854.1.1 by Martin Pool
Fix "unprintable error" message for BzrCheckError and others
471
    def test_check_error(self):
472
        e = errors.BzrCheckError('example check failure')
473
        self.assertEqual(
474
            "Internal check failed: example check failure",
475
            str(e))
476
        self.assertTrue(e.internal_error)
2506.6.1 by Andrew Bennetts
Return a callable instead of a str from read, and add more validation.
477
2535.3.40 by Andrew Bennetts
Tidy up more XXXs.
478
    def test_repository_data_stream_error(self):
479
        """Test the formatting of RepositoryDataStreamError."""
480
        e = errors.RepositoryDataStreamError(u"my reason")
481
        self.assertEqual(
482
            "Corrupt or incompatible data stream: my reason", str(e))
483
2978.2.1 by Alexander Belchenko
fix formatting of ImmortalPendingDeletion error message.
484
    def test_immortal_pending_deletion_message(self):
485
        err = errors.ImmortalPendingDeletion('foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
486
        self.assertEqual(
2978.2.1 by Alexander Belchenko
fix formatting of ImmortalPendingDeletion error message.
487
            "Unable to delete transform temporary directory foo.  "
488
            "Please examine foo to see if it contains any files "
489
            "you wish to keep, and delete it when you are done.",
490
            str(err))
491
3006.2.2 by Alexander Belchenko
tests added.
492
    def test_unable_create_symlink(self):
493
        err = errors.UnableCreateSymlink()
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
494
        self.assertEqual(
3006.2.2 by Alexander Belchenko
tests added.
495
            "Unable to create symlink on this platform",
496
            str(err))
497
        err = errors.UnableCreateSymlink(path=u'foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
498
        self.assertEqual(
3006.2.2 by Alexander Belchenko
tests added.
499
            "Unable to create symlink 'foo' on this platform",
500
            str(err))
501
        err = errors.UnableCreateSymlink(path=u'\xb5')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
502
        self.assertEqual(
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
503
            "Unable to create symlink %s on this platform" % repr(u'\xb5'),
3006.2.2 by Alexander Belchenko
tests added.
504
            str(err))
505
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
506
    def test_invalid_url_join(self):
507
        """Test the formatting of InvalidURLJoin."""
508
        e = errors.InvalidURLJoin('Reason', 'base path', ('args',))
509
        self.assertEqual(
510
            "Invalid URL join request: Reason: 'base path' + ('args',)",
511
            str(e))
512
3035.3.2 by Lukáš Lalinský
Add tests for InvalidBugTrackerURL.
513
    def test_incorrect_url(self):
514
        err = errors.InvalidBugTrackerURL('foo', 'http://bug.com/')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
515
        self.assertEqual(
3035.3.2 by Lukáš Lalinský
Add tests for InvalidBugTrackerURL.
516
            ("The URL for bug tracker \"foo\" doesn't contain {id}: "
517
             "http://bug.com/"),
518
            str(err))
519
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.
520
    def test_unable_encode_path(self):
521
        err = errors.UnableEncodePath('foo', 'executable')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
522
        self.assertEqual("Unable to encode executable path 'foo' in "
523
                         "user encoding " + osutils.get_user_encoding(),
524
                         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.
525
3246.3.4 by Daniel Watkins
Added test.
526
    def test_unknown_format(self):
527
        err = errors.UnknownFormatError('bar', kind='foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
528
        self.assertEqual("Unknown foo format: 'bar'", str(err))
3246.3.4 by Daniel Watkins
Added test.
529
3398.1.29 by Ian Clatworthy
add UnknownRules class & test
530
    def test_unknown_rules(self):
531
        err = errors.UnknownRules(['foo', 'bar'])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
532
        self.assertEqual("Unknown rules detected: foo, bar.", str(err))
3398.1.29 by Ian Clatworthy
add UnknownRules class & test
533
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
534
    def test_tip_change_rejected(self):
535
        err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
536
        self.assertEqual(
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
537
            u'Tip change rejected: Unicode message\N{INTERROBANG}',
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
538
            text_type(err))
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
539
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
540
    def test_error_from_smart_server(self):
541
        error_tuple = ('error', 'tuple')
542
        err = errors.ErrorFromSmartServer(error_tuple)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
543
        self.assertEqual(
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
544
            "Error received from smart server: ('error', 'tuple')", str(err))
545
546
    def test_untranslateable_error_from_smart_server(self):
547
        error_tuple = ('error', 'tuple')
548
        orig_err = errors.ErrorFromSmartServer(error_tuple)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
549
        err = errors.UnknownErrorFromSmartServer(orig_err)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
550
        self.assertEqual(
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
551
            "Server sent an unexpected error: ('error', 'tuple')", str(err))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
552
3883.2.3 by Andrew Bennetts
Add test, tweak traceback formatting.
553
    def test_smart_message_handler_error(self):
554
        # Make an exc_info tuple.
555
        try:
556
            raise Exception("example error")
557
        except Exception:
5340.15.2 by John Arbash Meinel
supercede 2.4-613247-cleanup-tests
558
            err = errors.SmartMessageHandlerError(sys.exc_info())
559
        # GZ 2010-11-08: Should not store exc_info in exception instances.
560
        try:
561
            self.assertStartsWith(
562
                str(err), "The message handler raised an exception:\n")
563
            self.assertEndsWith(str(err), "Exception: example error\n")
564
        finally:
565
            del err
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
566
3983.1.8 by Daniel Watkins
Added MustHaveWorkingTree error and accompanying test.
567
    def test_must_have_working_tree(self):
568
        err = errors.MustHaveWorkingTree('foo', 'bar')
3983.1.10 by Daniel Watkins
Made exception message slightly better.
569
        self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
570
                                   " working tree.")
3983.1.8 by Daniel Watkins
Added MustHaveWorkingTree error and accompanying test.
571
3586.1.1 by Ian Clatworthy
add view-related errors and tests
572
    def test_no_such_view(self):
573
        err = errors.NoSuchView('foo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
574
        self.assertEqual("No such view: foo.", str(err))
3586.1.1 by Ian Clatworthy
add view-related errors and tests
575
576
    def test_views_not_supported(self):
577
        err = errors.ViewsNotSupported('atree')
578
        err_str = str(err)
579
        self.assertStartsWith(err_str, "Views are not supported by ")
6622.1.30 by Jelmer Vernooij
Some more test fixes.
580
        self.assertEndsWith(err_str, "; use 'brz upgrade' to change your "
3586.1.1 by Ian Clatworthy
add view-related errors and tests
581
            "tree to a later format.")
582
3586.1.9 by Ian Clatworthy
first cut at view command
583
    def test_file_outside_view(self):
584
        err = errors.FileOutsideView('baz', ['foo', 'bar'])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
585
        self.assertEqual('Specified file "baz" is outside the current view: '
586
                         'foo, bar', str(err))
3586.1.9 by Ian Clatworthy
first cut at view command
587
3990.2.2 by Daniel Watkins
Added InvalidShelfId error and accompanying test.
588
    def test_invalid_shelf_id(self):
589
        invalid_id = "foo"
590
        err = errors.InvalidShelfId(invalid_id)
3999.1.1 by Ian Clatworthy
Improve shelf documentation & fix backtrace (Daniel Watkins)
591
        self.assertEqual('"foo" is not a valid shelf id, '
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
592
                         'try a number instead.', str(err))
3990.2.2 by Daniel Watkins
Added InvalidShelfId error and accompanying test.
593
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
594
    def test_unresumable_write_group(self):
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
595
        repo = "dummy repo"
596
        wg_tokens = ['token']
597
        reason = "a reason"
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
598
        err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
599
        self.assertEqual(
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
600
            "Repository dummy repo cannot resume write group "
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
601
            "['token']: a reason", str(err))
602
603
    def test_unsuspendable_write_group(self):
604
        repo = "dummy repo"
605
        err = errors.UnsuspendableWriteGroup(repo)
606
        self.assertEqual(
607
            'Repository dummy repo cannot suspend a write group.', str(err))
608
4734.4.9 by Andrew Bennetts
More tests and comments.
609
    def test_not_branch_no_args(self):
610
        err = errors.NotBranchError('path')
611
        self.assertEqual('Not a branch: "path".', str(err))
612
5050.46.1 by Andrew Bennetts
Suppress unexpected errors during NotBranchError's call to open_repository.
613
    def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
614
        class FakeBzrDir(object):
615
            def open_repository(self):
616
                # str() on the NotBranchError will trigger a call to this,
617
                # which in turn will another, identical NotBranchError.
618
                raise errors.NotBranchError('path', bzrdir=FakeBzrDir())
619
        err = errors.NotBranchError('path', bzrdir=FakeBzrDir())
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
620
        self.assertEqual('Not a branch: "path": NotBranchError.', str(err))
4734.4.9 by Andrew Bennetts
More tests and comments.
621
5339.1.1 by Parth Malwankar
fixes errors.InvalidPattern to work on Python2.5
622
    def test_invalid_pattern(self):
623
        error = errors.InvalidPattern('Bad pattern msg.')
624
        self.assertEqualDiff("Invalid pattern(s) found. Bad pattern msg.",
625
            str(error))
626
5050.7.6 by Parth Malwankar
fixed test name
627
    def test_recursive_bind(self):
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
628
        error = errors.RecursiveBind('foo_bar_branch')
629
        msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
630
            'Please use `brz unbind` to fix.')
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
631
        self.assertEqualDiff(msg, str(error))
632
5609.58.1 by Andrew Bennetts
Fix 'Unprintable exception' when displaying RetryWithNewPacks error.
633
    def test_retry_with_new_packs(self):
634
        fake_exc_info = ('{exc type}', '{exc value}', '{exc traceback}')
635
        error = errors.RetryWithNewPacks(
636
            '{context}', reload_occurred=False, exc_info=fake_exc_info)
637
        self.assertEqual(
638
            'Pack files have changed, reload and retry. context: '
639
            '{context} {exc value}', str(error))
640
2116.3.1 by John Arbash Meinel
Cleanup error tests
641
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
642
class PassThroughError(errors.BzrError):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
643
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
644
    _fmt = """Pass through %(foo)s and %(bar)s"""
2116.3.1 by John Arbash Meinel
Cleanup error tests
645
646
    def __init__(self, foo, bar):
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
647
        errors.BzrError.__init__(self, foo=foo, bar=bar)
648
649
650
class ErrorWithBadFormat(errors.BzrError):
651
652
    _fmt = """One format specifier: %(thing)s"""
653
654
655
class ErrorWithNoFormat(errors.BzrError):
5131.2.6 by Martin
Fix more tests which were failing under -OO that had been missed earlier
656
    __doc__ = """This class has a docstring but no format string."""
2116.3.1 by John Arbash Meinel
Cleanup error tests
657
658
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
659
class TestErrorFormatting(tests.TestCase):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
660
2116.3.1 by John Arbash Meinel
Cleanup error tests
661
    def test_always_str(self):
662
        e = PassThroughError(u'\xb5', 'bar')
663
        self.assertIsInstance(e.__str__(), str)
664
        # In Python str(foo) *must* return a real byte string
665
        # not a Unicode string. The following line would raise a
666
        # Unicode error, because it tries to call str() on the string
667
        # returned from e.__str__(), and it has non ascii characters
668
        s = str(e)
669
        self.assertEqual('Pass through \xc2\xb5 and bar', s)
670
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
671
    def test_missing_format_string(self):
672
        e = ErrorWithNoFormat(param='randomvalue')
6318.2.1 by Martin Packman
Remove deprecated classes and practices from bzrlib.errors
673
        self.assertStartsWith(str(e),
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
674
                              "Unprintable exception ErrorWithNoFormat")
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
675
2116.3.1 by John Arbash Meinel
Cleanup error tests
676
    def test_mismatched_format_args(self):
677
        # Even though ErrorWithBadFormat's format string does not match the
678
        # arguments we constructing it with, we can still stringify an instance
679
        # of this exception. The resulting string will say its unprintable.
680
        e = ErrorWithBadFormat(not_thing='x')
681
        self.assertStartsWith(
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
682
            str(e), 'Unprintable exception ErrorWithBadFormat')
4634.1.2 by Martin Pool
Add test for CannotBindAddress
683
684
    def test_cannot_bind_address(self):
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
685
        # see <https://bugs.launchpad.net/bzr/+bug/286871>
4634.1.2 by Martin Pool
Add test for CannotBindAddress
686
        e = errors.CannotBindAddress('example.com', 22,
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
687
                                     socket.error(13, 'Permission denied'))
688
        self.assertContainsRe(
689
            str(e),
4634.1.2 by Martin Pool
Add test for CannotBindAddress
690
            r'Cannot bind address "example\.com:22":.*Permission denied')
4976.1.1 by Jelmer Vernooij
Add FileTimestampUnavailable exception.
691
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
692
    def test_file_timestamp_unavailable(self):
4976.1.1 by Jelmer Vernooij
Add FileTimestampUnavailable exception.
693
        e = errors.FileTimestampUnavailable("/path/foo")
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
694
        self.assertEqual("The filestamp for /path/foo is not available.",
695
                         str(e))
696
5186.2.6 by Martin Pool
Add formatting test for TransformRenameFailed
697
    def test_transform_rename_failed(self):
5186.2.7 by Martin Pool
Update other cases where transform detects failure to rename
698
        e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
699
        self.assertEqual(
5186.2.6 by Martin Pool
Add formatting test for TransformRenameFailed
700
            u"Failed to rename from to to: readonly file",
701
            str(e))
6670.3.1 by Martin
Initial work to make errors module Python 3 compatible
702
703
704
class TestErrorsUsingTransport(tests.TestCaseWithMemoryTransport):
705
    """Tests for errors that need to use a branch or repo."""
706
707
    def test_no_public_branch(self):
708
        b = self.make_branch('.')
709
        error = errors.NoPublicBranch(b)
710
        url = urlutils.unescape_for_display(b.base, 'ascii')
711
        self.assertEqualDiff(
712
            'There is no public branch set for "%s".' % url, str(error))
713
714
    def test_no_repo(self):
715
        dir = controldir.ControlDir.create(self.get_url())
716
        error = errors.NoRepositoryPresent(dir)
717
        self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
718
        self.assertEqual(-1, str(error).find((dir.transport.base)))
719
720
    def test_corrupt_repository(self):
721
        repo = self.make_repository('.')
722
        error = errors.CorruptRepository(repo)
723
        self.assertEqualDiff("An error has been detected in the repository %s.\n"
724
                             "Please run brz reconcile on this repository." %
725
                             repo.bzrdir.root_transport.base,
726
                             str(error))
727
728
    def test_unknown_bug_tracker_abbreviation(self):
729
        """Test the formatting of UnknownBugTrackerAbbreviation."""
730
        branch = self.make_branch('some_branch')
731
        error = errors.UnknownBugTrackerAbbreviation('xxx', branch)
732
        self.assertEqual(
733
            "Cannot find registered bug tracker called xxx on %s" % branch,
734
            str(error))
735
736
    def test_not_branch_bzrdir_with_repo(self):
737
        bzrdir = self.make_repository('repo').bzrdir
738
        err = errors.NotBranchError('path', bzrdir=bzrdir)
739
        self.assertEqual(
740
            'Not a branch: "path": location is a repository.', str(err))
741
742
    def test_not_branch_bzrdir_without_repo(self):
743
        bzrdir = self.make_bzrdir('bzrdir')
744
        err = errors.NotBranchError('path', bzrdir=bzrdir)
745
        self.assertEqual('Not a branch: "path".', str(err))
746
747
    def test_not_branch_laziness(self):
748
        real_bzrdir = self.make_bzrdir('path')
749
        class FakeBzrDir(object):
750
            def __init__(self):
751
                self.calls = []
752
            def open_repository(self):
753
                self.calls.append('open_repository')
754
                raise errors.NoRepositoryPresent(real_bzrdir)
755
        fake_bzrdir = FakeBzrDir()
756
        err = errors.NotBranchError('path', bzrdir=fake_bzrdir)
757
        self.assertEqual([], fake_bzrdir.calls)
758
        str(err)
759
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
760
        # Stringifying twice doesn't try to open a repository twice.
761
        str(err)
762
        self.assertEqual(['open_repository'], fake_bzrdir.calls)