protocols.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """
  2. typing.Protocol classes for jsonschema interfaces.
  3. """
  4. # for reference material on Protocols, see
  5. # https://www.python.org/dev/peps/pep-0544/
  6. from __future__ import annotations
  7. from typing import TYPE_CHECKING, Any, ClassVar, Protocol, runtime_checkable
  8. # in order for Sphinx to resolve references accurately from type annotations,
  9. # it needs to see names like `jsonschema.TypeChecker`
  10. # therefore, only import at type-checking time (to avoid circular references),
  11. # but use `jsonschema` for any types which will otherwise not be resolvable
  12. if TYPE_CHECKING:
  13. from collections.abc import Iterable, Mapping
  14. import referencing.jsonschema
  15. from jsonschema import _typing
  16. from jsonschema.exceptions import ValidationError
  17. import jsonschema
  18. import jsonschema.validators
  19. # For code authors working on the validator protocol, these are the three
  20. # use-cases which should be kept in mind:
  21. #
  22. # 1. As a protocol class, it can be used in type annotations to describe the
  23. # available methods and attributes of a validator
  24. # 2. It is the source of autodoc for the validator documentation
  25. # 3. It is runtime_checkable, meaning that it can be used in isinstance()
  26. # checks.
  27. #
  28. # Since protocols are not base classes, isinstance() checking is limited in
  29. # its capabilities. See docs on runtime_checkable for detail
  30. @runtime_checkable
  31. class Validator(Protocol):
  32. """
  33. The protocol to which all validator classes adhere.
  34. Arguments:
  35. schema:
  36. The schema that the validator object will validate with.
  37. It is assumed to be valid, and providing
  38. an invalid schema can lead to undefined behavior. See
  39. `Validator.check_schema` to validate a schema first.
  40. registry:
  41. a schema registry that will be used for looking up JSON references
  42. resolver:
  43. a resolver that will be used to resolve :kw:`$ref`
  44. properties (JSON references). If unprovided, one will be created.
  45. .. deprecated:: v4.18.0
  46. `RefResolver <_RefResolver>` has been deprecated in favor of
  47. `referencing`, and with it, this argument.
  48. format_checker:
  49. if provided, a checker which will be used to assert about
  50. :kw:`format` properties present in the schema. If unprovided,
  51. *no* format validation is done, and the presence of format
  52. within schemas is strictly informational. Certain formats
  53. require additional packages to be installed in order to assert
  54. against instances. Ensure you've installed `jsonschema` with
  55. its `extra (optional) dependencies <index:extras>` when
  56. invoking ``pip``.
  57. .. deprecated:: v4.12.0
  58. Subclassing validator classes now explicitly warns this is not part of
  59. their public API.
  60. """
  61. #: An object representing the validator's meta schema (the schema that
  62. #: describes valid schemas in the given version).
  63. META_SCHEMA: ClassVar[Mapping]
  64. #: A mapping of validation keywords (`str`\s) to functions that
  65. #: validate the keyword with that name. For more information see
  66. #: `creating-validators`.
  67. VALIDATORS: ClassVar[Mapping]
  68. #: A `jsonschema.TypeChecker` that will be used when validating
  69. #: :kw:`type` keywords in JSON schemas.
  70. TYPE_CHECKER: ClassVar[jsonschema.TypeChecker]
  71. #: A `jsonschema.FormatChecker` that will be used when validating
  72. #: :kw:`format` keywords in JSON schemas.
  73. FORMAT_CHECKER: ClassVar[jsonschema.FormatChecker]
  74. #: A function which given a schema returns its ID.
  75. ID_OF: _typing.id_of
  76. #: The schema that will be used to validate instances
  77. schema: Mapping | bool
  78. def __init__(
  79. self,
  80. schema: Mapping | bool,
  81. resolver: Any = None, # deprecated
  82. format_checker: jsonschema.FormatChecker | None = None,
  83. *,
  84. registry: referencing.jsonschema.SchemaRegistry = ...,
  85. ) -> None: ...
  86. @classmethod
  87. def check_schema(cls, schema: Mapping | bool) -> None:
  88. """
  89. Validate the given schema against the validator's `META_SCHEMA`.
  90. Raises:
  91. `jsonschema.exceptions.SchemaError`:
  92. if the schema is invalid
  93. """
  94. def is_type(self, instance: Any, type: str) -> bool:
  95. """
  96. Check if the instance is of the given (JSON Schema) type.
  97. Arguments:
  98. instance:
  99. the value to check
  100. type:
  101. the name of a known (JSON Schema) type
  102. Returns:
  103. whether the instance is of the given type
  104. Raises:
  105. `jsonschema.exceptions.UnknownType`:
  106. if ``type`` is not a known type
  107. """
  108. def is_valid(self, instance: Any) -> bool:
  109. """
  110. Check if the instance is valid under the current `schema`.
  111. Returns:
  112. whether the instance is valid or not
  113. >>> schema = {"maxItems" : 2}
  114. >>> Draft202012Validator(schema).is_valid([2, 3, 4])
  115. False
  116. """
  117. def iter_errors(self, instance: Any) -> Iterable[ValidationError]:
  118. r"""
  119. Lazily yield each of the validation errors in the given instance.
  120. >>> schema = {
  121. ... "type" : "array",
  122. ... "items" : {"enum" : [1, 2, 3]},
  123. ... "maxItems" : 2,
  124. ... }
  125. >>> v = Draft202012Validator(schema)
  126. >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str):
  127. ... print(error.message)
  128. 4 is not one of [1, 2, 3]
  129. [2, 3, 4] is too long
  130. .. deprecated:: v4.0.0
  131. Calling this function with a second schema argument is deprecated.
  132. Use `Validator.evolve` instead.
  133. """
  134. def validate(self, instance: Any) -> None:
  135. """
  136. Check if the instance is valid under the current `schema`.
  137. Raises:
  138. `jsonschema.exceptions.ValidationError`:
  139. if the instance is invalid
  140. >>> schema = {"maxItems" : 2}
  141. >>> Draft202012Validator(schema).validate([2, 3, 4])
  142. Traceback (most recent call last):
  143. ...
  144. ValidationError: [2, 3, 4] is too long
  145. """
  146. def evolve(self, **kwargs) -> Validator:
  147. """
  148. Create a new validator like this one, but with given changes.
  149. Preserves all other attributes, so can be used to e.g. create a
  150. validator with a different schema but with the same :kw:`$ref`
  151. resolution behavior.
  152. >>> validator = Draft202012Validator({})
  153. >>> validator.evolve(schema={"type": "number"})
  154. Draft202012Validator(schema={'type': 'number'}, format_checker=None)
  155. The returned object satisfies the validator protocol, but may not
  156. be of the same concrete class! In particular this occurs
  157. when a :kw:`$ref` occurs to a schema with a different
  158. :kw:`$schema` than this one (i.e. for a different draft).
  159. >>> validator.evolve(
  160. ... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]}
  161. ... )
  162. Draft7Validator(schema=..., format_checker=None)
  163. """