如何使 py.test 失败触发外部函数?

How to make a py.test failure trigger outside functions?

我目前正在编写一个脚本来安装我的待测软件,然后使用 py.test 自动运行我的冒烟测试。如果在这些测试中的任何一个发生故障,我想告诉我的软件不要将软件发布到构建服务器。伪代码基本上是这样的:

def install_build_and_test():
    # some python code installs some_build
    install_my_build(some_build)

    # then I want to test my build
    subprocess.Popen(["py.test", "smoke_test_suite.py"])
    # test_failures = ???

    # If any failures occurred during testing, do not publish build 
    if test_failures is True:
        print "Build will not publish because there were errors in your logs"

    if test_failures is False:
        publish_build(some_build)

我的问题是如何使用 pytest 失败告诉我的 install_and_test_build 代码不发布 some_build?

如果测试失败,

py.test 必须 return 非零退出代码。最简单的处理方法是使用 subprocess.check_call():

try:
    subprocess.check_call(["py.test", "smoke_test_suite.py"])
except subprocess.CalledProcessError:
    print "Smoke tests have failed, not publishing"
else:
    print "Smoke tests have passed, publishing"
    # ...

方法一

我认为这就是您要走的路。基本上,只需将 test.py 视为黑盒过程并使用退出代码来确定是否存在任何测试失败(例如,如果存在非零退出代码)

exit_code = subprocess.Popen(["py.test", "smoke_test_suite.py"]).wait()
test_failures = bool(exit_code)

方法 #2

另一种更简洁的方法是 run py.test in python directly

import pytest
exit_code = pytest.main("smoke_test_suite.py")
test_failures = bool(exit_code)