简体   繁体   English

pytest-mock 模拟自我方法

[英]pytest-mock mock self method

I'm trying to mock a self method using pytest-mock.我正在尝试使用 pytest-mock 模拟 self 方法。

Simply my class got a function "distance" which I want to mock.只是我的班级得到了一个我想模拟的函数“距离”。

I want to test my eq function that is like this:我想测试我的eq函数是这样的:

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

I try something like this:我尝试这样的事情:

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

But this return:但是这个回报:

AssertionError: assert <\\MagicMock spec='Interval' id='140333310434384'> ==<\\MagicMock spec='Interval' id='140333310558104'>断言错误:断言 <\\MagicMock spec='Interval' id='140333310434384'> ==<\\MagicMock spec='Interval' id='140333310558104'>

I have also tried我也试过

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

but this get me an AttributeError as i expected from MagicMock.但这让我得到了一个 AttributeError,正如我对 MagicMock 的预期。

What is the right way to patch my object self method?修补我的对象 self 方法的正确方法是什么?

I don't think you can patch 'Interval' like this.我认为你不能像这样修补“间隔”。 Instead you should patch the constructor and manually replace the distance functions to return expected results.相反,您应该修补构造函数并手动替换距离函数以返回预期结果。

This example will only test the Interval.__eq__ method:这个例子只会测试Interval.__eq__方法:

def test_eq(mocker):
    # Mock constructor as it is already tested elsewhere
    mocker.patch.object(Interval, "__init__", return_value=None)

    i1 = Interval()
    i1.distance = lambda: 1

    i2 = Interval()
    i2.distance = lambda: 1

    assert i1 == i2

You can easily mock out the distance method like this.您可以轻松地模拟这样的距离方法。 Assuming that your Interval class is defined in the interval module for example like this:假设您的Interval类是在 interval 模块中定义的,例如像这样:

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

    def distance(self):
        raise NotImplementedError()

Then in your test you can just mock out the distance function to always return 1 like this:然后在你的测试中,你可以模拟距离函数总是像这样返回 1:

from interval import Interval

def test_eq(mocker):
    mocker.patch('interval.Interval.distance', return_value=1)

    i1 = Interval()
    i2 = Interval()

    assert i1 == i2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM