Coverage for pydantic / plugin / _schema_validator.py: 100.00%

72 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Pluggable schema validator for pydantic.""" 

2 

3from __future__ import annotations 1abcdefghijklsmnopqr

4 

5import functools 1abcdefghijklsmnopqr

6from collections.abc import Callable, Iterable 1abcdefghijklsmnopqr

7from typing import TYPE_CHECKING, Any, Literal, ParamSpec, TypeVar 1abcdefghijklsmnopqr

8 

9from pydantic_core import CoreConfig, CoreSchema, SchemaValidator, ValidationError 1abcdefghijklsmnopqr

10 

11if TYPE_CHECKING: 1abcdefghijklsmnopqr

12 from . import BaseValidateHandlerProtocol, PydanticPluginProtocol, SchemaKind, SchemaTypePath 

13 

14 

15P = ParamSpec('P') 1abcdefghijklsmnopqr

16R = TypeVar('R') 1abcdefghijklsmnopqr

17Event = Literal['on_validate_python', 'on_validate_json', 'on_validate_strings'] 1abcdefghijklsmnopqr

18events: list[Event] = list(Event.__args__) # type: ignore 1abcdefghijklsmnopqr

19 

20 

21def create_schema_validator( 1abcdefghijklsmnopqr

22 schema: CoreSchema, 

23 schema_type: Any, 

24 schema_type_module: str, 

25 schema_type_name: str, 

26 schema_kind: SchemaKind, 

27 config: CoreConfig | None = None, 

28 plugin_settings: dict[str, Any] | None = None, 

29 _use_prebuilt: bool = True, 

30) -> SchemaValidator | PluggableSchemaValidator: 

31 """Create a `SchemaValidator` or `PluggableSchemaValidator` if plugins are installed. 

32 

33 Returns: 

34 If plugins are installed then return `PluggableSchemaValidator`, otherwise return `SchemaValidator`. 

35 """ 

36 from . import SchemaTypePath 1abcdefghijklsmnopqr

37 from ._loader import get_plugins 1abcdefghijklsmnopqr

38 

39 plugins = get_plugins() 1abcdefghijklsmnopqr

40 if plugins: 1abcdefghijklsmnopqr

41 return PluggableSchemaValidator( 1abcdefghijklmnopqr

42 schema, 

43 schema_type, 

44 SchemaTypePath(schema_type_module, schema_type_name), 

45 schema_kind, 

46 config, 

47 plugins, 

48 plugin_settings or {}, 

49 _use_prebuilt=_use_prebuilt, 

50 ) 

51 else: 

52 return SchemaValidator(schema, config, _use_prebuilt=_use_prebuilt) 1abcdefghijklsmnopqr

53 

54 

55class PluggableSchemaValidator: 1abcdefghijklsmnopqr

56 """Pluggable schema validator.""" 

57 

58 __slots__ = '_schema_validator', 'validate_json', 'validate_python', 'validate_strings' 1abcdefghijklsmnopqr

59 

60 def __init__( 1abcdefghijklsmnopqr

61 self, 

62 schema: CoreSchema, 

63 schema_type: Any, 

64 schema_type_path: SchemaTypePath, 

65 schema_kind: SchemaKind, 

66 config: CoreConfig | None, 

67 plugins: Iterable[PydanticPluginProtocol], 

68 plugin_settings: dict[str, Any], 

69 _use_prebuilt: bool = True, 

70 ) -> None: 

71 self._schema_validator = SchemaValidator(schema, config, _use_prebuilt=_use_prebuilt) 1abcdefghijklmnopqr

72 

73 python_event_handlers: list[BaseValidateHandlerProtocol] = [] 1abcdefghijklmnopqr

74 json_event_handlers: list[BaseValidateHandlerProtocol] = [] 1abcdefghijklmnopqr

75 strings_event_handlers: list[BaseValidateHandlerProtocol] = [] 1abcdefghijklmnopqr

76 for plugin in plugins: 1abcdefghijklmnopqr

77 try: 1abcdefghijklmnopqr

78 p, j, s = plugin.new_schema_validator( 1abcdefghijklmnopqr

79 schema, schema_type, schema_type_path, schema_kind, config, plugin_settings 

80 ) 

81 except TypeError as e: # pragma: no cover 

82 raise TypeError(f'Error using plugin `{plugin.__module__}:{plugin.__class__.__name__}`: {e}') from e 

83 if p is not None: 1abcdefghijklmnopqr

84 python_event_handlers.append(p) 1abcdefghijklmnopqr

85 if j is not None: 1abcdefghijklmnopqr

86 json_event_handlers.append(j) 1abcdefghijklmnopqr

87 if s is not None: 1abcdefghijklmnopqr

88 strings_event_handlers.append(s) 1abcdefghijklmnopqr

89 

90 self.validate_python = build_wrapper(self._schema_validator.validate_python, python_event_handlers) 1abcdefghijklmnopqr

91 self.validate_json = build_wrapper(self._schema_validator.validate_json, json_event_handlers) 1abcdefghijklmnopqr

92 self.validate_strings = build_wrapper(self._schema_validator.validate_strings, strings_event_handlers) 1abcdefghijklmnopqr

93 

94 # Used to allow reuse of validators in pydantic-core (see pydantic-core/src/validators/prebuilt.rs): 

95 @property 1abcdefghijklsmnopqr

96 def __pydantic_schema_validator__(self) -> SchemaValidator: 1abcdefghijklsmnopqr

97 """The underlying pydantic-core `SchemaValidator`. 

