/brz/remove-bazaar

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