Open In App

Run Tests in Parallel with Python

Last Updated : 05 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

PyTest is a popular testing framework for Python that simplifies the process of writing and executing tests. It is easy to set up and provides powerful features like fixtures, parameterized testing, and more.

Here are the Steps to Run Tests with PyTest

Step 1: Installation

Use the following command to install PyTest on your local system.

pip3 install pytest

file

Step 2: Write Program Code.

To use pytest, we require a Python program to be tested. Let's create a basic python program with addition function for the same. Refer the following python code stored in my_math.py file.

my_math.py

Python
# my_math.py
def add(a, b):
    return a + b

Step 3: Write Test File Code.

Now we are ready to test this python function using pytest. Let's create a new test file called test.py and import my_math.py file into it. We will write 5 different tests to test this python function.

test.py

Python
from my_math import add

def test_add_positive_numbers():
    result = add(2, 3)
    assert result == 5

def test_add_negative_numbers():
    result = add(-2, -3)
    assert result == -5

def test_add_mixed_numbers_1():
    result = add(2, -3)
    assert result == -1

def test_add_mixed_numbers_2():
    result = add(-2, 3)
    assert result == 1    

def test_add_zero():
    result = add(0, 0)
    assert result == 0 

Step 4: Run Tests

With this, we are good to run the pytest for our python code. Use the following command to test code using pytest.

pytest test.py

Output:

file

Refer the above screenshot to check the output of the above command. As can be seen in the output, everything has run successfully and the tests have passed.

Steps to Run Pytest Tests in Parallel

After we running the simple pytest we try to learn Pytest Tests in Parallel:

Step 1: Installation

Here, pytest-xdist does parallelism while pytest-parallel does parallelism and concurrency. To install the pytest-xdist library use the following command.

pip3 install pytest-xdist

file

Step 2: Write Program Code.

To use pytest, we require a python program to be tested. Let's create a basic python program with addition function for the same. Refer the following python code stored in my_math.py file.

my_math.py

Python
def add(a, b):
    return a + b

Step 3: Write Test File

As can be seen in the previous output, it is very difficult to analyse time taken to run the tests on a small scale code. To make it easier, let's add a sleep time of 5 seconds in each test to understand and analyse the total time taken to run 6 tests.

test.py

Python
from my_math import add
import time

def test_add_positive_numbers():
    result = add(2, 3)
    time.sleep(5)
    assert result == 5

def test_add_negative_numbers():
    result = add(-2, -3)
    time.sleep(5)
    assert result == -5

def test_add_mixed_numbers_1():
    result = add(2, -3)
    time.sleep(5)
    assert result == -1

def test_add_mixed_numbers_2():
    result = add(-2, 3)
    time.sleep(5)
    assert result == 1    

def test_add_zero():
    result = add(0, 0)
    time.sleep(5)
    assert result == 0

Step 4: Run Tests

Run the tests again using pytest command to find out the total time taken by library to run 5 tests.Refer the screenshot below, it takes around 30 seconds to fininsh the testing when run in a synchronised manner. Now, let's use parallelisation in order to run the tests. Use the following command to tun tests in parallel.

pytest test.py -n <number of workers>

where <number of workers> is the number to be provided at run time to specify the number of threads which will run in parallel to execute testing.

file

Check the above output for the same code when run for 5 threads and 10 threads respectively. The time difference between the execution of tests when run parallelly can be visibly seen through the output.

Running Selenium Tests with PyTest

Install additional dependencies for Selenium and WebDriver Manager:

pip3 install selenium webdriver-manager pytest pytest-xdist

Step 2: Write Selenium Test File

Create a test file named test_selenium.py with the provided Selenium code to test login functionality on https://www.saucedemo.com/ for both Chrome and Firefox.

temp.py:

Python
import time
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager

# Initialize the WebDriver based on the browser parameter
def initialize_driver(browser):
    driver = None
    if browser.lower() == "chrome":
        options = ChromeOptions()
        options.add_argument("--start-maximized")
        # options.add_argument("--headless")  # Optional
        service = ChromeService(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=options)
    elif browser.lower() == "firefox":
        options = FirefoxOptions()
        # options.add_argument("--headless")  # Optional
        service = FirefoxService(GeckoDriverManager().install())
        driver = webdriver.Firefox(service=service, options=options)
    else:
        raise ValueError(f"Unsupported browser: {browser}")

    driver.maximize_window()
    return driver

# Perform the login test on the SauceDemo page
def login(driver):
    driver.get("https://www.saucedemo.com/")

    # Validate page title
    assert "Swag Labs" in driver.title, f"Page title does not contain 'Swag Labs' on {driver.capabilities['browserName']}"

    # Perform login
    username_field = driver.find_element(By.ID, "user-name")
    password_field = driver.find_element(By.ID, "password")
    login_button = driver.find_element(By.ID, "login-button")

    username_field.send_keys("standard_user")
    password_field.send_keys("secret_sauce")
    login_button.click()

    time.sleep(2)  # Simple wait; for real use, prefer WebDriverWait

    # Validate successful login by checking for inventory list
    inventory_container = driver.find_element(By.CLASS_NAME, "inventory_list")
    assert inventory_container.is_displayed(), "Login failed: Inventory list not displayed"

    # Validate URL after login
    assert "inventory.html" in driver.current_url, "URL does not indicate successful login"

    print(f"Test passed on {driver.capabilities['browserName']}: Login functionality works.")

# Parametrize the test to run on Chrome and Firefox
@pytest.mark.parametrize("browser", ["chrome", "firefox"])
def test_login_functionality(browser):
    driver = None
    try:
        driver = initialize_driver(browser)
        login(driver)
    except Exception as e:
        print(f"Test failed on {browser}: {e}")
        pytest.fail(f"Test failed on {browser}: {e}")
    finally:
        if driver:
            driver.quit()

Step 3: Run Selenium Tests

Run the Selenium tests using:

python -m pytest temp.py -s

This will show two tests (one for Chrome, one for Firefox) executing sequentially, with each test validating the login functionality.

Output:

output-of-Selenium-python-Test
Output of Selenium python Test -

By integrating pytest-xdist, you can significantly improve testing efficiency by running tests in parallel, which speeds up the execution time. After installing necessary dependencies and writing your test cases, PyTest makes it easy to execute tests both sequentially and in parallel. With Selenium with PyTest, you can automate browser-based testing for web applications, improving both testing speed and coverage.








Similar Reads