Python-单元测试补丁

时间:2019-12-26 16:04:17

标签: python testing mocking

我在让@patch与单元测试一起工作时遇到了一些问题,在修补导入之后,似乎没有选择模拟,而是使用了'regular'类

我要测试的类和方法如下所示(为方便起见,已简化)

from sila2lib.sila_server import SiLA2Server
# ... snip ...

class DeviceService:

def __init__(self, central_message_queue: asyncio.Queue, config: Config):

    self.central_message_queue: asyncio.Queue = central_message_queue
    self.logger = logging.getLogger('GWLogger')

    # ...... snip ......

async def start_device_server(self, tag_config: dict) -> asyncio.Queue:

    # Message queue used for passing messages to running device features (instrument readings)
    name = tag_config["Name"]
    uuid = tag_config["UUID"]
    cfg = tag_config["FeatureConfig"]

    # SiLA Server Setup [This is what I want to mock]
    self.device_server = SiLA2Server(name=name,
                                     description="Provides Device specific functions",
                                     server_uuid=uuid,
                                     port=self.device_server_port,
                                     ip=self.device_server_address,
                                     simulation_mode=False,
                                     key_file=None,
                                     cert_file=None)

    # ........ snip .......

还有一个示例测试-我要做的就是将SilaServer换成MagicMock,这样我就可以验证使用正确的参数调用了一个方法

import asynctest, asyncio
from tests.util.MockConfig import build_mock_config
from unittest.mock import patch, MagicMock
from services.device.DeviceService import DeviceService

class DeviceServiceTests(asynctest.TestCase):

@patch("services.device.DeviceService.SiLA2Server")
async def test_device_info_load(self, mock_sila_server_class):

    mock_sila_server_instance = MagicMock()
    mock_sila_server_class.return_value = mock_sila_server_instance
    message_queue = asyncio.Queue()
    device_service = DeviceService(message_queue, build_mock_config())
    device_service.logger = MagicMock()

    await device_service.start_device_server(empty_tag_config)

    # Test feature has been set
    mock_sila_server_instance.add_feature.assert_called_with(data_path='',
                                                             feature_id='DeviceInfo',
                                                             servicer=None)

    # Check that server was started
    mock_sila_server_instance.run.assert_called_with(block=False)

项目结构

Project Structure

由于未使用模拟程序,因此测试运行失败,并且我得到了一个断言异常,这是您所期望的,添加了一个断点并检查device_service是否使用了实际的类

Var inspect

我觉得这确实很明显,但是我看不到,我有其他类似的测试可以与@patch装饰器一起使用,但是在这些测试中的应用方式似乎没有任何区别还有这个

真的很感谢任何帮助

1 个答案:

答案 0 :(得分:0)

弄清楚了,我在混合asynctest和标准的unittest库

此行:

from unittest.mock import patch, MagicMock

应该是:

from asynctest.mock import patch, MagicMock