在 pytest 中断言 UserWarning 和 SystemExit
在我的应用程序中,我有一个函数,当提供错误的参数值时,它将从模块引发一个UserWarnings然后warnings从SystemExit模块引发sys。
代码类似于:
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我可以SystemExit在 pytest 中进行检查。
with pytest.raises(SystemExit):
compare_tags(....)
但这也会显示警告消息(这不是错误)。
如果我想检查警告:
pytest.warns(UserWarning,
compare_tags(...)
这会产生一个SystemExit错误,因为这个被调用的函数会触发系统退出。
我怎样才能把warnings和SystemExit检查都放在同一个pytest中?