Python 单元测试模拟属性

问题描述 投票:0回答:1

我有一个连接到 PC 的设备,我为其 API 编写了一个 Python 包装器,以便我可以控制它。我为我的代码写了

unittest

有些值是从设备本身获取的,无法更改。

例如,要检查设备是否已连接,我必须从属性中读取它,并且无法更改它。

一个非常简化的版本:

请注意,我知道可能存在一些未定义的类或变量,但这是由于代码简化所致。

from win32com import client
from pythoncom import com_error


class Device:
    def __init__(self, port):
        try:
            self.device = client.Dispatch(port)
        except com_error:
            raise WrongSelect(
                f"No such {self.__class__.__name__} as {port}")

    def get_description(self):
        if self.device.connected:
            return self.device.Description
        
        raise NotConnected("Device is not Connected")

这里是测试代码:

import unittest
from unittest.mock import patch


class TestDevice(unittest.TestCase):
    def setUp(self):
        self.PORT = "A PORT"
        self.DEVICE = Device(self.PORT)

    def test_get_description(self):
        description = self.DEVICE.get_description()
        self.assertIsInstance(description, str)

    def test_get_description_not_connected(self):
        # How to mock self.DEVICE.device.connected
        pass

如何模拟对象的

connected
值?

python win32com python-unittest.mock
1个回答
0
投票

您可以使用

unittest.mock.patch.object
作为上下文管理器来临时更改上下文中局部变量中对象的属性值:

def test_get_description_not_connected(self):
    with patch.object(self.DEVICE.device, 'connected', new=False):
        with self.assertRaises(NotConnected):
            self.DEVICE.get_description()
© www.soinside.com 2019 - 2024. All rights reserved.