Asynchronous pytestmock总是通过
我创建了一个pytest类来验证模块,但由于某些原因,它总是通过 从测试用例中可以看到,模拟中分配的返回值与所断言的不同,但测试用例通过了。我尝试了不同的选择,但仍然得到了相同的结果 我不知道执行测试用例的方法的异步性质是否是导致问题的原因 以下是测试套件:Asynchronous pytestmock总是通过,asynchronous,mocking,pytest,Asynchronous,Mocking,Pytest,我创建了一个pytest类来验证模块,但由于某些原因,它总是通过 从测试用例中可以看到,模拟中分配的返回值与所断言的不同,但测试用例通过了。我尝试了不同的选择,但仍然得到了相同的结果 我不知道执行测试用例的方法的异步性质是否是导致问题的原因 以下是测试套件: try: import mock except ImportError: from unittest import mock import unittest import pytest from asb_queue im
try:
import mock
except ImportError:
from unittest import mock
import unittest
import pytest
from asb_queue import AsbQueue
@pytest.mark.usefixtures('mocker')
class TestAsbQueue(unittest.TestCase):
# TODO: test_asbqueue_get_messages
@pytest.mark.asb_queue
@pytest.mark.asyncio
@mock.patch.object(AsbQueue, '_get_messages.receiver')
async def test_asbqueue_get_messages(self, mocked_instance) -> None:
""" Verify a message can be retrieve from from the Azure Service Bus Queue """
# Setup
import asyncio
loop = asyncio.get_event_loop()
mocked_instance.return_value = ['']
# Excercise - n/a
# Verify
assert AsbQueue(loop, False)._get_messages() == ['message']
# Cleanup
del loop
以下是模块(为了简单起见,我删去了不相关的代码):asb_队列。main.py
正如您可以看到的,AsbQueue类包含一个方法_get_messages,其中有一个对象,通过该对象可以从Azure队列收集数据,我想在这里放置模拟,我想用模拟替换Azure队列,以屏蔽依赖关系:receiver
以下是结果(为了简单起见,去掉警告):
您不能将unittest.mock与pytest混合使用,因此解决方案分为两个步骤:
import pytest
from asb_queue import AsbQueue
@pytest.mark.asb_queue
@pytest.mark.asyncio
async def test_asbqueue__get_messages_test(self, mocker) -> None:
""" Verify a message can be retrieve from the Azure Service Bus Queue """
# Setup
import asyncio
loop = asyncio.get_event_loop()
mocker.patch(
'asb_queue.__main__.AsbQueue._get_messages'
, return_value=['message'])
# Excercise - n/a
# Verify
assert ['message'] == await AsbQueue(loop, True)._get_messages()
# Cleanup
del loop
import pytest
from asb_queue import AsbQueue
@pytest.mark.asb_queue
@pytest.mark.asyncio
async def test_asbqueue__get_messages_test(self, mocker) -> None:
""" Verify a message can be retrieve from the Azure Service Bus Queue """
# Setup
import asyncio
loop = asyncio.get_event_loop()
mocker.patch(
'asb_queue.__main__.AsbQueue._get_messages'
, return_value=['message'])
# Excercise - n/a
# Verify
assert ['message'] == await AsbQueue(loop, True)._get_messages()
# Cleanup
del loop