• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

danielmbomfim / PyYep / 7152741451

09 Dec 2023 06:06PM UTC coverage: 98.886% (+0.03%) from 98.857%
7152741451

push

github

danielmbomfim
docs: updates README.md

355 of 359 relevant lines covered (98.89%)

0.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.0
/PyYep/__init__.py
1
"""
2
Allows simple schema parsing and validation for inputs.
3

4
Classes:
5
    Schema
6
    InputItem
7
    StringValidator
8
    NumericValidator
9
    ArrayValidator
10
    DictValidator
11
    ValidationError
12
"""
13
from typing import (
1✔
14
    List,
15
    Optional,
16
    Callable,
17
    Union,
18
    Dict,
19
    TypeVar,
20
    TYPE_CHECKING,
21
)
22
from PyYep.validators.string import StringValidator
1✔
23
from PyYep.validators.numeric import NumericValidator
1✔
24
from PyYep.validators.array import ArrayValidator
1✔
25
from PyYep.validators.dict import DictValidator
1✔
26
from PyYep.exceptions import ValidationError
1✔
27

28
if TYPE_CHECKING:
1✔
29
    from .validators import Validator
×
30

31

32
InputT = TypeVar("InputT")
1✔
33
InputValueT = TypeVar("InputValueT")
1✔
34

35

36
class Schema:
1✔
37
    """
38
    A class to represent a schema.
39

40
    ...
41

42
    Attributes
43
    ----------
44
    _inputs: Union[List[InputItem], List[Validator]]
45
            the schema inputs
46
    on_fail: Callable[[], None]
47
            a callable to be used as a error hook
48
    abort_early: bool
49
            sets if the schema will raise a exception soon after
50
            a validation error happens
51

52
    Methods
53
    -------
54
    validate():
55
            Execute the inputs validators and return a dict containing all the
56
            inputs' values
57
    """
58

59
    def __init__(
1✔
60
        self,
61
        inputs: Union[List["InputItem"], List["Validator"]],
1✔
62
        on_fail: Optional[Callable[[], None]] = None,
1✔
63
        abort_early: Optional[int] = True,
1✔
64
    ) -> None:
1✔
65
        """
66
        Constructs all the necessary attributes for the schema object.
67

68
        Parameters
69
        ----------
70
                inputs (Union[List[InputItem], List[Validator]]):
71
                    the schema inputs
72
                on_fail (Callable[[], None]):
73
                    a callable to be used as a error hook
74
                abort_early (bool):
75
                    sets if the schema will raise a exception soon after
76
                    an error happens
77
        """
78

79
        for item in inputs:
1✔
80
            item._set_parent_form(self)
1✔
81

82
        self._inputs = inputs
1✔
83
        self.on_fail = on_fail
1✔
84
        self.abort_early = abort_early
1✔
85

86
    def validate(self) -> Dict[str, InputValueT]:
1✔
87
        """
88
        Execute the inputs validators and return a dict containing
89
        all the inputs' values
90

91
        Raises
92
        -------
93
        ValidationError: if any validation error happens in the
94
        inputs validation methods
95

96
        Returns
97
        -------
98
        result (dict): a dict containing all the validated values
99
        """
100

101
        result = {}
1✔
102
        errors = []
1✔
103

104
        for item in self._inputs:
1✔
105
            try:
1✔
106
                result[item.name] = item.verify()
1✔
107
            except ValidationError as error:
1✔
108
                if self.abort_early:
1✔
109
                    raise error
1✔
110

111
                if error.inner:
1✔
112
                    errors.extend(error.inner)
113
                    continue
114

115
                errors.append(error)
1✔
116

117
        if not self.abort_early and errors:
1✔
118
            raise ValidationError(
1✔
119
                "", "One or more inputs failed during validation", inner=errors
1✔
120
            )
121

122
        return result
1✔
123

124

125
class InputItem:
1✔
126
    """
127
    A class to represent a input item.
128

129
    ...
130

131
    Attributes
132
    ----------
133
    name: str
134
            the name of the input item
135
    _form: Schema
136
            the parent schema
137
    _input: InputT
138
            the input itself
139
    _path: str
140
            the property or method name that store the value in the input
141
    _validators: List[Callable[[InputValueT], None]]
142
            a list of validators
143
    on_success: Callable[[], None]
144
            a callable used as a local success hook
145
    on_fail: Callable[[], None]
146
            a callable used as a local error hook
147

148
    Methods
149
    -------
150
    _set_parent_form(form):
151
            Set the parent schema of the input item
152

153
    verify(result):
154
            Execute the inputs validators and return the result
155

156
    validate(validator):
157
            receives a validator and appends it on the validators list
158

159
    condition(condition):
160
            Set a condition for the execution of the previous validator
161

162
    modifier(modifier):
163
            Set a modifier to allow changes in the value after validation
164

165
    string():
166
            create a StringValidator using the input item as base
167

168
    number():
169
            create a NumericValidator using the input item as base
170
    """
171

172
    def __init__(
1✔
173
        self,
174
        name: str,
1✔
175
        input_: InputT,
1✔
176
        path: str,
1✔
177
        on_success: Optional[Callable[[], None]] = None,
1✔
178
        on_fail: Optional[Callable[[], None]] = None,
1✔
179
    ):
