Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pytest

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?

like image 944
Laizer Avatar asked Aug 07 '14 16:08

Laizer


People also ask

How do I run a specific test case in pytest?

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 .

Does pytest run tests in parallel?

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.

How do I run multiple tests in pytest?

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.


2 Answers

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.

like image 50
ramnes Avatar answered Nov 15 '22 23:11

ramnes


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... 
like image 34
cgons Avatar answered Nov 15 '22 22:11

cgons