1
# Copyright (C) 2006 Canonical Ltd
2
# Authors: Robert Collins <robert.collins@canonical.com>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""Tests for the formatting and construction of errors."""
24
from bzrlib.tests import TestCase, TestCaseWithTransport
27
# TODO: Make sure builtin exception class formats are consistent - e.g. should
28
# or shouldn't end with a full stop, etc.
31
class TestErrors(TestCaseWithTransport):
33
def test_inventory_modified(self):
34
error = errors.InventoryModified("a tree to be repred")
35
self.assertEqualDiff("The current inventory for the tree 'a tree to "
36
"be repred' has been modified, so a clean inventory cannot be "
37
"read without data loss.",
40
def test_medium_not_connected(self):
41
error = errors.MediumNotConnected("a medium")
43
"The medium 'a medium' is not connected.", str(error))
45
def test_no_repo(self):
46
dir = bzrdir.BzrDir.create(self.get_url())
47
error = errors.NoRepositoryPresent(dir)
48
self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
49
self.assertEqual(-1, str(error).find((dir.transport.base)))
51
def test_no_smart_medium(self):
52
error = errors.NoSmartMedium("a transport")
53
self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
57
def test_no_such_id(self):
58
error = errors.NoSuchId("atree", "anid")
59
self.assertEqualDiff("The file id anid is not present in the tree "
63
def test_not_write_locked(self):
64
error = errors.NotWriteLocked('a thing to repr')
65
self.assertEqualDiff("'a thing to repr' is not write locked but needs "
69
def test_too_many_concurrent_requests(self):
70
error = errors.TooManyConcurrentRequests("a medium")
71
self.assertEqualDiff("The medium 'a medium' has reached its concurrent "
72
"request limit. Be sure to finish_writing and finish_reading on "
73
"the current request that is open.",
76
def test_up_to_date(self):
77
error = errors.UpToDateFormat(bzrdir.BzrDirFormat4())
78
self.assertEqualDiff("The branch format Bazaar-NG branch, "
79
"format 0.0.4 is already at the most "
83
def test_corrupt_repository(self):
84
repo = self.make_repository('.')
85
error = errors.CorruptRepository(repo)
86
self.assertEqualDiff("An error has been detected in the repository %s.\n"
87
"Please run bzr reconcile on this repository." %
88
repo.bzrdir.root_transport.base,
91
def test_bzrnewerror_is_deprecated(self):
92
class DeprecatedError(errors.BzrNewError):
94
self.callDeprecated(['BzrNewError was deprecated in bzr 0.12; '
95
'please convert DeprecatedError to use BzrError instead'],
98
def test_bzrerror_from_literal_string(self):
99
# Some code constructs BzrError from a literal string, in which case
100
# no further formatting is done. (I'm not sure raising the base class
101
# is a great idea, but if the exception is not intended to be caught
102
# perhaps no more is needed.)
104
raise errors.BzrError('this is my errors; %d is not expanded')
105
except errors.BzrError, e:
106
self.assertEqual('this is my errors; %d is not expanded', str(e))
108
def test_reading_completed(self):
109
error = errors.ReadingCompleted("a request")
110
self.assertEqualDiff("The MediumRequest 'a request' has already had "
111
"finish_reading called upon it - the request has been completed and"
112
" no more data may be read.",
115
def test_writing_completed(self):
116
error = errors.WritingCompleted("a request")
117
self.assertEqualDiff("The MediumRequest 'a request' has already had "
118
"finish_writing called upon it - accept bytes may not be called "
122
def test_writing_not_completed(self):
123
error = errors.WritingNotComplete("a request")
124
self.assertEqualDiff("The MediumRequest 'a request' has not has "
125
"finish_writing called upon it - until the write phase is complete"
126
" no data may be read.",
130
class PassThroughError(errors.BzrError):
132
_fmt = """Pass through %(foo)s and %(bar)s"""
134
def __init__(self, foo, bar):
135
errors.BzrError.__init__(self, foo=foo, bar=bar)
138
class ErrorWithBadFormat(errors.BzrError):
140
_fmt = """One format specifier: %(thing)s"""
143
class ErrorWithNoFormat(errors.BzrError):
144
"""This class has a docstring but no format string."""
147
class TestErrorFormatting(TestCase):
149
def test_always_str(self):
150
e = PassThroughError(u'\xb5', 'bar')
151
self.assertIsInstance(e.__str__(), str)
152
# In Python str(foo) *must* return a real byte string
153
# not a Unicode string. The following line would raise a
154
# Unicode error, because it tries to call str() on the string
155
# returned from e.__str__(), and it has non ascii characters
157
self.assertEqual('Pass through \xc2\xb5 and bar', s)
159
def test_missing_format_string(self):
160
e = ErrorWithNoFormat(param='randomvalue')
161
s = self.callDeprecated(
162
['ErrorWithNoFormat uses its docstring as a format, it should use _fmt instead'],
166
"This class has a docstring but no format string.")
168
def test_mismatched_format_args(self):
169
# Even though ErrorWithBadFormat's format string does not match the
170
# arguments we constructing it with, we can still stringify an instance
171
# of this exception. The resulting string will say its unprintable.
172
e = ErrorWithBadFormat(not_thing='x')
173
self.assertStartsWith(
174
str(e), 'Unprintable exception ErrorWithBadFormat')
177
class TestSpecificErrors(TestCase):
179
def test_transport_not_possible(self):
180
e = errors.TransportNotPossible('readonly', 'original error')
181
self.assertEqual('Transport operation not possible:'
182
' readonly original error', str(e))
184
def assertSocketConnectionError(self, expected, *args, **kwargs):
185
"""Check the formatting of a SocketConnectionError exception"""
186
e = errors.SocketConnectionError(*args, **kwargs)
187
self.assertEqual(expected, str(e))
189
def test_socket_connection_error(self):
190
"""Test the formatting of SocketConnectionError"""
192
# There should be a default msg about failing to connect
193
# we only require a host name.
194
self.assertSocketConnectionError(
195
'Failed to connect to ahost',
198
# If port is None, we don't put :None
199
self.assertSocketConnectionError(
200
'Failed to connect to ahost',
202
# But if port is supplied we include it
203
self.assertSocketConnectionError(
204
'Failed to connect to ahost:22',
207
# We can also supply extra information about the error
208
# with or without a port
209
self.assertSocketConnectionError(
210
'Failed to connect to ahost:22; bogus error',
211
'ahost', port=22, orig_error='bogus error')
212
self.assertSocketConnectionError(
213
'Failed to connect to ahost; bogus error',
214
'ahost', orig_error='bogus error')
215
# An exception object can be passed rather than a string
216
orig_error = ValueError('bad value')
217
self.assertSocketConnectionError(
218
'Failed to connect to ahost; %s' % (str(orig_error),),
219
host='ahost', orig_error=orig_error)
221
# And we can supply a custom failure message
222
self.assertSocketConnectionError(
223
'Unable to connect to ssh host ahost:444; my_error',
224
host='ahost', port=444, msg='Unable to connect to ssh host',
225
orig_error='my_error')