python - 在使用 pytest 运行测试之前执行健全性检查

标签 python testing pytest

当我使用 pytest 运行测试时,我想执行一些健全性检查。通常,我想检查测试是否可以访问某些可执行文件,以及用户在命令行上提供的选项是否有效。

我发现的最接近的方法是使用固定装置,例如:

@pytest.fixture(scope="session", autouse=True)
def sanity_check(request):
  if not good:
     sys.exit(0)

但这仍然运行所有测试。我希望脚本在尝试运行测试之前失败。

最佳答案

您不需要显式验证命令行选项;这将由 arg 解析器完成,如有必要,它将提前中止执行。至于条件检查,您离解决方案已经不远了。使用

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/

相关文章:

python - 如何向 json 字典添加键值列表

python - 如何将数据帧字典条目拆分/分解为多行

python - 如何在 if 语句中使用两个条件

forms - 如何在 Laravel 5 中测试表单请求规则?

android - Espresso AccessibilityChecks测试已弃用

python - 了解 python 引用计数以调试 c 扩展

Python:typing.cast 与内置类型转换

ruby-on-rails - 运行 Rspec 时出现 "No such file to load"错误

python - py.test : Get expected values for test functions for different fixtures from configuration

pytest - 更改 xml 报告中的 pytest 测试套件名称