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

LeanderCS / flask-inputfilter / #387

24 May 2025 12:54PM UTC coverage: 93.386% (-0.3%) from 93.644%
#387

Pull #56

coveralls-python

LeanderCS
48 | Updated IsDataclassValidator to also check against their types, including nested dataclasses, lists, and dictionaries
Pull Request #56: 48 | Update ArrayElementValidator and IsDataclassValidator

60 of 69 new or added lines in 4 files covered. (86.96%)

81 existing lines in 14 files now uncovered.

1878 of 2011 relevant lines covered (93.39%)

0.93 hits per line

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

92.59
/flask_inputfilter/validators/custom_json_validator.py
1
from __future__ import annotations
1✔
2

3
import json
1✔
4
from typing import Any, List, Optional
1✔
5

6
from flask_inputfilter.exceptions import ValidationError
1✔
7
from flask_inputfilter.validators import BaseValidator
1✔
8

9

10
class CustomJsonValidator(BaseValidator):
1✔
11
    """
12
    Validates that the provided value is valid JSON. It also checks
13
    for the presence of required fields and optionally verifies field
14
    types against a provided schema.
15

16
    **Parameters:**
17

18
    - **required_fields** (*list*, default: []): Fields that must exist
19
        in the JSON.
20
    - **schema** (*dict*, default: {}): A dictionary specifying expected
21
        types for certain fields.
22
    - **error_message** (*Optional[str]*): Custom error message if validation
23
        fails.
24

25
    **Expected Behavior:**
26

27
    If the input is a string, it attempts to parse it as JSON. It then confirms
28
    that the result is a dictionary, contains all required fields, and that each
29
    field adheres to the defined type in the schema.
30

31
    **Example Usage:**
32

33
    .. code-block:: python
34

35
        class JsonInputFilter(InputFilter):
36
            def __init__(self):
37
                super().__init__()
38

39
                self.add('data', validators=[
40
                    CustomJsonValidator(
41
                        required_fields=['id', 'name'],
42
                        schema={'id': int, 'name': str}
43
                    )
44
                ])
45
    """
46

47
    __slots__ = ("required_fields", "schema", "error_message")
1✔
48

49
    def __init__(
1✔
50
        self,
51
        required_fields: List[str] = None,
52
        schema: dict = None,
53
        error_message: Optional[str] = None,
54
    ) -> None:
55
        self.required_fields = required_fields or []
1✔
56
        self.schema = schema or {}
1✔
57
        self.error_message = error_message
1✔
58

59
    def validate(self, value: Any) -> None:
1✔
60
        if isinstance(value, str):
1✔
61
            try:
1✔
62
                value = json.loads(value)
1✔
63
            except json.JSONDecodeError:
1✔
64
                raise ValidationError("Invalid json format.")
1✔
65

66
        if not isinstance(value, dict):
1✔
UNCOV
67
            raise ValidationError("The input should be a dictionary.")
×
68

69
        for field in self.required_fields:
1✔
70
            if field not in value:
1✔
71
                raise ValidationError(f"Missing required field '{field}'.")
1✔
72

73
        if not self.schema:
1✔
UNCOV
74
            return
×
75

76
        for field, expected_type in self.schema.items():
1✔
77
            if field in value and not isinstance(value[field], expected_type):
1✔
78
                raise ValidationError(
1✔
79
                    self.error_message
80
                    or f"Field '{field}' has to be of type "
81
                    f"'{expected_type.__name__}'."
82
                )
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

© 2026 Coveralls, Inc