简体   繁体   中英

unittest Mock - patch return value

I think I misunderstand how to use mocks for changing a function return value. Here is my test :

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")

What am I doing wrong ? How do I get the programme_finder._calc_update_interval to return my patched datetime ?

Tried

assert programme_finder._calc_update_interval == earlier_date

as well and it fails.

#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

It looks to me like you're not calling the function -- you're referencing it by name, so you get back the mocked function instead of your mock return value.

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

Should be

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

The problem seems to be that _calc_update_interval is a property (I'm guessing created with the @property decorator) and not a method. The easiest approach is to simply use the PropertyMock class provided with mock (Documented here ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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