I am trying to patch a property of a class with some mock value, but when I run the test case the function or class that is using that property is not replacing it with the mock that I have created.
Module property that I need to mock
class Mymodule:
@property
async def calling_property(self):
return "Calling the property"
the class that is using this module.
class Usecase:
async def execute(self):
module = Mymodule()
data = await module.calling_property
print(data)
the test case I have written
import unittest
from unittest.mock import patch, AsyncMock,PropertyMock
class TestModule(unittest.IsolatedAsyncioTestCase):
async def test_execute(self):
with patch("users.usecases.medical_device.update_medical_device.Mymodule",
**{"calling_property":AsyncMock(return_value="calling mock")}, new_callable=PropertyMock
)as mock:
a = Usecase()
await a.execute()
As you can see i am logging the response from the property in my usecase, so when I run my test it is logging "calling the property" rather than "calling mock".
I tried another way.
class TestModule(unittest.IsolatedAsyncioTestCase):
async def test_execute(self):
with patch("users.usecases.medical_device.update_medical_device.Mymodule.calling_property",
new_callable=PropertyMock,
return_value= AsyncMock(return_value="calling mock")
)as mock:
a = A()
await a.execute()
This gives separate error
TypeError: object AsyncMock can't be used in 'await' expression
I have also tried creating a mock for the class object
class TestModule(unittest.IsolatedAsyncioTestCase):
async def test_execute(self):
with patch.object(Mymodule,
"calling_property",
new_callable=PropertyMock,
return_value=AsyncMock(return_value="calling mock")
)as mock:
a = A()
await a.execute()
TypeError: object AsyncMock can't be used in 'await' expression