pythonpytestpreconditions

Stop pytest right at the start if condition not met


Any way of stopping the entire pytest run from happening at a very early stage if some condition is not met. For example, if it is found that the Elasticsearch service is not running?

I have tried putting this in a common file which is imported by all test files:

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)

... but tests are being run for each file and each test within each file, and large amounts of error-related output is also produced.

Obviously what I am trying to do is stop the run at the very start of the collection stage.

Obviously too, I could write a script which checks any necessary conditions before calling pytest with any CLI parameters I might pass to it. Is this the only way to accomplish this?


Solution

  • Try using the pytest_configure initialization hook.

    In your global 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)
    

    Updates:

    1. Note that the single argument of pytest_configure has to be named config!
    2. Using pytest.exit makes it look nicer.