I have come across this problem when making my unit tests.
from unittest.mock import AsyncMock, patch
import pydantic
# class Parent(): # Using non-pydantic class works
class Parent(pydantic.BaseModel): # Using pydantic.BaseModel makes this test fail.
async def method(self):
raise NotImplementedError
class Child(Parent):
async def method(self):
# Overriding the parent method
return False
async def test_patching():
child_instance = Child()
with patch.object(child_instance, 'method', new_callable=AsyncMock) as mock_method:
mock_method.return_value = True
assert await child_instance.method() is True
This results in the error:
AttributeError: 'Child' object has no attribute 'method'
If I do not use the pydantic.BaseModel, I do not get this error.
What can I do to fix this?
asked Sep 29 at 15:42
-
Might look like parent/child is irrelevant.Automatico– Automatico2025年09月29日 15:45:21 +00:00Commented Sep 29 at 15:45
-
Here is some relevant dialog around this, but the solution of "not using basemodel" here is in sufficient in my case. github.com/pydantic/pydantic/discussions/4537Automatico– Automatico2025年09月29日 15:52:52 +00:00Commented Sep 29 at 15:52
-
The problem is equivalent of this: stackoverflow.com/questions/75804182/…Automatico– Automatico2025年09月29日 16:00:02 +00:00Commented Sep 29 at 16:00
1 Answer 1
It seems that pydantic somehow changes the internals of the object.
The method is located under the __dict__ -object inside of the object. Rewriting the test to the below solves the issue.
The parent child relationship is not important in this case.
from unittest.mock import AsyncMock, patch
import pydantic
class Parent(pydantic.BaseModel):
async def method(self):
raise NotImplementedError
class Child(Parent):
async def method(self):
# Overriding the parent method
return False
async def test_patching():
child_instance = Child()
with patch.dict(
child_instance.__dict__,
{"method": AsyncMock(),}
) as mocked_dict:
mocked_dict["method"].return_value = True
assert await child_instance.method() is True
answered Sep 29 at 16:14
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-py