180
        """
181
        Constructs all the necessary attributes for the input item object.
182

183
        Parameters
184
        ----------
185
                name (str):
186
                    the name of the input item
187
                input_ (InputT):
188
                    the input itself
189
                path (str):
190
                    the input's property or method name that store the value
191
                on_success (Callable[[], None]):
192
                    a callable to be used as a local success hook
193
                on_fail (Callable[[], None]):
194
                    a callable to be used as a local error hook
195
        """
196

197
        self.name = name
1✔
198
        self._form = None
1✔
199
        self._input = input_
1✔
200
        self._path = path
1✔
201

202
        self._validators = []
1✔
203
        self._conditions = {}
1✔
204
        self._modifier = None
1✔
205
        self.on_fail = on_fail
1✔
206
        self.on_success = on_success
1✔
207

208
    def set_input(self, name: str, input_: InputT, path: str):
1✔
209
        """
210
        Sets the item
211

212
        Parameters
213
        ----------
214
                name (str):
215
                    the name of the input item
216
                input_ (InputT):
217
                    the input itself
218
                path (str):
219
                    the input's property or method name that store the value
220
        """
221

222
        self.name = name
1✔
223
        self._input = input_
1✔
224
        self._path = path
1✔
225

226
    def _set_parent_form(self, form: Schema) -> None:
1✔
227
        """
228
        Set the parent schema of the input item
229

230
        Parameters
231
        ----------
232
        form : Schema
233
                the input item parent schema
234

235
        Returns
236
        -------
237
        None
238
        """
239

240
        self._form = form
1✔
241

242
    def verify(self, result: Optional[InputValueT] = None) -> InputValueT:
1✔
243
        """
244
        Get the input value and execute all the validators
245

246
        Parameters
247
        ----------
248
        result : Optional[InputValueT]
249
                the value stored on the input, if not passed it will use
250
                the value returned by the method or attribute with the name
251
                stored on the input item _path attribute
252

253
        Raises:
254
        _______
255
        ValidationError:
256
                if any error happens during the validation process
257

258
        Returns
259
        -------
260
        result (InputValueT): The value received after all the validation
261
        """
262

263
        if result is None:
1✔
264
            result = getattr(self._input, self._path)
1✔
265

266
        if callable(result):
1✔
267
            result = result()
1✔
268

269
        for validator in self._validators:
1✔
270
            if validator in self._conditions and not self._conditions[
1✔
271
                validator
1✔
272
            ](result):
1✔
273
                continue
1✔
274

275
            try:
1✔
276
                validator(result)
1✔
277
            except ValidationError as error:
1✔
278
                if self.on_fail is not None:
1✔
279
                    self.on_fail()
1✔
280
                elif self._form is not None and self._form.on_fail is not None:
1✔
281
                    self._form.on_fail()
1✔
282

283
                raise error
1✔
284

285
        if self.on_success is not None:
1✔
286
            self.on_success()
1✔
287

288
        return result if self._modifier is None else self._modifier(result)
1✔
289

290
    def validate(
1✔
291
        self, validator: Callable[[InputValueT], None]
1✔
292
    ) -> "InputItem":
1✔
293
        """
294
        Append a validator in the input item validators list
295

296
        Returns
297
        -------
298
        self (InputItem): The input item itself
299
        """
300

301
        self._validators.append(validator)
1✔
302
        return self
1✔
303

304
    def condition(
1✔
305
        self, condition: Callable[[InputValueT], bool]
1✔
306
    ) -> "InputItem":
1✔
307
        """
308
        Set a condition for the execution of the previous validator
309

310
        Parameters
311
        ----------
312
        condition : Callable
313
                a callable that return a boolean that defines if the condition
314
                was satisfied
315

316
        Returns
317
        -------
318
        InputItem
319
        """
320

321
        self._conditions[self._validators[-1]] = condition
1✔
322
        return self
1✔
323

324
    def modifier(self, modifier: Callable[[InputValueT], bool]) -> "InputItem":
1✔
325
        """
326
        Set a modifier to allow changes in the value after validation
327

328
        Parameters
329
        ----------
330
        modifier : Callable
331
                a callable that executes changes in the value after validation
332

333
        Returns
334
        -------
335
        InputItem
336
        """
337

338
        self._modifier = modifier
1✔
339
        return self
1✔
340

341
    def string(self) -> StringValidator:
1✔
342
        """
343
        create a StringValidator using the input item as base
344

345
        Returns
346
        -------
347
        result (StringValidator): A string validator object
348
        """
349
        return StringValidator(self)
1✔
350

351
    def number(self) -> NumericValidator:
1✔
352
        """
353
        create a NumericValidator using the input item as base
354

355
        Returns
356
        -------
357
        result (NumericValidator): A numeric validator object
358
        """
359
        return NumericValidator(self)
1✔
360

361
    def array(self) -> ArrayValidator:
1✔
362
        """
363
        create a ArrayValidator using the input item as base
364

365
        Returns
366
        -------
367
        result (ArrayValidator): An array validator object
368
        """
369
        return ArrayValidator(self)
1✔
370

371
    def dict(self) -> DictValidator:
1✔
372
        """
373
        create a DictValidator using the input item as base
374

375
        Returns
376
        -------
377
        result (DictValidator): A dict validator object
378
        """
379
        return DictValidator(self)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc