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