1# -*- coding: utf-8 -*-
2
3""" pyKwalify - errors.py """
4
5# python stdlib
6from pykwalify.compat import basestring
7
8retcodes = {
9    # PyKwalifyExit
10    0: 'noerror',
11
12    # UnknownError
13    1: 'unknownerror',
14
15    # SchemaError
16    # e.g. when a rule or the core finds an error
17    2: 'schemaerror',
18
19    # CoreError
20    # e.g. when the core finds an error that is not a SchemaError
21    3: 'coreerror',
22
23    # RuleError
24    # e.g. when the rule class finds an error that is not a SchemaError, similar to CoreError
25    4: 'ruleerror',
26
27    # SchemaConflict
28    # e.g. when a schema conflict occurs
29    5: 'schemaconflict',
30
31    # NotMappingError
32    # e.g. when a value is not a mapping when it was expected it should be
33    6: 'notmaperror',
34
35    # NotSequenceError
36    # e.g. when a value is not a sequence when it was expected it should be
37    7: 'notsequenceerror',
38}
39
40
41retnames = dict((v, k) for (k, v) in retcodes.items())
42
43
44class PyKwalifyException(RuntimeError):
45    """
46    """
47
48    def __init__(self, msg=None, error_key=None, retcode=None, path=None):
49        """
50        Arguments:
51        - `msg`: a string
52        - `error_key`: a unique string that makes it easier to identify what error it is
53        - `retcode`: an integer, defined in PyKwalify.errors.retcodes
54        """
55        self.msg = msg or ""
56        self.retcode = retcode or retnames['unknownerror']
57        self.retname = retcodes[retcode]
58        self.error_key = error_key
59        self.path = path or "/"
60
61    def __str__(self):
62        """
63        """
64        # <PyKwalifyException msg='foo bar' retcode=1>
65        # kwargs = []
66        # if self.msg:
67        #        kwargs.append("msg='{0}'".format(self.msg))
68        # if self.retcode != retnames['noerror']:
69        #        kwargs.append("retcode=%d" % self.retcode)
70        # if kwargs:
71        #        kwargs.insert(0, '')
72        # return "<{0}{1}>".format(self.__class__.__name__, ' '.join(kwargs))
73
74        # <PyKwalifyException: error code 1: foo bar>
75        kwargs = []
76        if self.retcode != retnames['noerror']:
77            kwargs.append("error code {0}".format(self.retcode))
78        if self.msg:
79            kwargs.append(self.msg)
80        if kwargs:
81            kwargs.insert(0, '')
82        if self.path:
83            kwargs.append("Path: '{0}'".format(self.path))
84        return "<{0}{1}>".format(self.__class__.__name__, ': '.join(kwargs))
85
86    def __repr__(self):
87        """
88        """
89        kwargs = []
90        if self.msg:
91            kwargs.append("msg='{0}'".format(self.msg))
92        return "{0}({1})".format(self.__class__.__name__, ', '.join(kwargs))
93
94    def msg():
95        doc = """ """
96
97        def fget(self):
98            return self._msg
99
100        def fset(self, value):
101            assert isinstance(value, basestring), "argument is not string"
102            self._msg = value
103
104        return locals()
105    msg = property(**msg())
106
107    def retcode():
108        doc = """ """
109
110        def fget(self):
111            return self._retcode
112
113        def fset(self, value):
114            assert isinstance(value, int), "argument is not integer"
115            self._retcode = value
116
117        return locals()
118    retcode = property(**retcode())
119
120    def retname():
121        doc = """ """
122
123        def fget(self):
124            return self._retname
125
126        def fset(self, value):
127            assert isinstance(value, str), "argument is not string"
128            self._retname = value
129
130        return locals()
131    retname = property(**retname())
132
133
134class UnknownError(PyKwalifyException):
135    """
136    """
137    def __init__(self, *args, **kwargs):
138        """
139        """
140        assert 'retcode' not in kwargs, "keyword retcode implicitly defined"
141        super(self.__class__, self).__init__(
142            retcode=retnames['unknownerror'],
143            *args, **kwargs
144        )
145
146
147class SchemaError(PyKwalifyException):
148    """
149    """
150    class SchemaErrorEntry(object):
151        """
152        """
153        def __init__(self, msg, path, value, **kwargs):
154            """
155            """
156            self.msg = msg
157            self.path = path
158            self.value = value
159            for key, value in kwargs.items():
160                self.__setattr__(key, value)
161
162        def __repr__(self):
163            return self.msg.format(**self.__dict__)
164
165    def __init__(self, *args, **kwargs):
166        """
167        """
168        assert "retcode" not in kwargs, "keyword retcode implicitly defined"
169        super(self.__class__, self).__init__(
170            retcode=retnames["schemaerror"],
171            *args, **kwargs
172        )
173
174
175class CoreError(PyKwalifyException):
176    """
177    """
178    def __init__(self, *args, **kwargs):
179        """
180        """
181        assert "retcode" not in kwargs, "keyword retcode implicitly defined"
182        super(self.__class__, self).__init__(
183            retcode=retnames["coreerror"],
184            *args, **kwargs
185        )
186
187
188class NotMappingError(PyKwalifyException):
189    """
190    """
191    def __init__(self, *args, **kwargs):
192        """
193        """
194        assert "retcode" not in kwargs, "keyword retcode implicitly defined"
195        super(self.__class__, self).__init__(
196            retcode=retnames['notmaperror'],
197            *args, **kwargs
198        )
199
200
201class NotSequenceError(PyKwalifyException):
202    """
203    """
204    def __init__(self, *args, **kwargs):
205        """
206        """
207        assert "retcode" not in kwargs, "keyword retcode implicitly defined"
208        super(self.__class__, self).__init__(
209            retcode=retnames['notsequenceerror'],
210            *args, **kwargs
211        )
212
213
214class RuleError(PyKwalifyException):
215    """
216    """
217    def __init__(self, *args, **kwargs):
218        """
219        """
220        assert "retcode" not in kwargs, "keyword retcode implicitly defined"
221        super(self.__class__, self).__init__(
222            retcode=retnames["ruleerror"],
223            *args, **kwargs
224        )
225
226
227class SchemaConflict(PyKwalifyException):
228    """
229    """
230    def __init__(self, *args, **kwargs):
231        """
232        """
233        assert "retcode" not in kwargs, "keyword retcode implicitly defined"
234        super(self.__class__, self).__init__(
235            retcode=retnames["schemaconflict"],
236            *args, **kwargs
237        )
238