98 

99 This is a private attribute, not meant to be used outside Pydantic. 

100 """ 

101 return self._schema_validator 1abcdefghijklmnopqr

102 

103 def __getattr__(self, name: str) -> Any: 1abcdefghijklsmnopqr

104 return getattr(self._schema_validator, name) 1abcdefghijklmnopqr

105 

106 

107def build_wrapper(func: Callable[P, R], event_handlers: list[BaseValidateHandlerProtocol]) -> Callable[P, R]: 1abcdefghijklsmnopqr

108 if not event_handlers: 1abcdefghijklmnopqr

109 return func 1abcdefghijklmnopqr

110 else: 

111 on_enters = tuple(h.on_enter for h in event_handlers if filter_handlers(h, 'on_enter')) 1abcdefghijklmnopqr

112 on_successes = tuple(h.on_success for h in event_handlers if filter_handlers(h, 'on_success')) 1abcdefghijklmnopqr

113 on_errors = tuple(h.on_error for h in event_handlers if filter_handlers(h, 'on_error')) 1abcdefghijklmnopqr

114 on_exceptions = tuple(h.on_exception for h in event_handlers if filter_handlers(h, 'on_exception')) 1abcdefghijklmnopqr

115 

116 @functools.wraps(func) 1abcdefghijklmnopqr

117 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: 1abcdefghijklmnopqr

118 for on_enter_handler in on_enters: 1abcdefghijklmnopqr

119 on_enter_handler(*args, **kwargs) 1abcdefghijklmnopqr

120 

121 try: 1abcdefghijklmnopqr

122 result = func(*args, **kwargs) 1abcdefghijklmnopqr

123 except ValidationError as error: 1abcdefghijklmnopqr

124 for on_error_handler in on_errors: 1abcdefghijklmnopqr

125 on_error_handler(error) 1abcdefghijklmnopqr

126 raise 1abcdefghijklmnopqr

127 except Exception as exception: 1abcdefghijklmnopqr

128 for on_exception_handler in on_exceptions: 1abcdefghijklmnopqr

129 on_exception_handler(exception) 1abcdefghijklmnopqr

130 raise 1abcdefghijklmnopqr

131 else: 

132 for on_success_handler in on_successes: 1abcdefghijklmnopqr

133 on_success_handler(result) 1abcdefghijklmnopqr

134 return result 1abcdefghijklmnopqr

135 

136 return wrapper 1abcdefghijklmnopqr

137 

138 

139def filter_handlers(handler_cls: BaseValidateHandlerProtocol, method_name: str) -> bool: 1abcdefghijklsmnopqr

140 """Filter out handler methods which are not implemented by the plugin directly - e.g. those that are missing 

141 or are inherited from the protocol. 

142 """ 

143 handler = getattr(handler_cls, method_name, None) 1abcdefghijklmnopqr

144 if handler is None: 1abcdefghijklmnopqr

145 return False 1abcdefghijklmnopqr

146 elif handler.__module__ == 'pydantic.plugin': 1abcdefghijklmnopqr

147 # this is the original handler, from the protocol due to runtime inheritance 

148 # we don't want to call it 

149 return False 1abcdefghijklmnopqr

150 else: 

151 return True 1abcdefghijklmnopqr