当我使用 pytest 运行测试时,我想执行一些健全性检查。通常,我想检查测试是否可以访问某些可执行文件,以及用户在命令行上提供的选项是否有效。
我发现的最接近的方法是使用固定装置,例如:
@pytest.fixture(scope="session", autouse=True)
def sanity_check(request):
if not good:
sys.exit(0)
但这仍然运行所有测试。我希望脚本在尝试运行测试之前失败。
最佳答案
您不需要显式验证命令行选项;这将由 arg 解析器完成,如有必要,它将提前中止执行。至于条件检查,您离解决方案已经不远了。使用
-
pytest.exit
立即中止 -
pytest.skip
跳过所有测试 -
pytest.xfail
使所有测试失败(尽管这是预期的失败,因此它不会将整个执行标记为失败)
fixture 示例:
@pytest.fixture(scope='session', autouse=True)
def precondition():
if not shutil.which('spam'):
# immediate shutdown
pytest.exit('Install spam before running this test suite.')
# or skip each test
# pytest.skip('Install spam before running this test suite.')
# or make it an expected failure
# pytest.xfail('Install spam before running this test suite.')
xdist
兼容性
在使用 xdist
的测试运行中调用 pytest.exit()
只会使当前工作线程崩溃,而不会中止主进程。您必须将检查移至 runteSTLoop 启动之前调用的 Hook (因此 pytest_runteSTLoop
Hook 之前的任何内容),例如:
# conftest.py
def pytest_sessionstart(session):
if not shutil.which('spam'):
# immediate shutdown
pytest.exit('Install spam before running this test suite.')
关于python - 在使用 pytest 运行测试之前执行健全性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463143/