0

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.

Hans
  • 2,569
  • 3
  • 22
  • 39
  • 1
    probably this https://stackoverflow.com/a/66973011/12502959 – python_user May 04 '22 at 08:47
  • Not really because I would like to enforce it to be a check on all tests which is run before a setup method that may delete data eg. from a database. Manually having to confirm that the method is decorated with the checks for each test would be very annoying. – Hans May 04 '22 at 14:27
  • So you want to execute the test runner, and immediately exit? Why not just not execute the test runner? – chepner May 04 '22 at 16:02

1 Answers1

1

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.")
    
Teejay Bruno
  • 1,225
  • 1
  • 3
  • 10