【发布时间】:2019-09-28 03:02:11
【问题描述】:
在 pytest 中断言 UserWarning 和 SystemExit
在我的应用程序中,我有一个函数,当提供错误的参数值时,它将从warnings 模块引发UserWarnings,然后从sys 模块引发SystemExit。
代码类似于:
def compare_tags(.....):
requested_tags = user_requested_tags # as list
all_tags = tags_calculated_from_input_file # as list
non_matching_key = [x for x in requested_tags if x not in all_tags]
# if user requested non existing tag then raise warning and then exit
if len(non_matching_key) > 0:
# generate warning
warnings.warn("The requested '%s' keys from '%s' is not present in the input file. Please makes sure the input file has the metadata of interest or remove the non matching keys." %(non_matching_key, given_tags))
# raise system exit
sys.exit(0)
为上述函数编写 pytest
我想立即在 pytest 中测试这个 UserWarning 和 SystemExit。我可以在pytest中检查SystemExit。
with pytest.raises(SystemExit):
compare_tags(....)
但这也会显示警告消息(这不是错误)。
如果我想检查警告:
pytest.warns(UserWarning,
compare_tags(...)
这会产生一个SystemExit 错误,因为这个被调用的函数会触发系统退出。
如何将warnings 和SystemExit 检查放在同一个pytest 中?
【问题讨论】:
标签: python unit-testing pytest systemexit user-warning