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

Laizer picture Laizer · Aug 7, 2014 · Viewed 11.6k times · Source

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?

Answer

ramnes picture ramnes · Jun 16, 2017

A simpler solution I came to:

import sys

if "pytest" in sys.modules:
    ...

Pytest runner will always load the pytest module, making it available in sys.modules.

Of course, this solution only works if the code you're trying to test does not use pytest itself.