~bzr-pqm/bzr/bzr.dev

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