pytest-xdist installation - Build an Automation Script
import subprocess import sys import pytest def test_pytest_xdist_installation_and_parallel_run(): # Step 1: Install pytest-xdist install_cmd = [sys.executable, '-m', 'pip', 'install', 'pytest-xdist'] install_result = subprocess.run(install_cmd, capture_output=True, text=True) assert install_result.returncode == 0, f"Failed to install pytest-xdist: {install_result.stderr}" # Step 2: Verify pytest-xdist is listed in pytest --version version_cmd = ['pytest', '--version'] version_result = subprocess.run(version_cmd, capture_output=True, text=True) assert version_result.returncode == 0, f"pytest --version failed: {version_result.stderr}" assert 'xdist' in version_result.stdout, "pytest-xdist not found in pytest --version output" # Step 3: Run tests in parallel with 2 workers run_cmd = ['pytest', '-n', '2', '--maxfail=1', '--disable-warnings', 'test_sample.py'] run_result = subprocess.run(run_cmd, capture_output=True, text=True) assert run_result.returncode == 0, f"Parallel test run failed: {run_result.stderr}" # Step 4: Check output contains info about 2 workers assert 'gw0' in run_result.stdout and 'gw1' in run_result.stdout, "Parallel workers output missing"
This test script automates the manual test case steps.
First, it installs pytest-xdist using pip via subprocess and asserts the installation succeeded.
Next, it runs pytest --version and checks that 'xdist' appears in the output, confirming pytest-xdist is installed.
Then, it runs pytest with the -n 2 option to execute tests in parallel with 2 workers, asserting the tests pass.
Finally, it verifies the output contains worker identifiers gw0 and gw1, which pytest-xdist uses to label parallel workers.
Using subprocess allows running shell commands from Python and capturing their output for assertions.
This approach ensures the installation and parallel execution features of pytest-xdist work as expected.
Now add data-driven testing to run the parallel test execution with 1, 2, and 3 workers