Make pytest check only one file

less than 1 minute read

By default, Pytest checks all files matching its template. To enable testing one file at a time, particularly useful for Spyder or other IDE debugging, add at the bottom of each test_*.py file:

if __name__ == '__main__':
    pytest.main([__file__])

Then the file can be interactively debugged in Spyder or other IDE without running all the other test files too.

Pytest template

For Pytest to find and execute test scripts:

  • each function name must begin with test_ e.g. def test_my1(a, b):
  • each test file name must begin with test_ e.g. test_io.py
  • each test file should be under a subdirectory somewhere in the project named tests/

Command line

To run self-tests on a specific file tests/test_my.py from the command line:

pytest tests/test_my.py

or

python tests/test_my.py

Notes

If you already have a bunch of files with:

if __name__ == '__main__':
    pytest.main()

fix this by

sed -i 's/pytest.main()/pytest.main([__file__])/' test_*.py

Leave a comment