exceptions.py 15 KB

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