0
0
PyTesttesting~15 mins

Running with -n auto in PyTest - Build an Automation Script

Choose your learning style9 modes available
Run pytest tests in parallel using -n auto
Preconditions (2)
Step 1: Open the terminal
Step 2: Navigate to the directory containing the test file
Step 3: Run the command: pytest -n auto
Step 4: Observe the test execution running in parallel
Step 5: Verify all tests pass successfully
✅ Expected Result: Tests run in parallel using all available CPU cores and all tests pass
Automation Requirements - pytest with pytest-xdist
Assertions Needed:
All test functions complete successfully
No test failures or errors occur
Best Practices:
Use pytest fixtures for setup and teardown
Avoid shared state between tests to prevent race conditions
Use -n auto to automatically use all CPU cores
Automated Solution
PyTest
import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]

@pytest.mark.parametrize('num', [1, 2, 3])
def test_is_positive(num):
    assert num > 0

def test_sum(sample_data):
    assert sum(sample_data) == 6

# To run these tests in parallel, execute in terminal:
# pytest -n auto

This code defines simple pytest tests that can run independently.

The test_is_positive function checks numbers are positive.

The test_sum function checks the sum of a list.

Using pytest -n auto runs these tests in parallel using all CPU cores.

Fixtures and parameterization ensure tests are isolated and suitable for parallel execution.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not installing pytest-xdist before using -n auto', 'why_bad': 'The -n option requires pytest-xdist plugin; without it, the command fails.', 'correct_approach': "Install pytest-xdist using 'pip install pytest-xdist' before running tests with -n."}
Sharing mutable global state between tests
{'mistake': 'Using print statements to debug without capturing output', 'why_bad': 'Parallel output can mix and become unreadable.', 'correct_approach': "Use pytest's capsys fixture or logging for better output management."}
Bonus Challenge

Now add data-driven testing with 3 different inputs and run them in parallel using -n auto

Show Hint