exceptions.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. """
  2. Validation errors, and some surrounding helpers.
  3. """
  4. from __future__ import annotations
  5. from collections import defaultdict, deque
  6. from pprint import pformat
  7. from textwrap import dedent, indent
  8. from typing import TYPE_CHECKING, ClassVar
  9. import heapq
  10. import itertools
  11. import warnings
  12. from attrs import define
  13. from referencing.exceptions import Unresolvable as _Unresolvable
  14. from jsonschema import _utils
  15. if TYPE_CHECKING:
  16. from collections.abc import Iterable, Mapping, MutableMapping
  17. WEAK_MATCHES: frozenset[str] = frozenset(["anyOf", "oneOf"])
  18. STRONG_MATCHES: frozenset[str] = frozenset()
  19. _unset = _utils.Unset()
  20. def __getattr__(name):
  21. if name == "RefResolutionError":
  22. warnings.warn(
  23. _RefResolutionError._DEPRECATION_MESSAGE,
  24. DeprecationWarning,
  25. stacklevel=2,
  26. )
  27. return _RefResolutionError
  28. raise AttributeError(f"module {__name__} has no attribute {name}")
  29. class _Error(Exception):
  30. _word_for_schema_in_error_message: ClassVar[str]
  31. _word_for_instance_in_error_message: ClassVar[str]
  32. def __init__(
  33. self,
  34. message: str,
  35. validator=_unset,
  36. path=(),
  37. cause=None,
  38. context=(),
  39. validator_value=_unset,
  40. instance=_unset,
  41. schema=_unset,
  42. schema_path=(),
  43. parent=None,
  44. type_checker=_unset,
  45. ):
  46. super().__init__(
  47. message,
  48. validator,
  49. path,
  50. cause,
  51. context,
  52. validator_value,
  53. instance,
  54. schema,
  55. schema_path,
  56. parent,
  57. )
  58. self.message = message
  59. self.path = self.relative_path = deque(path)
  60. self.schema_path = self.relative_schema_path = deque(schema_path)
  61. self.context = list(context)
  62. self.cause = self.__cause__ = cause
  63. self.validator = validator
  64. self.validator_value = validator_value
  65. self.instance = instance
  66. self.schema = schema
  67. self.parent = parent
  68. self._type_checker = type_checker
  69. for error in context:
  70. error.parent = self
  71. def __repr__(self):
  72. return f"<{self.__class__.__name__}: {self.message!r}>"
  73. def __str__(self):
  74. essential_for_verbose = (
  75. self.validator, self.validator_value, self.instance, self.schema,
  76. )
  77. if any(m is _unset for m in essential_for_verbose):
  78. return self.message
  79. schema_path = _utils.format_as_index(
  80. container=self._word_for_schema_in_error_message,
  81. indices=list(self.relative_schema_path)[:-1],
  82. )
  83. instance_path = _utils.format_as_index(
  84. container=self._word_for_instance_in_error_message,
  85. indices=self.relative_path,
  86. )
  87. prefix = 16 * " "
  88. return dedent(
  89. f"""\
  90. {self.message}
  91. Failed validating {self.validator!r} in {schema_path}:
  92. {indent(pformat(self.schema, width=72), prefix).lstrip()}
  93. On {instance_path}:
  94. {indent(pformat(self.instance, width=72), prefix).lstrip()}
  95. """.rstrip(),
  96. )
  97. @classmethod
  98. def create_from(cls, other):
  99. return cls(**other._contents())
  100. @property
  101. def absolute_path(self):
  102. parent = self.parent
  103. if parent is None:
  104. return self.relative_path
  105. path = deque(self.relative_path)
  106. path.extendleft(reversed(parent.absolute_path))
  107. return path
  108. @property
  109. def absolute_schema_path(self):
  110. parent = self.parent
  111. if parent is None:
  112. return self.relative_schema_path
  113. path = deque(self.relative_schema_path)
  114. path.extendleft(reversed(parent.absolute_schema_path))
  115. return path
  116. @property
  117. def json_path(self):
  118. path = "$"
  119. for elem in self.absolute_path:
  120. if isinstance(elem, int):
  121. path += "[" + str(elem) + "]"
  122. else:
  123. path += "." + elem
  124. return path
  125. def _set(self, type_checker=None, **kwargs):
  126. if type_checker is not None and self._type_checker is _unset:
  127. self._type_checker = type_checker
  128. for k, v in kwargs.items():
  129. if getattr(self, k) is _unset:
  130. setattr(self, k, v)
  131. def _contents(self):
  132. attrs = (
  133. "message", "cause", "context", "validator", "validator_value",
  134. "path", "schema_path", "instance", "schema", "parent",
  135. )
  136. return {attr: getattr(self, attr) for attr in attrs}
  137. def _matches_type(self):
  138. try:
  139. expected = self.schema["type"]
  140. except (KeyError, TypeError):
  141. return False
  142. if isinstance(expected, str):
  143. return self._type_checker.is_type(self.instance, expected)
  144. return any(
  145. self._type_checker.is_type(self.instance, expected_type)
  146. for expected_type in expected
  147. )
  148. class ValidationError(_Error):
  149. """
  150. An instance was invalid under a provided schema.
  151. """
  152. _word_for_schema_in_error_message = "schema"
  153. _word_for_instance_in_error_message = "instance"
  154. class SchemaError(_Error):
  155. """
  156. A schema was invalid under its corresponding metaschema.
  157. """
  158. _word_for_schema_in_error_message = "metaschema"
  159. _word_for_instance_in_error_message = "schema"
  160. @define(slots=False)
  161. class _RefResolutionError(Exception):
  162. """
  163. A ref could not be resolved.
  164. """
  165. _DEPRECATION_MESSAGE = (
  166. "jsonschema.exceptions.RefResolutionError is deprecated as of version "
  167. "4.18.0. If you wish to catch potential reference resolution errors, "
  168. "directly catch referencing.exceptions.Unresolvable."
  169. )
  170. _cause: Exception
  171. def __eq__(self, other):
  172. if self.__class__ is not other.__class__:
  173. return NotImplemented # pragma: no cover -- uncovered but deprecated # noqa: E501
  174. return self._cause == other._cause
  175. def __str__(self):
  176. return str(self._cause)
  177. class _WrappedReferencingError(_RefResolutionError, _Unresolvable): # pragma: no cover -- partially uncovered but to be removed # noqa: E501
  178. def __init__(self, cause: _Unresolvable):
  179. object.__setattr__(self, "_wrapped", cause)
  180. def __eq__(self, other):
  181. if other.__class__ is self.__class__:
  182. return self._wrapped == other._wrapped
  183. elif other.__class__ is self._wrapped.__class__:
  184. return self._wrapped == other
  185. return NotImplemented
  186. def __getattr__(self, attr):
  187. return getattr(self._wrapped, attr)
  188. def __hash__(self):
  189. return hash(self._wrapped)
  190. def __repr__(self):
  191. return f"<WrappedReferencingError {self._wrapped!r}>"
  192. def __str__(self):
  193. return f"{self._wrapped.__class__.__name__}: {self._wrapped}"
  194. class UndefinedTypeCheck(Exception):
  195. """
  196. A type checker was asked to check a type it did not have registered.
  197. """
  198. def __init__(self, type):
  199. self.type = type
  200. def __str__(self):
  201. return f"Type {self.type!r} is unknown to this type checker"
  202. class UnknownType(Exception):
  203. """
  204. A validator was asked to validate an instance against an unknown type.
  205. """
  206. def __init__(self, type, instance, schema):
  207. self.type = type
  208. self.instance = instance
  209. self.schema = schema
  210. def __str__(self):
  211. prefix = 16 * " "
  212. return dedent(
  213. f"""\
  214. Unknown type {self.type!r} for validator with schema:
  215. {indent(pformat(self.schema, width=72), prefix).lstrip()}
  216. While checking instance:
  217. {indent(pformat(self.instance, width=72), prefix).lstrip()}
  218. """.rstrip(),
  219. )
  220. class FormatError(Exception):
  221. """
  222. Validating a format failed.
  223. """
  224. def __init__(self, message, cause=None):
  225. super().__init__(message, cause)
  226. self.message = message
  227. self.cause = self.__cause__ = cause
  228. def __str__(self):
  229. return self.message
  230. class ErrorTree:
  231. """
  232. ErrorTrees make it easier to check which validations failed.
  233. """
  234. _instance = _unset
  235. def __init__(self, errors: Iterable[ValidationError] = ()):
  236. self.errors: MutableMapping[str, ValidationError] = {}
  237. self._contents: Mapping[str, ErrorTree] = defaultdict(self.__class__)
  238. for error in errors:
  239. container = self
  240. for element in error.path:
  241. container = container[element]
  242. container.errors[error.validator] = error
  243. container._instance = error.instance
  244. def __contains__(self, index: str | int):
  245. """
  246. Check whether ``instance[index]`` has any errors.
  247. """
  248. return index in self._contents
  249. def __getitem__(self, index):
  250. """
  251. Retrieve the child tree one level down at the given ``index``.
  252. If the index is not in the instance that this tree corresponds
  253. to and is not known by this tree, whatever error would be raised
  254. by ``instance.__getitem__`` will be propagated (usually this is
  255. some subclass of `LookupError`.
  256. """
  257. if self._instance is not _unset and index not in self:
  258. self._instance[index]
  259. return self._contents[index]
  260. def __setitem__(self, index: str | int, value: ErrorTree):
  261. """
  262. Add an error to the tree at the given ``index``.
  263. .. deprecated:: v4.20.0
  264. Setting items on an `ErrorTree` is deprecated without replacement.
  265. To populate a tree, provide all of its sub-errors when you
  266. construct the tree.
  267. """
  268. warnings.warn(
  269. "ErrorTree.__setitem__ is deprecated without replacement.",
  270. DeprecationWarning,
  271. stacklevel=2,
  272. )
  273. self._contents[index] = value # type: ignore[index]
  274. def __iter__(self):
  275. """
  276. Iterate (non-recursively) over the indices in the instance with errors.
  277. """
  278. return iter(self._contents)
  279. def __len__(self):
  280. """
  281. Return the `total_errors`.
  282. """
  283. return self.total_errors
  284. def __repr__(self):
  285. total = len(self)
  286. errors = "error" if total == 1 else "errors"
  287. return f"<{self.__class__.__name__} ({total} total {errors})>"
  288. @property
  289. def total_errors(self):
  290. """
  291. The total number of errors in the entire tree, including children.
  292. """
  293. child_errors = sum(len(tree) for _, tree in self._contents.items())
  294. return len(self.errors) + child_errors
  295. def by_relevance(weak=WEAK_MATCHES, strong=STRONG_MATCHES):
  296. """
  297. Create a key function that can be used to sort errors by relevance.
  298. Arguments:
  299. weak (set):
  300. a collection of validation keywords to consider to be
  301. "weak". If there are two errors at the same level of the
  302. instance and one is in the set of weak validation keywords,
  303. the other error will take priority. By default, :kw:`anyOf`
  304. and :kw:`oneOf` are considered weak keywords and will be
  305. superseded by other same-level validation errors.
  306. strong (set):
  307. a collection of validation keywords to consider to be
  308. "strong"
  309. """
  310. def relevance(error):
  311. validator = error.validator
  312. return ( # prefer errors which are ...
  313. -len(error.path), # 'deeper' and thereby more specific
  314. error.path, # earlier (for sibling errors)
  315. validator not in weak, # for a non-low-priority keyword
  316. validator in strong, # for a high priority keyword
  317. not error._matches_type(), # at least match the instance's type
  318. ) # otherwise we'll treat them the same
  319. return relevance
  320. relevance = by_relevance()
  321. """
  322. A key function (e.g. to use with `sorted`) which sorts errors by relevance.
  323. Example:
  324. .. code:: python
  325. sorted(validator.iter_errors(12), key=jsonschema.exceptions.relevance)
  326. """
  327. def best_match(errors, key=relevance):
  328. """
  329. Try to find an error that appears to be the best match among given errors.
  330. In general, errors that are higher up in the instance (i.e. for which
  331. `ValidationError.path` is shorter) are considered better matches,
  332. since they indicate "more" is wrong with the instance.
  333. If the resulting match is either :kw:`oneOf` or :kw:`anyOf`, the
  334. *opposite* assumption is made -- i.e. the deepest error is picked,
  335. since these keywords only need to match once, and any other errors
  336. may not be relevant.
  337. Arguments:
  338. errors (collections.abc.Iterable):
  339. the errors to select from. Do not provide a mixture of
  340. errors from different validation attempts (i.e. from
  341. different instances or schemas), since it won't produce
  342. sensical output.
  343. key (collections.abc.Callable):
  344. the key to use when sorting errors. See `relevance` and
  345. transitively `by_relevance` for more details (the default is
  346. to sort with the defaults of that function). Changing the
  347. default is only useful if you want to change the function
  348. that rates errors but still want the error context descent
  349. done by this function.
  350. Returns:
  351. the best matching error, or ``None`` if the iterable was empty
  352. .. note::
  353. This function is a heuristic. Its return value may change for a given
  354. set of inputs from version to version if better heuristics are added.
  355. """
  356. errors = iter(errors)
  357. best = next(errors, None)
  358. if best is None:
  359. return
  360. best = max(itertools.chain([best], errors), key=key)
  361. while best.context:
  362. # Calculate the minimum via nsmallest, because we don't recurse if
  363. # all nested errors have the same relevance (i.e. if min == max == all)
  364. smallest = heapq.nsmallest(2, best.context, key=key)
  365. if len(smallest) == 2 and key(smallest[0]) == key(smallest[1]): # noqa: PLR2004
  366. return best
  367. best = smallest[0]
  368. return best