Python:如何从测试文件模拟源文件中的日期



manager.py 中考虑此方法

def get_start_end_time_for(user, year, month):
    today = datetime.today()
    if today.day  < user.financial_day_of_month:
        if month == 1:
            month = 12
            year -= 1
        else:
            month -= 1
    time_from = date(day=user.financial_day_of_month,
                     month=month, year=year)
    time_to = time_from + relativedelta(months=+1)
    return time_from, time_to

test.py 中考虑以下内容

def test_get_start_end_time_for(user, year, month):
    # mock datetime.datetime.today in manager.py
    # do further steps

我看了Python:试图模拟datetime.date.today(),但不起作用,但似乎只能在测试方法中模拟一些东西

如何在manager.py中模拟datetime.datetime.today

最简单的策略之一是将datetime.today()封装在方法中。它可能看起来像这样:

def get_start_end_time_for(user, year, month):
    today = get_today()
    ...
def get_today():
    return datetime.today()

然后在test.py中,您可以通过如下方式模拟getToday()方法来模拟它:

@patch('get_today')
def test_get_start_end_time_for(user, year, month, get_today_mock):
    get_today_mock.return_value = #whatever date you want to use for your test

最新更新