Rerun failed tests in Pytest

Pytest provides two command line options to rerun failures from the last pytest invocation:

  • --lf--last-failed – to only re-run the failures.
  • --ff--failed-first – to run the failures first and then the rest of the tests.

However, you should clean the pytest cache to remove all cross-session cache contents if any before running the tests. Otherwise, Pytest may collect wrong number of last failed tests.

There are two options to clear the cache.

  1. You can instruct pytest to clear all cache files and values by adding the --cache-clear option like this:
pytest --cache-clear

Note that this command takes some times to completed.

This is recommended for invocations from Continuous Integration servers where isolation and correctness is more important than speed.

2. If you are running the tests on local, simply delete the .pytest_cache directory in the project root (or .cache for older versions of pytest). 

I usually use this option because it’s faster.

After cleaned the cache and running your tests, you can rerun the failed tests by command:

pytest --last-failed

Reference: https://docs.pytest.org/en/latest/cache.html

Leave a comment