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?
Running pytest We can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .
Learn Pytest From Scratch By default, pytest runs tests in sequential order. In a real scenario, a test suite will have a number of test files and each file will have a bunch of tests. This will lead to a large execution time. To overcome this, pytest provides us with an option to run tests in parallel.
Run Multiple Tests From a Specific File and Multiple Files To run all the tests from all the files in the folder and subfolders we need to just run the pytest command. This will run all the filenames starting with test_ and the filenames ending with _test in that folder and subfolders under that folder.
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.
There's also another way documented in the manual: https://docs.pytest.org/en/latest/example/simple.html#pytest-current-test-environment-variable
Pytest will set the following environment variable PYTEST_CURRENT_TEST
.
Checking the existence of said variable should reliably allow one to detect if code is being executed from within the umbrella of pytest.
import os if "PYTEST_CURRENT_TEST" in os.environ: # We are running under pytest, act accordingly...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With