()
| 215 | |
| 216 | |
| 217 | def test_stateful_plugin() -> None: |
| 218 | stack: list[Any] = [] |
| 219 | |
| 220 | class CustomOnValidatePython(ValidatePythonHandlerProtocol): |
| 221 | def on_enter( |
| 222 | self, |
| 223 | input: Any, |
| 224 | *, |
| 225 | strict: bool | None = None, |
| 226 | extra: ExtraValues | None = None, |
| 227 | from_attributes: bool | None = None, |
| 228 | context: Any | None = None, |
| 229 | self_instance: Any | None = None, |
| 230 | by_alias: bool | None = None, |
| 231 | by_name: bool | None = None, |
| 232 | ) -> None: |
| 233 | stack.append(input) |
| 234 | |
| 235 | def on_success(self, result: Any) -> None: |
| 236 | stack.pop() |
| 237 | |
| 238 | def on_error(self, error: Exception) -> None: |
| 239 | stack.pop() |
| 240 | |
| 241 | def on_exception(self, exception: Exception) -> None: |
| 242 | stack.pop() |
| 243 | |
| 244 | class Plugin(PydanticPluginProtocol): |
| 245 | def new_schema_validator(self, schema, schema_type, schema_type_path, schema_kind, config, plugin_settings): |
| 246 | return CustomOnValidatePython(), None, None |
| 247 | |
| 248 | plugin = Plugin() |
| 249 | |
| 250 | class MyException(Exception): |
| 251 | pass |
| 252 | |
| 253 | with install_plugin(plugin): |
| 254 | |
| 255 | class Model(BaseModel, plugin_settings={'observe': 'all'}): |
| 256 | a: int |
| 257 | |
| 258 | @field_validator('a') |
| 259 | def validate_a(cls, v: int) -> int: |
| 260 | if v < 0: |
| 261 | raise MyException |
| 262 | return v |
| 263 | |
| 264 | with contextlib.suppress(ValidationError): |
| 265 | Model.model_validate({'a': 'potato'}) |
| 266 | assert not stack |
| 267 | with contextlib.suppress(MyException): |
| 268 | Model.model_validate({'a': -1}) |
| 269 | assert not stack |
| 270 | assert Model.model_validate({'a': 1}).a == 1 |
| 271 | assert not stack |
| 272 | |
| 273 | |
| 274 | def test_all_handlers(): |
nothing calls this directly
no test coverage detected