How to Use -x Flag in pytest for Early Test Exit
Use the
-x flag with pytest to stop running tests immediately after the first failure or error occurs. This helps quickly identify issues without running the entire test suite.Syntax
The basic syntax to use the -x flag in pytest is:
pytest -x [options] [test_paths]
Here:
pytestruns the test runner.-xtells pytest to stop after the first failure or error.[options]are other optional pytest flags.[test_paths]specify files or directories to test.
bash
pytest -x
Example
This example shows a test file with three tests. The -x flag stops pytest after the first failure.
python
import pytest def test_pass(): assert 1 == 1 def test_fail(): assert 1 == 2 def test_never_run(): assert 3 == 3
Output
============================= test session starts =============================
collected 3 items
test_example.py .F
=========================== short test summary info ===========================
FAILED test_example.py::test_fail - assert 1 == 2
========================= 1 failed, 1 passed in 0.03s =========================
Common Pitfalls
Some common mistakes when using -x include:
- Expecting all tests to run:
-xstops at first failure, so later tests won't run. - Using
-xwith flaky tests can hide other issues. - Confusing
-xwith--maxfailwhich allows stopping after multiple failures.
To run all tests regardless of failures, do not use -x.
bash
pytest # runs all tests even if some fail pytest -x # stops after first failure pytest --maxfail=3 # stops after 3 failures
Quick Reference
| Flag | Description |
|---|---|
| -x | Stop test run after first failure or error |
| --maxfail=N | Stop after N failures |
| -v | Verbose output |
| -q | Quiet output |
Key Takeaways
Use
-x to stop pytest immediately after the first test failure or error.This flag helps save time by not running all tests when an early failure occurs.
Do not use
-x if you want to see all test results in one run.For stopping after multiple failures, use
--maxfail=N instead.Remember that
-x can hide other failing tests after the first failure.