Running tests with -n auto lets pytest run tests faster by using all your computer's CPU cores at once.
0
0
Running with -n auto in PyTest
Introduction
You have many tests and want them to finish quicker.
You want to use all your computer's power without guessing how many cores to use.
You want to speed up testing during development or before releasing software.
Syntax
PyTest
pytest -n auto
This command tells pytest to run tests in parallel using all CPU cores.
You need to have the pytest-xdist plugin installed for this to work.
Examples
Run all tests using all available CPU cores automatically.
PyTest
pytest -n auto
Run tests using exactly 4 CPU cores (manual setting).
PyTest
pytest -n 4Sample Program
This test file has two tests: one fast and one slow (2 seconds).
Running with -n auto uses two CPU cores to run tests at the same time, so total time is about 2 seconds instead of 4.
PyTest
# test_sample.py import time def test_fast(): assert 1 + 1 == 2 def test_slow(): time.sleep(2) assert True # Run command: # pytest -n auto # Expected output snippet: # ============================= test session starts ============================= # platform ... # gw0 [2] / gw1 [2] # # collected 2 items # # test_sample.py .. [100%] # # ============================== 2 passed in ~2.0s ==============================
OutputSuccess
Important Notes
Make sure pytest-xdist is installed: pip install pytest-xdist.
Not all tests benefit from parallel running, especially if they share resources.
Using -n auto is a simple way to speed up tests without manual setup.
Summary
Running with -n auto uses all CPU cores to run tests in parallel.
This speeds up test execution, especially for many or slow tests.
Requires pytest-xdist plugin installed.