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