Run pytest tests in parallel on CI pipeline
Preconditions (3)
✅ Expected Result: Tests run in parallel on 4 workers, all tests pass, and CI shows a successful test report
Jump into concepts and practice - no test required
import pytest # Sample test file: test_sample.py def test_one(): assert 1 + 1 == 2 def test_two(): assert 'hello'.upper() == 'HELLO' def test_three(): assert len([1, 2, 3]) == 3 # To run in CI, use the command: # pytest -n 4 --dist=loadscope # This requires pytest-xdist installed: # pip install pytest-xdist # In CI pipeline script (example): # python -m pip install -r requirements.txt # pytest -n 4 --dist=loadscope
The code defines simple pytest tests to demonstrate parallel execution.
We use the -n 4 option with pytest to run tests on 4 parallel workers.
The --dist=loadscope option helps distribute tests by scope to avoid conflicts.
In the CI pipeline, dependencies including pytest and pytest-xdist must be installed before running tests.
This setup reduces total test time by running tests concurrently.
Now add data-driven testing with 3 different inputs and run them in parallel in CI
-n followed by the number of workers.pytest -n 4.pytest -n 3 tests/, what is the expected behavior?-n 3 option tells pytest-xdist to use 3 parallel workers.pytest -n 4 in your CI but tests still run sequentially. What is the most likely cause?-n parallel execution.-n and runs tests sequentially.-n auto.--dist loadscope option balances tests to avoid overloading any worker.