如果条件不满足,请在开始时立即停止pytest



如果不满足某些条件,在非常早期的阶段阻止整个pytest运行的任何方法。例如,如果发现Elasticsearch服务没有运行?

我试着把它放在一个由所有测试文件导入的通用文件中:

try:
requests.get('http://localhost:9200')
except requests.exceptions.ConnectionError:
msg = 'FATAL. Connection refused: ES does not appear to be installed as a service (localhost port 9200)' 
pytest.exit(msg)

但是,每个文件和每个文件中的每个测试都在运行测试,并且还会产生大量与错误相关的输出。

显然,我想做的是在收集阶段一开始就停止运行。

很明显,我也可以写一个脚本,在用我可能传递给它的任何CLI参数调用pytest之前检查任何必要的条件。这是实现这一点的唯一方法吗?

尝试使用pytest_configure初始化挂钩。

在您的全球conftest.py:中

import requests
import pytest
def pytest_configure(config):
try:
requests.get(f'http://localhost:9200')
except requests.exceptions.ConnectionError:
msg = 'FATAL. Connection refused: ES does not appear to be installed as a service (localhost port 9200)' 
pytest.exit(msg)

更新:

  1. 注意,pytest_configure的单个参数有要命名为config
  2. 使用pytest.exit使它看起来更好

是的,MrBeanBramen的解决方案也能工作,在conftest.py中有以下代码:

@pytest.fixture(scope='session', autouse=True)    
def check_es():
try:
requests.get(f'http://localhost:9200')
except requests.exceptions.ConnectionError:
msg = 'FATAL. Connection refused: ES does not appear to be installed as a service (localhost port 9200)' 
pytest.exit(msg)

最新更新