Below is a sample code demonstrating how Pytest-xdist can be used to run tests concurrently on multiple CPU cores, which can significantly reduce test execution time for large test suites.
To run the tests in parallel using Pytest-xdist, you can specify the number of CPUs to use with the -n
option. For example, to run tests on 2 CPUs in parallel, you can run:
Pytest-xdist will execute the test cases concurrently, utilizing the available CPU cores efficiently.
# pip install pytest pytest-xdist | |
# tests/test_parallel_execution.py | |
# In this code, we have three test functions representing tasks that can run concurrently. | |
import pytest | |
import time | |
def test_task_1(): | |
"""Simulate task 1 that takes some time to complete.""" | |
time.sleep(1) # Simulate a task that takes 1 second | |
assert True, "Task 1 completed successfully." | |
def test_task_2(): | |
"""Simulate task 2 that takes some time to complete.""" | |
time.sleep(1) # Simulate a task that takes 1 second | |
assert True, "Task 2 completed successfully." | |
def test_task_3(): | |
"""Simulate task 3 that takes some time to complete.""" | |
time.sleep(1) # Simulate a task that takes 1 second | |
assert True, "Task 3 completed successfully." | |
# pytest -n 2 |
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND