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