[英]How do you unit test functions that rely on data inputted on CLI?
我很难理解如何使用 argparse 对依赖于 CLI 输入的函数进行单元测试。 如何正确设置单元测试? 让我的代码帮助说明......
我的 arg 解析:
parser = argparse.ArgumentParser()
parser.add_argument('--date_flag', type=str, choices=['P', 'C'],
help='Helps script determine which month date to check for. Previous or current month.')
args = parser.parse_args()
我的功能:
def create_filename_to_watch() -> str:
"""
Creates a filename string to search for given which date flag ('P' or 'C') was passed.
:return: A string value that represents the file name to watch for.
"""
current_month_year = datetime.date.today().replace(day=1)
previous_month_year = current_month_year - datetime.timedelta(days=1)
if args.date_flag == 'P':
name_to_watch_for = feed_metadata[4].replace('YYYYMM', previous_month_year.strftime('%Y%m'))
else:
name_to_watch_for = feed_metadata[4].replace('YYYYMM', current_month_year.strftime('%Y%m'))
return name_to_watch_for
我的目标是使用 Python unittest 编写一个单元测试,以评估在 CLI 上同时传递“P”或“C”时返回的正确字符串。 我不明白如何从单元测试内部控制 CLI 以使函数执行正确的条件。
正如@chepner 在评论中建议的那样,您需要传入 args.date_flag 的值,并可能对 datetime 函数进行猴子修补,以提供可重复的值。
每当您使用全局值时,测试都很难编写,因为测试的范围会扩大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.