首页 > 解决方案 > Python asynctest 模拟补丁装饰器溢出到后续测试中

问题描述

我正在尝试测试异步功能。为此,我正在使用pytest-asyncioand asynctest。我需要检查在我正在测试的函数中使用的函数被调用了多少次。为此,我正在使用aynsctest.mock.patch(). 我的测试文件如下所示:

@pytest.mark.asyncio
@asynctest.mock.patch('my_module.function_name')
async def test_function_called_twice(function_mock):
    await function_to_be_tested()
    assert function_mock.call_count == 2

@pytest.mark.asyncio
@asynctest.mock.patch('my_module.function_name')
async def test_function_called_once(function_mock):
    await function_to_be_tested()
    assert function_mock.call_count == 1

如果我单独运行测试用例,它们就会通过。但是,当我运行整个模块时,要运行的第二个测试用例会失败 - 无论它们运行的​​顺序如何。我怀疑这是因为第一个测试用例的模拟仍然影响要运行的第二个测试用例。

我在这里做错了什么?

标签: pytestpython-asynciopytest-mockpytest-asyncioasynctest

解决方案


推荐阅读