import time
import pytest
def test_one():
time.sleep(2)
assert True
def test_two():
time.sleep(2)
assert True
def test_three():
time.sleep(2)
assert True
if __name__ == '__main__':
import subprocess
import sys
import time
print('Running tests sequentially...')
start_seq = time.time()
subprocess.run([sys.executable, '-m', 'pytest', '-q', '--tb=line', '--disable-warnings'], check=True)
end_seq = time.time()
seq_duration = end_seq - start_seq
print(f'Sequential run duration: {seq_duration:.2f} seconds')
print('Running tests in parallel with 3 workers...')
start_par = time.time()
subprocess.run([sys.executable, '-m', 'pytest', '-q', '--tb=line', '--disable-warnings', '-n', '3'], check=True)
end_par = time.time()
par_duration = end_par - start_par
print(f'Parallel run duration: {par_duration:.2f} seconds')
assert par_duration < seq_duration, 'Parallel run should be faster than sequential run'
This script defines three simple test functions that each wait for 2 seconds and then pass.
When run sequentially, the total time should be about 6 seconds (3 tests × 2 seconds each).
When run in parallel with 3 workers using pytest-xdist, the tests run at the same time, so total time should be about 2 seconds.
The script runs pytest twice: once sequentially and once in parallel, measuring the time taken for each.
Finally, it asserts that the parallel run is faster than the sequential run, demonstrating how parallel tests reduce total execution time.