pythonpytest

Test if code is executed from within a py.test session


I'd like to connect to a different database if my code is running under py.test. Is there a function to call or an environment variable that I can test that will tell me if I'm running under a py.test session? What's the best way to handle this?


Solution

  • A solution came from RTFM, although not in an obvious place. The manual also had an error in code, corrected below.

    Detect if running from within a pytest run

    Usually it is a bad idea to make application code behave differently if called from a test. But if you absolutely must find out if your application code is running from a test you can do something like this:

    # content of conftest.py
    def pytest_configure(config):
        import sys
        sys._called_from_test = True
    
    def pytest_unconfigure(config):
        import sys  # This was missing from the manual
        del sys._called_from_test
    

    and then check for the sys._called_from_test flag:

    if hasattr(sys, '_called_from_test'):
        # called from within a test run
    else:
        # called "normally"
    

    accordingly in your application. It’s also a good idea to use your own application module rather than sys for handling flag.