当案例失败时,如何将 pytest.main() 的 return 代码设置为非零值?

how can I set the return code of pytest.main() to a non-zero when cases failed?

我正在尝试将退出代码添加到我的 pytest,但是 pytest 的文档只告诉了退出代码的基本描述。
如果测试成功完成,似乎 pytest.main 将 return 0,但我希望它在任何情况下失败时 return 一个非零代码,我该如何实现?
我试了几次,当我使用 ctrl+C 停止测试时它是 returns 1,而当我简单地输入“pytest”时它是 returns 2,但大多数情况下 returns 0的案例失败了。
谢谢

我的部分代码(真的很抱歉我不能展示所有代码)

#!/usr/bin/env python
# -*- coding:utf8 -*-

import sys
import pytest
import argparse
import time
from pytest import ExitCode


def main():
……
    if args.arg == "all":
        logger.debug('test all')
        ret = pytest.main(["-v", "--capture=tee-sys", "--html=./temp/report_{}.html".format(VERSION), "--self-contained-html", "-n", "auto", "--dist", "no", "e2e/cases"]+sys.argv[2:])
        return ret


if __name__ == '__main__':
    main()

那我就用tox来运行吧。

[tox]
envlist = py37

skipsdist=true
toxworkdir= {toxinidir}/var/.tox
indexserver =
    default = https://pip.nie.netease.com/simple

[testenv]

passenv = *

changedir={toxinidir}
deps =
    -r{toxinidir}/e2e/misc/requirements.txt
recreate=true
setenv =

    PYTHONDONTWRITEBYTECODE = 1
commands =
    python -m e2e all {posargs}

如有不完整,难以理解,请见谅......

您需要确保以您感兴趣的 return 值退出进程

现在你有

if __name__ == '__main__':
    main()

当 main returns 非零时,这个 return 值被丢弃

相反,使用 raise SystemExitsys.exit:

退出进程
if __name__ == '__main__':
    raise SystemExit(main())