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

abravalheri / validate-pyproject / 5226968556240896

pending completion
5226968556240896

push

cirrus-ci

GitHub
Typo: validate-project => validate-pyproject (#78)

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

99.18
/src/validate_pyproject/error_reporting.py
1
import io
8✔
2
import json
8✔
3
import logging
8✔
4
import os
8✔
5
import re
8✔
6
from contextlib import contextmanager
8✔
7
from textwrap import indent, wrap
8✔
8
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union, cast
8✔
9

10
from ._vendor.fastjsonschema import JsonSchemaValueException
8✔
11

12
_logger = logging.getLogger(__name__)
8✔
13

14
_MESSAGE_REPLACEMENTS = {
8✔
15
    "must be named by propertyName definition": "keys must be named by",
16
    "one of contains definition": "at least one item that matches",
17
    " same as const definition:": "",
18
    "only specified items": "only items matching the definition",
19
}
20

21
_SKIP_DETAILS = (
8✔
22
    "must not be empty",
23
    "is always invalid",
24
    "must not be there",
25
)
26

27
_NEED_DETAILS = {"anyOf", "oneOf", "anyOf", "contains", "propertyNames", "not", "items"}
8✔
28

29
_CAMEL_CASE_SPLITTER = re.compile(r"\W+|([A-Z][^A-Z\W]*)")
8✔
30
_IDENTIFIER = re.compile(r"^[\w_]+$", re.I)
8✔
31

32
_TOML_JARGON = {
8✔
33
    "object": "table",
34
    "property": "key",
35
    "properties": "keys",
36
    "property names": "keys",
37
}
38

39

40
class ValidationError(JsonSchemaValueException):
8✔
41
    """Report violations of a given JSON schema.
42

43
    This class extends :exc:`~fastjsonschema.JsonSchemaValueException`
44
    by adding the following properties:
45

46
    - ``summary``: an improved version of the ``JsonSchemaValueException`` error message
47
      with only the necessary information)
48

49
    - ``details``: more contextual information about the error like the failing schema
50
      itself and the value that violates the schema.
51

52
    Depending on the level of the verbosity of the ``logging`` configuration
53
    the exception message will be only ``summary`` (default) or a combination of
54
    ``summary`` and ``details`` (when the logging level is set to :obj:`logging.DEBUG`).
55
    """
56

57
    summary = ""
8✔
58
    details = ""
8✔
59
    _original_message = ""
8✔
60

61
    @classmethod
8✔
62
    def _from_jsonschema(cls, ex: JsonSchemaValueException):
8✔
63
        formatter = _ErrorFormatting(ex)
8✔
64
        obj = cls(str(formatter), ex.value, formatter.name, ex.definition, ex.rule)
8✔
65
        debug_code = os.getenv("JSONSCHEMA_DEBUG_CODE_GENERATION", "false").lower()
8✔
66
        if debug_code != "false":  # pragma: no cover
67
            obj.__cause__, obj.__traceback__ = ex.__cause__, ex.__traceback__
68
        obj._original_message = ex.message
8✔
69
        obj.summary = formatter.summary
8✔
70
        obj.details = formatter.details
8✔
71
        return obj
8✔
72

73

74
@contextmanager
8✔
75
def detailed_errors():
6 all except 5226968556240896.2 and 5226968556240896.4 ✔
76
    try:
8✔
77
        yield
8✔
78
    except JsonSchemaValueException as ex:
8✔
79
        raise ValidationError._from_jsonschema(ex) from None
8✔
80

81

82
class _ErrorFormatting:
8✔
83
    def __init__(self, ex: JsonSchemaValueException):
8✔
84
        self.ex = ex
8✔
85
        self.name = f"`{self._simplify_name(ex.name)}`"
8✔
86
        self._original_message = self.ex.message.replace(ex.name, self.name)
8✔
87
        self._summary = ""
8✔
88
        self._details = ""
8✔
89

90
    def __str__(self) -> str:
8✔
91
        if _logger.getEffectiveLevel() <= logging.DEBUG and self.details:
8✔
92
            return f"{self.summary}\n\n{self.details}"
8✔
93

94
        return self.summary
8✔
95

96
    @property
8✔
97
    def summary(self) -> str:
8✔
98
        if not self._summary:
8✔
99
            self._summary = self._expand_summary()
8✔
100

101
        return self._summary
8✔
102

103
    @property
8✔
104
    def details(self) -> str:
8✔
105
        if not self._details:
8✔
106
            self._details = self._expand_details()
8✔
107

108
        return self._details
8✔
109

110
    def _simplify_name(self, name):
8✔
111
        x = len("data.")
8✔
112
        return name[x:] if name.startswith("data.") else name
8✔
113

114
    def _expand_summary(self):
8✔
115
        msg = self._original_message
8✔
116

117
        for bad, repl in _MESSAGE_REPLACEMENTS.items():
8✔
118
            msg = msg.replace(bad, repl)
8✔
119

120
        if any(substring in msg for substring in _SKIP_DETAILS):
8✔
121
            return msg
8✔
122

123
        schema = self.ex.rule_definition
8✔
124
        if self.ex.rule in _NEED_DETAILS and schema:
8✔
125
            summary = _SummaryWriter(_TOML_JARGON)
8✔
126
            return f"{msg}:\n\n{indent(summary(schema), '    ')}"
8✔
127

128
        return msg
8✔
129

130
    def _expand_details(self) -> str:
8✔
131
        optional = []
8✔
132
        desc_lines = self.ex.definition.pop("$$description", [])
8✔
133
        desc = self.ex.definition.pop("description", None) or " ".join(desc_lines)
8✔
134
        if desc:
8✔
135
            description = "\n".join(
8✔
136
                wrap(
137
                    desc,
138
                    width=80,
139
                    initial_indent="    ",
140
                    subsequent_indent="    ",
141
                    break_long_words=False,
142
                )
143
            )
144
            optional.append(f"DESCRIPTION:\n{description}")
8✔
145
        schema = json.dumps(self.ex.definition, indent=4)
8✔
146
        value = json.dumps(self.ex.value, indent=4)
8✔
147
        defaults = [
8✔
148
            f"GIVEN VALUE:\n{indent(value, '    ')}",
149
            f"OFFENDING RULE: {self.ex.rule!r}",
150
            f"DEFINITION:\n{indent(schema, '    ')}",
151
        ]
152
        return "\n\n".join(optional + defaults)
8✔
153

154

155
class _SummaryWriter:
8✔
156
    _IGNORE = {"description", "default", "title", "examples"}
8✔
157

158
    def __init__(self, jargon: Optional[Dict[str, str]] = None):
8✔
159
        self.jargon: Dict[str, str] = jargon or {}
8✔
160
        # Clarify confusing terms
161
        self._terms = {
8✔
162
            "anyOf": "at least one of the following",
163
            "oneOf": "exactly one of the following",
164
            "allOf": "all of the following",
165
            "not": "(*NOT* the following)",
166
            "prefixItems": f"{self._jargon('items')} (in order)",
167
            "items": "items",
168
            "contains": "contains at least one of",
169
            "propertyNames": (
170
                f"non-predefined acceptable {self._jargon('property names')}"
171
            ),
172
            "patternProperties": f"{self._jargon('properties')} named via pattern",
173
            "const": "predefined value",
174
            "enum": "one of",
175
        }
176
        # Attributes that indicate that the definition is easy and can be done
177
        # inline (e.g. string and number)
178
        self._guess_inline_defs = [
8✔
179
            "enum",
180
            "const",
181
            "maxLength",
182
            "minLength",
183
            "pattern",
184
            "format",
185
            "minimum",
186
            "maximum",
187
            "exclusiveMinimum",
188
            "exclusiveMaximum",
189
            "multipleOf",
190
        ]
191

192
    def _jargon(self, term: Union[str, List[str]]) -> Union[str, List[str]]:
8✔
193
        if isinstance(term, list):
8✔
194
            return [self.jargon.get(t, t) for t in term]
8✔
195
        return self.jargon.get(term, term)
8✔
196

197
    def __call__(
8✔
198
        self,
199
        schema: Union[dict, List[dict]],
200
        prefix: str = "",
201
        *,
202
        _path: Sequence[str] = (),
203
    ) -> str:
204
        if isinstance(schema, list):
8✔
205
            return self._handle_list(schema, prefix, _path)
8✔
206

207
        filtered = self._filter_unecessary(schema, _path)
8✔
208
        simple = self._handle_simple_dict(filtered, _path)
8✔
209
        if simple:
8✔
210
            return f"{prefix}{simple}"
8✔
211

212
        child_prefix = self._child_prefix(prefix, "  ")
8✔
213
        item_prefix = self._child_prefix(prefix, "- ")
8✔
214
        indent = len(prefix) * " "
8✔
215
        with io.StringIO() as buffer:
8✔
216
            for i, (key, value) in enumerate(filtered.items()):
8✔
217
                child_path = [*_path, key]
8✔
218
                line_prefix = prefix if i == 0 else indent
8✔
219
                buffer.write(f"{line_prefix}{self._label(child_path)}:")
8✔
220
                # ^  just the first item should receive the complete prefix
221
                if isinstance(value, dict):
8✔
222
                    filtered = self._filter_unecessary(value, child_path)
8✔
223
                    simple = self._handle_simple_dict(filtered, child_path)
8✔
224
                    buffer.write(
8✔
225
                        f" {simple}"
226
                        if simple
227
                        else f"\n{self(value, child_prefix, _path=child_path)}"
228
                    )
229
                elif isinstance(value, list) and (
8✔
230
                    key != "type" or self._is_property(child_path)
231
                ):
232
                    children = self._handle_list(value, item_prefix, child_path)
8✔
233
                    sep = " " if children.startswith("[") else "\n"
8✔
234
                    buffer.write(f"{sep}{children}")
8✔
235
                else:
236
                    buffer.write(f" {self._value(value, child_path)}\n")
8✔
237
            return buffer.getvalue()
8✔
238

239
    def _is_unecessary(self, path: Sequence[str]) -> bool:
8✔
240
        if self._is_property(path) or not path:  # empty path => instruction @ root
8✔
241
            return False
8✔
242
        key = path[-1]
8✔
243
        return any(key.startswith(k) for k in "$_") or key in self._IGNORE
8✔
244

245
    def _filter_unecessary(self, schema: dict, path: Sequence[str]):
8✔
246
        return {
8✔
247
            key: value
248
            for key, value in schema.items()
249
            if not self._is_unecessary([*path, key])
250
        }
251

252
    def _handle_simple_dict(self, value: dict, path: Sequence[str]) -> Optional[str]:
8✔
253
        inline = any(p in value for p in self._guess_inline_defs)
8✔
254
        simple = not any(isinstance(v, (list, dict)) for v in value.values())
8✔
255
        if inline or simple:
8✔
256
            return f"{{{', '.join(self._inline_attrs(value, path))}}}\n"
8✔
257
        return None
8✔
258

259
    def _handle_list(
8✔
260
        self, schemas: list, prefix: str = "", path: Sequence[str] = ()
261
    ) -> str:
262
        if self._is_unecessary(path):
8!
263
            return ""
×
264

265
        repr_ = repr(schemas)
8✔
266
        if all(not isinstance(e, (dict, list)) for e in schemas) and len(repr_) < 60:
8✔
267
            return f"{repr_}\n"
8✔
268

269
        item_prefix = self._child_prefix(prefix, "- ")
8✔
270
        return "".join(
8✔
271
            self(v, item_prefix, _path=[*path, f"[{i}]"]) for i, v in enumerate(schemas)
272
        )
273

274
    def _is_property(self, path: Sequence[str]):
8✔
275
        """Check if the given path can correspond to an arbitrarily named property"""
276
        counter = 0
8✔
277
        for key in path[-2::-1]:
8✔
278
            if key not in {"properties", "patternProperties"}:
8✔
279
                break
8✔
280
            counter += 1
8✔
281

282
        # If the counter if even, the path correspond to a JSON Schema keyword
283
        # otherwise it can be any arbitrary string naming a property
284
        return counter % 2 == 1
8✔
285

286
    def _label(self, path: Sequence[str]) -> str:
8✔
287
        *parents, key = path
8✔
288
        if not self._is_property(path):
8✔
289
            norm_key = _separate_terms(key)
8✔
290
            return self._terms.get(key) or " ".join(self._jargon(norm_key))
8✔
291

292
        if parents[-1] == "patternProperties":
8✔
293
            return f"(regex {key!r})"
8✔
294
        return repr(key)  # property name
8✔
295

296
    def _value(self, value: Any, path: Sequence[str]) -> str:
8✔
297
        if path[-1] == "type" and not self._is_property(path):
8✔
298
            type_ = self._jargon(value)
8✔
299
            return (
8✔
300
                f"[{', '.join(type_)}]" if isinstance(value, list) else cast(str, type_)
301
            )
302
        return repr(value)
8✔
303

304
    def _inline_attrs(self, schema: dict, path: Sequence[str]) -> Iterator[str]:
8✔
305
        for key, value in schema.items():
8✔
306
            child_path = [*path, key]
8✔
307
            yield f"{self._label(child_path)}: {self._value(value, child_path)}"
8✔
308

309
    def _child_prefix(self, parent_prefix: str, child_prefix: str) -> str:
8✔
310
        return len(parent_prefix) * " " + child_prefix
8✔
311

312

313
def _separate_terms(word: str) -> List[str]:
8✔
314
    """
315
    >>> _separate_terms("FooBar-foo")
316
    ['foo', 'bar', 'foo']
317
    """
318
    return [w.lower() for w in _CAMEL_CASE_SPLITTER.split(word) if w]
8✔
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