Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic/_internal/_mock_val_ser.py: 38%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

104 statements  

1from __future__ import annotations 

2 

3from collections.abc import Callable, Iterator, Mapping 

4from typing import TYPE_CHECKING, Any, Generic, Literal, Protocol, TypeVar 

5 

6from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator 

7 

8from ..errors import PydanticErrorCodes, PydanticUserError 

9from ..plugin._schema_validator import PluggableSchemaValidator 

10 

11if TYPE_CHECKING: 

12 from ..dataclasses import PydanticDataclass 

13 from ..main import BaseModel 

14 from ..type_adapter import TypeAdapter 

15 

16 

17ValSer = TypeVar('ValSer', bound=SchemaValidator | PluggableSchemaValidator | SchemaSerializer) 

18T = TypeVar('T') 

19T_co = TypeVar('T_co', covariant=True) 

20 

21 

22class AttemptRebuild(Protocol[T_co]): 

23 def __call__(self, *, parent_namespace_depth: int = ...) -> T_co | None: ... 

24 

25 

26class MockCoreSchema(Mapping[str, Any]): 

27 """Mocker for `pydantic_core.CoreSchema` which optionally attempts to 

28 rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails. 

29 """ 

30 

31 __slots__ = '_error_message', '_code', '_attempt_rebuild', '_built_memo' 

32 

33 def __init__( 

34 self, 

35 error_message: str, 

36 *, 

37 code: PydanticErrorCodes, 

38 attempt_rebuild: AttemptRebuild[CoreSchema] | None = None, 

39 ) -> None: 

40 self._error_message = error_message 

41 self._code: PydanticErrorCodes = code 

42 self._attempt_rebuild = attempt_rebuild 

43 self._built_memo: CoreSchema | None = None 

44 

45 def __getitem__(self, key: str) -> Any: 

46 return self._get_built().__getitem__(key) 

47 

48 def __len__(self) -> int: 

49 return self._get_built().__len__() 

50 

51 def __iter__(self) -> Iterator[str]: 

52 return self._get_built().__iter__() 

53 

54 def _get_built(self) -> CoreSchema: 

55 if self._built_memo is not None: 

56 return self._built_memo 

57 

58 if self._attempt_rebuild: 

59 schema = self._attempt_rebuild() 

60 if schema is not None: 

61 self._built_memo = schema 

62 return schema 

63 raise PydanticUserError(self._error_message, code=self._code) 

64 

65 def rebuild(self) -> CoreSchema | None: 

66 self._built_memo = None 

67 if self._attempt_rebuild: 

68 schema = self._attempt_rebuild() 

69 if schema is not None: 

70 return schema 

71 else: 

72 raise PydanticUserError(self._error_message, code=self._code) 

73 return None 

74 

75 

76class MockValSer(Generic[ValSer]): 

77 """Mocker for `pydantic_core.SchemaValidator` or `pydantic_core.SchemaSerializer` which optionally attempts to 

78 rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails. 

79 """ 

80 

81 __slots__ = '_error_message', '_code', '_val_or_ser', '_attempt_rebuild' 

82 

83 def __init__( 

84 self, 

85 error_message: str, 

86 *, 

87 code: PydanticErrorCodes, 

88 val_or_ser: Literal['validator', 'serializer'], 

89 attempt_rebuild: AttemptRebuild[ValSer] | None = None, 

90 ) -> None: 

91 self._error_message = error_message 

92 self._val_or_ser = SchemaValidator if val_or_ser == 'validator' else SchemaSerializer 

93 self._code: PydanticErrorCodes = code 

94 self._attempt_rebuild = attempt_rebuild 

95 

96 def __getattr__(self, item: str) -> None: 

97 __tracebackhide__ = True 

98 if self._attempt_rebuild: 

99 val_ser = self._attempt_rebuild() 

100 if val_ser is not None: 

101 return getattr(val_ser, item) 

102 

103 # raise an AttributeError if `item` doesn't exist 

104 getattr(self._val_or_ser, item) 

105 raise PydanticUserError(self._error_message, code=self._code) 

106 

107 def rebuild(self, *, parent_namespace_depth: int = 5) -> ValSer | None: 

108 if self._attempt_rebuild: 

109 val_ser = self._attempt_rebuild(parent_namespace_depth=parent_namespace_depth) 

110 if val_ser is not None: 

111 return val_ser 

112 else: 

113 raise PydanticUserError(self._error_message, code=self._code) 

114 return None 

115 

116 

117def set_type_adapter_mocks(adapter: TypeAdapter) -> None: 

