Skip to main content
 首页 » 编程设计

带有 Aiohttp 的 Python Mock 不是模拟

2025年02月15日10lyhabc

我在工作中使用 AioHttp 来实现一个服务,在我的测试期间,我正在模拟一个方法,问题是对该方法的调用是调用真实的而不是模拟的方法。

@unittest_run_loop 
@patch('export_api.main.add_job_to_db') 
async def test_view_job(self, mocked_method): 
    json = { 
        "edl": "somedata" 
    } 
    response = await self.client.request("PUT", "/v1/job", json=json) 
    mocked_method.assert_called_once_with() 
    assert response.status == 200 

所以我在模拟的断言中得到了这个错误:

msg = "Expected 'add_job_to_db' to be called once. Called 0 times." 

我在 main.py 上的方法:

 async def __call__(self, request): 
    """Faz post do Job na fila do Render""" 
    data = await request.json() 
    job_id = uuid.uuid4() 
    job = Jobs( 
        job_id=str(job_id), 
        body=data 
        ) 
    try: 
        add_job_to_db(self.app['db'], job) 
        return web.Response(status=200) 
    except DatabaseError as e: 
        print(e) 
        return web.Response(status=500) 

是的,是一个类中的可调用方法。没有模拟,测试工作正常。但是我需要模拟对数据库的调用,到目前为止我运气不好。 有什么想法吗?

请您参考如下方法:

list :

  1. 使用asynctest包
  2. 不要忘记在单元测试周围使用 @asyncio.coroutine 装饰器
  3. 在使用它的地方修补对象,在本例中它是 export_api.main.add_job_to_db