0
0
PytestHow-ToBeginner ยท 3 min read

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:

  • pytest runs the test runner.
  • -x tells 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: -x stops at first failure, so later tests won't run.
  • Using -x with flaky tests can hide other issues.
  • Confusing -x with --maxfail which 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

FlagDescription
-xStop test run after first failure or error
--maxfail=NStop after N failures
-vVerbose output
-qQuiet 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.