简体   繁体   English

python中的模拟函数参数

[英]mock function arguments in python

Lets say I have this function 可以说我有这个功能

from datetime import date

def get_next_friday(base_date=date.today()):
   next_friday = ...
   return next_friday

Then I have a celery task to call this function without passing in the base_date 然后我有一个芹菜任务来调用此函数,而无需传入base_date

@celery_app.task
def refresh_settlement_date():
   Record.objects.update(process_date=get_next_friday())

In the unittest I am running the refresh_settlement_date() task, but it's not providing the base_date when it's calling the get_next_friday() , my question is how to mock that parameter to test the days in the future? 在单元测试中,我正在运行refresh_settlement_date()任务,但在调用get_next_friday()时未提供base_date ,我的问题是如何模拟该参数以测试将来的日子?

I am trying to avoid adding parameter to become refresh_settlement_date(base_date) as it doesn't serve real purpose but only for unittest. 我试图避免将参数添加为refresh_settlement_date(base_date)因为它不是真正的目的,而仅用于单元测试。

An alternative approach would to be to patch the current date. 一种替代方法是修补当前日期。

There is a relevant thread with multiple options: 有一个具有多个选项的相关线程:


My favorite option is to use a third-party module called freezegun . 我最喜欢的选择是使用名为freezegun的第三方模块。

You would need only one line to add, very clean and readable: 您只需要添加一行即可,非常清晰易读:

@freeze_time("2014-10-14")
def test_refresh_settlement_date_in_the_future(self):
    ...

You need to @patch get_next_friday() function and substitute it's return value with the one you need: 您需要@patch get_next_friday()函数,并将其返回值替换为所需的返回值:

date_in_the_future = date.today() + timedelta(50)
next_friday_in_the_future = get_next_friday(base_date=date_in_the_future)

with patch('module_under_test.get_next_friday') as mocked_function:
    mocked_function.return_value = next_friday_in_the_future

    # call refresh_settlement_date

I just tried this out, it seems to work: 我只是尝试了一下,它似乎有效:

first I need to copy the function: 首先,我需要复制函数:

old_get_next_friday = get_next_friday

then patch it: 然后打补丁:

with patch.object(get_next_friday) as mocked_func:
    for i in range(8):
        mocked_func.return_value = old_get_next_friday(date.today() + timedelta(days=i))
        refresh_settlement_date()

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

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