【发布时间】:2019-08-11 18:56:02
【问题描述】:
下面我有一个函数,它根据命令行输入返回两个日期。如何使用 mock 来制作它,以便我可以对 else 语句执行单元测试?
# time from of pull
def time_frame():
"""
checks for optional user input for start and end date of data pull
creates start and end date for query
:return: start and end date
"""
# get the dates
args, leftovers = get_the_args()
if args.start_dt is not None and args.end_dt is not None:
return args.start_dt, args.end_dt
else:
# get today
the_today_start_date, the_today_end_date = get_dates_from_today()
return the_today_start_date, the_today_end_date
我尝试过使用mock_get_the_args.return_value = mock.Mock(return_value=None), mock.Mock() 使其在单元测试的这一部分运行时get_the_args() 函数的args 输出返回None?我需要什么来更改代表args 变量的 mock.Mock() 才能正常工作?
以下是目前的单元测试:
# the time frame
@mock.patch('src.toolkit.get_dates_from_today')
@mock.patch('src.toolkit.get_the_args')
def test_time_frame(mock_get_the_args, mock_get_dates_from_today):
# set some dates
start_date = '2019-01-01'
end_date = '2019-01-01'
# mocking
mock_get_the_args.return_value = mock.Mock(), mock.Mock()
mock_get_dates_from_today.return_value = mock.Mock(), mock.Mock()
start_date, end_date = time_frame()
mock_get_the_args.assert_called_once()
mock_get_the_args.return_value = mock.Mock(return_value=None), mock.Mock()
start_date, end_date = time_frame()
mock_get_dates_from_today.assert_called_once()
【问题讨论】:
标签: python-3.x unit-testing mocking argparse python-unittest