Verify the error code or message from SystemExit in pytest(在pytest中验证来自SystemExit的错误代码或消息)
本文介绍了在pytest中验证来自SystemExit的错误代码或消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据pytest文档,我可以断言发生了SystemExit(),但我想做更多的事情:我还想验证退出代码和任何消息。我尝试了下面的代码,但没有打印任何内容,并且我不确定需要断言什么才能证明我获得了正确的错误代码。
with pytest.raises(SystemExit):
docopt_args = validate_args(docopt_args)
out, err = pytest.capsys.readouterr()
assert out == 'Foo'
print out, err
当我运行我的测试时,它通过了,但仅此而已。没有打印任何内容,并且我没有收到断言错误。
我希望执行的代码是:
print '
' + docopt_args['-d'] + ' is not a valid date
'
sys.exit(-3)
推荐答案
此功能适用于最新的pytest:
您只需使用--capture=sys
选项运行pytest
,并依赖于raises()
上下文之外的断言(此位出于某种原因很重要!)
示例:
#!/usr/bin/env python
from __future__ import print_function
import pytest
def f(code=0):
print("Foo")
raise SystemExit(code)
def test_f(capsys):
with pytest.raises(SystemExit):
f()
out, err = capsys.readouterr()
assert out == "Foo
"
print(out, err)
演示:
$ py.test -v --capture=sys test_foo.py
======================================= test session starts ========================================
platform linux2 -- Python 2.7.9 -- py-1.4.27 -- pytest-2.7.0 -- /home/prologic/.virtualenvs/test/bin/python
rootdir: /home/prologic/tmp, inifile:
collected 1 items
test_foo.py::test_f PASSED
===================================== 1 passed in 0.00 seconds =====================================
将print("Foo")
更改为print("Bar")
会导致:
$ py.test -v --capture=sys test_foo.py
======================================= test session starts ========================================
platform linux2 -- Python 2.7.9 -- py-1.4.27 -- pytest-2.7.0 -- /home/prologic/.virtualenvs/test/bin/python
rootdir: /home/prologic/tmp, inifile:
collected 1 items
test_foo.py::test_f FAILED
============================================= FAILURES =============================================
______________________________________________ test_f ______________________________________________
capsys = <_pytest.capture.CaptureFixture instance at 0x7f2729405518>
def test_f(capsys):
with pytest.raises(SystemExit):
f()
out, err = capsys.readouterr()
> assert out == "Foo
"
E assert 'Bar
' == 'Foo
'
E - Bar
E + Foo
test_foo.py:17: AssertionError
===================================== 1 failed in 0.01 seconds =====================================
我想这正是你想要的!
我在干净的virtualenv中完成了此操作:
mkvirtualenv test
pip install pytest
这里的诀窍是阅读和理解Setting capturing methods or disabling capturing
这篇关于在pytest中验证来自SystemExit的错误代码或消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在pytest中验证来自SystemExit的错误代码或消息


猜你喜欢
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 沿轴计算直方图 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12