118 """Set `core_schema`, `validator` and `serializer` to mock core types on a type adapter instance. 

119 

120 Args: 

121 adapter: The type adapter instance to set the mocks on 

122 """ 

123 type_repr = str(adapter._type) 

124 undefined_type_error_message = ( 

125 f'`TypeAdapter[{type_repr}]` is not fully defined; you should define `{type_repr}` and all referenced types,' 

126 f' then call `.rebuild()` on the instance.' 

127 ) 

128 

129 def attempt_rebuild_fn(attr_fn: Callable[[TypeAdapter], T]) -> AttemptRebuild[T]: 

130 def handler(*, parent_namespace_depth: int = 5) -> T | None: 

131 if adapter.rebuild(raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False: 

132 return attr_fn(adapter) 

133 return None 

134 

135 return handler 

136 

137 adapter.core_schema = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue] 

138 undefined_type_error_message, 

139 code='class-not-fully-defined', 

140 attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.core_schema), 

141 ) 

142 adapter.validator = MockValSer( # pyright: ignore[reportAttributeAccessIssue] 

143 undefined_type_error_message, 

144 code='class-not-fully-defined', 

145 val_or_ser='validator', 

146 attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.validator), 

147 ) 

148 adapter.serializer = MockValSer( # pyright: ignore[reportAttributeAccessIssue] 

149 undefined_type_error_message, 

150 code='class-not-fully-defined', 

151 val_or_ser='serializer', 

152 attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.serializer), 

153 ) 

154 

155 

156def set_model_mocks(cls: type[BaseModel], undefined_name: str | None = None) -> None: 

157 """Set `__pydantic_core_schema__`, `__pydantic_validator__` and `__pydantic_serializer__` to mock core types on a model. 

158 

159 Args: 

160 cls: The model class to set the mocks on 

161 undefined_name: Name of the undefined thing, used in error messages 

162 """ 

163 undefined_name = undefined_name if undefined_name is not None else 'all referenced types' 

164 

165 undefined_type_error_message = ( 

166 f'`{cls.__name__}` is not fully defined; you should define {undefined_name},' 

167 f' then call `{cls.__name__}.model_rebuild()`.' 

168 ) 

169 

170 def attempt_rebuild_fn(attr_fn: Callable[[type[BaseModel]], T]) -> AttemptRebuild[T]: 

171 def handler(*, parent_namespace_depth: int = 5) -> T | None: 

172 if cls.model_rebuild(raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False: 

173 return attr_fn(cls) 

174 return None 

175 

176 return handler 

177 

178 cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue] 

179 undefined_type_error_message, 

180 code='class-not-fully-defined', 

181 attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__), 

182 ) 

183 cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue] 

184 undefined_type_error_message, 

185 code='class-not-fully-defined', 

186 val_or_ser='validator', 

187 attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__), 

188 ) 

189 cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue] 

190 undefined_type_error_message, 

191 code='class-not-fully-defined', 

192 val_or_ser='serializer', 

193 attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__), 

194 ) 

195 

196 

197def set_dataclass_mocks(cls: type[PydanticDataclass], undefined_name: str | None = None) -> None: 

198 """Set `__pydantic_validator__` and `__pydantic_serializer__` to `MockValSer`s on a dataclass. 

199 

200 Args: 

201 cls: The model class to set the mocks on 

202 undefined_name: Name of the undefined thing, used in error messages 

203 """ 

204 from ..dataclasses import rebuild_dataclass 

205 

206 undefined_name = undefined_name if undefined_name is not None else 'all referenced types' 

207 

208 undefined_type_error_message = ( 

209 f'`{cls.__name__}` is not fully defined; you should define {undefined_name},' 

210 f' then call `pydantic.dataclasses.rebuild_dataclass({cls.__name__})`.' 

211 ) 

212 

213 def attempt_rebuild_fn(attr_fn: Callable[[type[PydanticDataclass]], T]) -> AttemptRebuild[T]: 

214 def handler(*, parent_namespace_depth: int = 5) -> T | None: 

215 if rebuild_dataclass(cls, raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False: 

216 return attr_fn(cls) 

217 return None 

218 

219 return handler 

220 

221 cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue] 

222 undefined_type_error_message, 

223 code='class-not-fully-defined', 

224 attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__), 

225 ) 

226 cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue] 

227 undefined_type_error_message, 

228 code='class-not-fully-defined', 

229 val_or_ser='validator', 

230 attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__), 

231 ) 

232 cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue] 

233 undefined_type_error_message, 

234 code='class-not-fully-defined', 

235 val_or_ser='serializer', 

236 attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__), 

237 )