pytestmock self方法

2024-05-03 18:38:39 发布

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

我试图用pytest mock来模拟self方法。你知道吗

简单地说,我的类得到了一个我想模拟的函数“distance”。你知道吗

我想测试我的eq函数,它是这样的:

def __eq__(self, other):
        return self.distance() == other.distance()

我试着这样做:

def test_eq(mocker):
    i = mocker.MagicMock(Interval)
    mocker.patch.object(i, 'distance', return_value=1)
    i2 = mocker.MagicMock(Interval)
    mocker.patch.object(i2, 'distance', return_value=1)

    assert i == i2

但是这个回报:

AssertionError: assert <\MagicMock spec='Interval' id='140333310434384'> ==<\MagicMock spec='Interval' id='140333310558104'>

我也试过了

mocker.patch.object(i, 'self.distance', return_value=1)

但这给了我一个属性错误,正如我从MagicMock期望的那样。你知道吗

修补对象自身方法的正确方法是什么?你知道吗


Tags: 方法函数selfreturnobjectvaluedefpatch