Search code examples
pythonpytestpython-unittest

Prevent all python unittests from running based on environment variable


Is there a way I could prevent all unit tests from running if a certain environment variable is not set to a specific value?

For example I want tests to only run if os.getenv(DB_URL) returns sqlite:///:memory:.

I'd like to configure this globally so I don't need to review every single test class / setup function to check this individually.


Solution

  • There's many ways to accomplish this, but a fixture is probably the easiest

    import os
    import pytest
    
    DB_URL = "foo"
    
    @pytest.fixture(autouse=True, scope="session")
    def verify_db_url():
        expected_url = "sqlite:///:memory:"
        if os.getenv(DB_URL) != expected_url:
            pytest.exit("Exiting due to incorrect database environment variable.")