-1

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
3

1 Answer 1

0

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.