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