summaryrefslogtreecommitdiffstats
path: root/ipalib/errors.py
blob: 8c1df4555870338902af3d5268061001af0c3072 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# Authors:
#   Jason Gerard DeRose <jderose@redhat.com>
#
# Copyright (C) 2008  Red Hat
# see file 'COPYING' for use and warranty inmsgion
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"""
All custom errors raised by `ipalib` package.
"""

TYPE_FORMAT = '%s: need a %r; got %r'

def raise_TypeError(name, type_, value):
    """
    Raises a TypeError with a nicely formatted message and helpful attributes.

    The TypeError raised will have three custom attributes:

        ``name`` - The name (identifier) of the argument in question.

        ``type`` - The type expected for the argument.

        ``value`` - The value (of incorrect type) passed as argument.

    There is no edict that all TypeError should be raised with raise_TypeError,
    but when it fits, use it... it makes the unit tests faster to write and
    the debugging easier to read.

    Here is an example:

    >>> raise_TypeError('message', str, u'Hello.')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/jderose/projects/freeipa2/ipalib/errors.py", line 61, in raise_TypeError
        raise e
    TypeError: message: need a <type 'str'>; got u'Hello.'

    :param name: The name (identifier) of the argument in question.
    :param type_: The type expected for the argument.
    :param value: The value (of incorrect type) passed argument.
    """

    assert type(name) is str, TYPE_FORMAT % ('name', str, name)
    assert type(type_) is type, TYPE_FORMAT % ('type_', type, type_)
    assert type(value) is not type_, 'value: %r is a %r' % (value, type_)
    e = TypeError(TYPE_FORMAT % (name, type_, value))
    setattr(e, 'name', name)
    setattr(e, 'type', type_)
    setattr(e, 'value', value)
    raise e


def check_type(name, type_, value, allow_None=False):
    assert type(name) is str, TYPE_FORMAT % ('name', str, name)
    assert type(type_) is type, TYPE_FORMAT % ('type_', type, type_)
    assert type(allow_None) is bool, TYPE_FORMAT % ('allow_None', bool, allow_None)
    if value is None and allow_None:
        return
    if type(value) is not type_:
        raise_TypeError(name, type_, value)
    return value


def check_isinstance(name, type_, value, allow_None=False):
    assert type(name) is str, TYPE_FORMAT % ('name', str, name)
    assert type(type_) is type, TYPE_FORMAT % ('type_', type, type_)
    assert type(allow_None) is bool, TYPE_FORMAT % ('allow_None', bool, allow_None)
    if value is None and allow_None:
        return
    if not isinstance(value, type_):
        raise_TypeError(name, type_, value)
    return value


class IPAError(Exception):
    """
    Use this base class for your custom IPA errors unless there is a
    specific reason to subclass from AttributeError, KeyError, etc.
    """
    msg = None

    def __init__(self, *args, **kw):
        self.args = args
        self.kw = kw

    def __str__(self):
        """
        Returns the string representation of this exception.
        """
        if self.msg is None:
            if len(self.args) == 1:
                return unicode(self.args[0])
            return unicode(self.args)
        if len(self.args) > 0:
            return self.msg % self.args
        return self.msg % self.kw


class ValidationError(IPAError):
    msg = 'invalid %r value %r: %s'

    def __init__(self, name, value, error):
        self.name = name
        self.value = value
        self.error = error
        IPAError.__init__(self, name, value, error)


class NormalizationError(ValidationError):
    def __init__(self, name, value, type):
        self.type = type
        ValidationError.__init__(self, name, value,
            'not %r' % type
        )


class RuleError(ValidationError):
    """
    Raised when a required option was not provided.
    """
    # FIXME: `rule` should really be after `error`
    def __init__(self, name, value, rule, error):
        self.rule = rule
        ValidationError.__init__(self, name, value, error)


class RequirementError(ValidationError):
    """
    Raised when a required option was not provided.
    """
    def __init__(self, name):
        ValidationError.__init__(self, name, None,
            'missing required value'
        )


class SetError(IPAError):
    msg = 'setting %r, but NameSpace does not allow attribute setting'



class RegistrationError(IPAError):
    """
    Base class for errors that occur during plugin registration.
    """


class NameSpaceError(RegistrationError):
    msg = 'name %r does not re.match %r'


class SubclassError(RegistrationError):
    """
    Raised when registering a plugin that is not a subclass of one of the
    allowed bases.
    """
    msg = 'plugin %r not subclass of any base in %r'

    def __init__(self, cls, allowed):
        self.cls = cls
        self.allowed = allowed

    def __str__(self):
        return self.msg % (self.cls, self.allowed)


class DuplicateError(RegistrationError):
    """
    Raised when registering a plugin whose exact class has already been
    registered.
    """
    msg = '%r at %d was already registered'

    def __init__(self, cls):
        self.cls = cls

    def __str__(self):
        return self.msg % (self.cls, id(self.cls))


class OverrideError(RegistrationError):
    """
    Raised when override=False yet registering a plugin that overrides an
    existing plugin in the same namespace.
    """
    msg = 'unexpected override of %s.%s with %r (use override=True if intended)'

    def __init__(self, base, cls):
        self.base = base
        self.cls = cls

    def __str__(self):
        return self.msg % (self.base.__name__, self.cls.__name__, self.cls)


class MissingOverrideError(RegistrationError):
    """
    Raised when override=True yet no preexisting plugin with the same name
    and base has been registered.
    """
    msg = '%s.%s has not been registered, cannot override with %r'

    def __init__(self, base, cls):
        self.base = base
        self.cls = cls

    def __str__(self):
        return self.msg % (self.base.__name__, self.cls.__name__, self.cls)



class TwiceSetError(IPAError):
    msg = '%s.%s cannot be set twice'