How to use side_effect from pytest framework with pydantic.ValidationError class? #6459
Replies: 4 comments 3 replies
-
The ValidationError class in Pydantic does not have a constructor, so you can't use the side_effect property to pass it as an argument to the mock.patch() function. you can use the side_effect_functools.partial() function to create a partial function that takes the exception message as an argument.
|
Beta Was this translation helpful? Give feedback.
-
I tried like this, but it doesn't work: /usr/lib/python3.9/unittest/mock.py:1096: in _mock_call
return self._execute_mock_call(*args, **kwargs)
def _execute_mock_call(self, /, *args, **kwargs):
# separate from _increment_mock_call so that awaited functions are
# executed separately from their call, also AsyncMock overrides this method
effect = self.side_effect
if effect is not None:
if _is_exception(effect):
raise effect
elif not _callable(effect):
result = next(effect)
if _is_exception(result):
raise result
else:
> result = effect(*args, **kwargs)
E TypeError: No constructor defined
/usr/lib/python3.9/unittest/mock.py:1157: TypeError |
Beta Was this translation helpful? Give feedback.
-
Hi @gamaleonardo, maybe as a workaround you could use a function that throws the ValidationError as a validate_mock = mocker.patch(
"my_package.MyClass.model_validate_json",
side_effect=lambda _: MyClass.model_validate_json(<some json that will fail the validation and cause a ValidationError>),
) |
Beta Was this translation helpful? Give feedback.
-
You could use from unittest.mock import Mock
from pydantic import ValidationError
func = Mock()
func.side_effect = ValidationError.from_exception_data("Invalid data", line_errors=[])
func() |
Beta Was this translation helpful? Give feedback.
-
Hi,
I'm trying to test my model validation exceptions with pytest.
When using the side_effect property (https://docs.python.org/3/library/unittest.mock.html#the-mock-class) I'm getting a TypeError, because the class pydantic.ValidationError does not have a constructor:
How to face this issue? Would you have an idea?
Thank you
Best regards,
Leonardo
Beta Was this translation helpful? Give feedback.
All reactions