我尝试为异步函数设置返回值。这是课程:
class Cache:
def __init__(self) -> None:
self.host = None
self.port = None
self.r = Redis()
async def init(self) -> bool:
"""Init redis pool"""
if not await self.r.ping():
self.host = config.CACHE_HOST
self.port = config.CACHE_PORT
await self.r.init(host=self.host, port=self.port)
return False
return True
我还有一个控制该类的类,这是该类:
class Adserver:
async def init(self):
cache_ok = await self.cache.init() //I want this mock
return cache_ok
单元测试:
@patch('aioads.storage.cache.Cache')
def test_cache_ok_true(self, fake_cache):
fake_cache.init.return_value = True
async def run_test():
a = self.adserver.cache
print(a) //Cache instance not MagicMock
output = await self.adserver.init() //Return false, it should be True
self.assertEqual(output, True)
self.loop.run_until_complete(run_test())
为什么fake_cache不会更改aioads类中的值缓存init?