修补类实例,并设置方法返回值

2024-09-30 01:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用传感器对象的报警对象。在我的测试中,我想用一个存根来修补传感器。下面的代码可以工作,但我必须显式地将存根传递给报警构造函数:

#tire_pressure_monitoring.py
from sensor import Sensor

class Alarm:

    def __init__(self, sensor=None):
        self._low_pressure_threshold = 17
        self._high_pressure_threshold = 21
        self._sensor = sensor or Sensor()
        self._is_alarm_on = False

    def check(self):
        psi_pressure_value = self._sensor.sample_pressure()
        if psi_pressure_value < self._low_pressure_threshold or self._high_pressure_threshold < psi_pressure_value:
            self._is_alarm_on = True

    @property
    def is_alarm_on(self):
        return self._is_alarm_on

#test_tire_pressure_monitoring.py
import unittest
from unittest.mock import patch, MagicMock, Mock

from tire_pressure_monitoring import Alarm
from sensor import Sensor

class AlarmTest(unittest.TestCase):

    def test_check_with_too_high_pressure(self):
        with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
            test_sensor_class.instance.sample_pressure.return_value=22
            alarm = Alarm(sensor=test_sensor_class.instance)
            alarm.check()
            self.assertTrue(alarm.is_alarm_on)

我想做的,但似乎找不到实现的方法,就是用存根替换传感器实例,而不将anthing传递给警报构造函数。在我看来,这段代码应该可以工作,但不能:

    def test_check_with_too_high_pressure(self):
    with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
        test_sensor_class.instance.sample_pressure.return_value=22
        alarm = Alarm()
        alarm.check()
        self.assertTrue(alarm.is_alarm_on)

Alarm实例获取MagicMock的实例,但“sample_pressure”方法不返回22。基本上,我想知道是否有一种方法可以使用unittest.mock来测试报警类,而不需要一个以传感器实例为参数的构造函数。


Tags: testimportselfisondefchecksensor
1条回答
网友
1楼 · 发布于 2024-09-30 01:37:03

当您调用test_sensor_class.instance时,您使用test_sensor_class作为属性持有者,添加一个模拟属性instance,并在其中添加一个模拟属性sample_pressure。你的补丁根本不用,你的代码实际上相当于:

def test_check_with_too_high_pressure(self):
    instance = MagicMock()
    instance.sample_pressure.return_value=22
    alarm = Alarm(sensor=instance)
    alarm.check()
    self.assertTrue(alarm.is_alarm_on)

您要做的是修补对Sensor()的调用。

使用代码,只需将模拟类test_sensor_class的返回值设置为预设的Sensor

def test_check_with_too_high_pressure(self):
    with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
        mockSensor = MagicMock()
        mockSensor.sample_pressure.return_value = 22
        test_sensor_class.return_value = mockSensor
        alarm = Alarm()
        alarm.check()
        self.assertTrue(alarm.is_alarm_on)

相关问题 更多 >

    热门问题