在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: Trying to mock datetime.date.today() but not working,但似乎你只能在测试方法中模拟一些东西
如何在datetime.datetime.today
中模拟manager.py
?
答案 0 :(得分:1)
最简单的策略之一是将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