/brz/remove-bazaar

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