![](/img/trans.png)
[英]How to make pytest return failure if a minimum number of tests is not run?
[英]how to make pytest fail on shellcommand invocation failure
对于包含以下内容的 python pytest 文件:
import os
def test_that():
print("step 1: should work")
os.system("echo hello")
print("step 2: should fail")
os.system("asdf_failing_non_existing_command")
和 pytest 的调用,例如:
pytest -s testing.py
输出是:
1 passed
我预计测试会失败。 如何从 os 系统调用中获取退出代码以影响测试失败并实际上使测试失败?
如何从 os 系统调用中获取退出代码以影响测试失败并实际上使测试失败?
不要使用os.system
。 (您几乎从不需要它,并且文档在使用subprocess
方面非常强大)。
使用子流程:
import subprocess
subprocess.run(["echo", "hi"], check=True)
subprocess.run(["asdfasdfasdfdas"], check=True)
或者您可以使用 os.system 并检查自己,但为什么要重新发明轮子呢?
您可以断言os.system()
的结果等于 0:
import os
def test_that():
print("step 1: should work")
assert os.system("echo hello") == 0
print("step 2: should fail")
assert os.system("asdf_failing_non_existing_command") == 0
输出是:
def test_that():
print("step 1: should work")
assert os.system("echo hello") == 0
print("step 2: should fail")
> assert os.system("asdf_failing_non_existing_command") == 0
E AssertionError: assert 1 == 0
E + where 1 = <built-in function system>('asdf_failing_non_existing_command')
E + where <built-in function system> = os.system
test.py:7: AssertionError
============================================================================== short test summary info ===============================================================================
FAILED test.py::test_that - AssertionError: assert 1 == 0
================================================================================= 1 failed in 0.16s ==================================================================================
使用 subprocess.getstatusoutput,如果它返回的第一个项目(返回代码)不是 0,则只引发一个异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.