unittest Mock - 补丁返回值

时间:2015-04-13 23:17:52

标签: python unit-testing python-3.4 python-unittest

我想我误解了如何使用模拟更改函数返回值。这是我的测试:

from path.to import programme_finder
@patch('path.to.programme_finder._calc_update_interval')
def test_refresh_interval(self,method_mock):
    today = datetime.datetime.now()
    dd = datetime.timedelta(millisecond=20)
    earlier_date = today - dd
    #The normal function returns a 5 day interval.
    # For tests I want it down to 20ms
    method_mock.return_value = earlier_date
    #Here I would expect a date object, instead I get MagicMock
    print("Calc returns %s " % programme_finder._calc_update_interval)
    # rest of the test irrelevant 
    self.fail("need to time responce time")

我做错了什么?如何让programme_finder._calc_update_interval返回已修补的datetime

尝试

assert programme_finder._calc_update_interval == earlier_date

同样也失败了。

#programme_finder.py
def _calc_update_interval():
    today = datetime.datetime.now()
    # The days we want to subtract for today.
    update_interval = current_app.config.get("RESOURCE_UPDATE_INTERVAL")
    dd = datetime.timedelta(days=update_interval)
    # Find which date it was x days ago 
    earlier_date = today - dd
    return earlier_date

2 个答案:

答案 0 :(得分:4)

在我看来,你并没有调用该函数 - 你按名称引用它,所以你得到了模拟函数而不是你的模拟返回值。

print("Calc returns %s " % programme_finder._calc_update_interval )
                                                                 ^reference

应该是

print("Calc returns %s " % programme_finder._calc_update_interval() )
                                                                 ^^call

答案 1 :(得分:0)

问题似乎是_calc_update_interval是一个属性(我猜是用@property装饰器创建的)而不是方法。最简单的方法是简单地使用mock提供的PropertyMock类(记录here):

@patch('path.to.programme_finder._calc_update_interval', new_callable=PropertyMock):
def test_refresh_interval(self,method_mock):
    #...