Sunday, 1 May 2016

Selenium Python with PyTest Framework: Complete Tutorial with Fixtures, Assertions and Test Execution


Introduction

Automation testing helps software teams verify application functionality quickly, consistently and efficiently. Selenium WebDriver is widely used for browser automation, while PyTest is a popular Python testing framework for organising and executing automated test cases.

Combining Selenium with PyTest allows testers to create structured automation scripts, reuse browser setup, validate application behaviour, execute multiple test scenarios and generate test reports.

For example, a tester can automate a login page, verify successful authentication, check invalid login behaviour and execute multiple test cases using a single test framework.

In this tutorial, we will learn how to integrate Selenium WebDriver with PyTest and develop a practical browser automation test suite.

1. What Is PyTest?

PyTest is a Python testing framework used to write and execute automated tests.

It provides several useful features:

  • Simple test case creation.

  • Automatic test discovery.

  • Fixtures for reusable setup and cleanup.

  • Assertions for validating expected results.

  • Parameterization for testing multiple data sets.

  • Markers for grouping test cases.

  • Plugin support for reports and parallel execution.

PyTest works particularly well with Selenium because it simplifies browser setup, test execution and result validation.

2. Why Combine Selenium with PyTest?

Selenium controls the browser, whereas PyTest manages the test execution process.

Selenium WebDriverPyTest
Opens and controls browsersDiscovers and executes tests
Locates web elementsOrganises test cases
Enters text and clicks buttonsProvides assertions
Handles browser interactionsProvides fixtures
Automates user workflowsSupports parameterization
Validates browser behaviour through codeProduces test execution results

Together, these technologies provide a foundation for developing maintainable Python automation frameworks.

3. Installing Selenium and PyTest

Before beginning, install Python and configure a suitable development environment such as VS Code or PyCharm.

Create a project directory:

mkdir selenium_pytest_project
cd selenium_pytest_project

Create a virtual environment:

python -m venv venv

Activate it on Windows:

venv\Scripts\activate

Activate it on macOS or Linux:

source venv/bin/activate

Install Selenium and PyTest:

python -m pip install selenium pytest

For HTML test reports, install an additional plugin:

python -m pip install pytest-html

Selenium Manager can automatically manage compatible browser drivers in many current Selenium installations, reducing the need for manual driver downloads.

4. Creating Your First Selenium PyTest Test Case

PyTest automatically discovers files named test_*.py or *_test.py and functions whose names begin with test_.

Create a file called test_browser.py.

from selenium import webdriver
from selenium.webdriver.common.by import By

def test_homepage_title():
    driver = webdriver.Chrome()

    try:
        driver.get("https://example.com")

        assert driver.title != ""

    finally:
        driver.quit()

Execute the test:

pytest -v

The -v option displays detailed test execution information.

This example opens a browser, navigates to a website and verifies that its title is not empty.

5. Understanding PyTest Fixtures

Fixtures are one of the most useful features of PyTest.

They provide reusable setup and cleanup operations. In Selenium automation, fixtures can initialise a browser before a test and close it after the test completes.

Example:

import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    browser = webdriver.Chrome()

    yield browser

    browser.quit()

The yield statement separates the setup and teardown portions of the fixture.

A test can use this fixture as follows:

def test_homepage(driver):
    driver.get("https://example.com")

    assert "Example" in driver.title

PyTest automatically supplies the fixture to the test function.

Common fixture scopes

ScopeDescription
functionRuns separately for each test function
classShared across tests in a class
moduleShared across a test module
packageShared within a package
sessionShared for the entire test session

For browser automation, function scope is a useful default because each test receives an independent browser session. Other scopes can be used when their lifecycle and isolation requirements are understood.

6. Writing Assertions in Selenium PyTest

Assertions verify whether an actual result matches the expected result.

Consider a test that checks a website title:

def test_title(driver):
    driver.get("https://example.com")

    expected_title = "Example Domain"

    assert driver.title == expected_title

If the condition is true, the test passes. If it is false, PyTest reports a failure.

Other assertion examples:

assert driver.current_url.startswith("https://")

assert "Example" in driver.title

assert len(driver.find_elements(
    By.TAG_NAME, "h1"
)) > 0

Assertions are essential for validating application behaviour rather than simply executing browser actions.

7. Parameterization: Testing Multiple Data Sets

Parameterization allows the same test function to run with different input values.

For example, a login test may need to verify several combinations of usernames and passwords.

import pytest

@pytest.mark.parametrize(
    "username,password",
    [
        ("user1", "password1"),
        ("user2", "password2"),
        ("user3", "password3")
    ]
)
def test_login_data(username, password):
    assert username != ""
    assert password != ""

This example demonstrates parameterized test execution. A real login test would enter each combination into the application and assert the expected login outcome.

Parameterization reduces code duplication and helps test positive and negative scenarios systematically.

8. Organising Selenium PyTest Test Cases

A well-structured automation project separates test cases, configuration, page objects and reusable utilities.

A sample folder structure is:

selenium_pytest_project/
│
├── tests/
│   ├── test_login.py
│   ├── test_homepage.py
│   └── test_registration.py
│
├── pages/
│   ├── login_page.py
│   └── home_page.py
│
├── utilities/
│   └── config.py
│
├── conftest.py
├── pytest.ini
└── requirements.txt

Purpose of important files:

  • tests/: Contains automated test cases.

  • pages/: Contains Page Object Model classes.

  • utilities/: Contains reusable helper functions.

  • conftest.py: Defines fixtures and shared test configuration.

  • pytest.ini: Stores PyTest configuration.

  • requirements.txt: Lists project dependencies.

This structure becomes especially useful when the number of test cases increases.

9. Using conftest.py for Shared Browser Fixtures

PyTest uses conftest.py to provide fixtures and hooks to test modules without requiring individual imports.

Create conftest.py:

import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    browser = webdriver.Chrome()
    browser.maximize_window()

    yield browser

    browser.quit()

Now test files inside the applicable directory can use the driver fixture automatically.

Example tests/test_homepage.py:

from selenium.webdriver.common.by import By

def test_homepage_heading(driver):
    driver.get("https://example.com")

    heading = driver.find_element(
        By.TAG_NAME, "h1"
    )

    assert heading.is_displayed()
    assert heading.text != ""

This avoids repeating browser initialisation code in every test.

10. Using PyTest Markers

Markers help categorise and selectively execute test cases.

For example:

import pytest

@pytest.mark.smoke
def test_login():
    assert True

@pytest.mark.regression
def test_registration():
    assert True

Register custom markers in pytest.ini:

[pytest]
markers =
    smoke: critical smoke tests
    regression: regression test cases

Execute only smoke tests:

pytest -m smoke

Execute regression tests:

pytest -m regression

Markers are useful when projects contain hundreds or thousands of test cases.

11. Generating HTML Test Reports

Reports help testers and project managers understand test execution results.

After installing pytest-html, execute:

pytest --html=reports/report.html --self-contained-html

The report can include:

  • Total tests executed.

  • Passed test cases.

  • Failed test cases.

  • Skipped test cases.

  • Execution duration.

  • Failure details.

For larger frameworks, additional reporting solutions such as Allure can also be considered.

12. Running Selenium PyTest Tests in Parallel

Parallel execution reduces the time required to execute large test suites.

The pytest-xdist plugin supports distributed test execution.

Install it:

python -m pip install pytest-xdist

Run tests using four workers:

pytest -n 4

Each worker should have its own independent WebDriver session. Avoid sharing a single browser instance between concurrently running tests.

Parallel execution also requires attention to test data, application state, ports and other shared resources.

13. Best Practices for Selenium PyTest Automation

Follow these practices when developing professional automation frameworks:

  1. Use fixtures for browser setup and teardown.

  2. Prefer explicit waits over fixed delays.

  3. Use Page Object Model to separate locators from test logic.

  4. Keep test cases independent wherever possible.

  5. Use parameterization for multiple input combinations.

  6. Organise tests using meaningful markers.

  7. Capture useful diagnostic information when tests fail.

  8. Maintain separate test data and configuration files.

  9. Avoid sharing browser sessions across parallel workers.

  10. Integrate test execution with Jenkins or GitHub Actions.

These practices improve maintainability, reliability and scalability.

14. Career Opportunities with Selenium Python and PyTest

Selenium Python with PyTest is a valuable skill combination for aspiring automation testers and software development engineers in test (SDETs).

After learning these technologies, learners can progress towards:

  • Selenium Python automation framework development.

  • Page Object Model implementation.

  • Data-driven automation.

  • API testing using Python.

  • CI/CD integration.

  • Cross-browser testing.

  • Playwright automation.

  • Advanced SDET responsibilities.

Practical projects and the ability to explain framework architecture are important during technical interviews.

Learn Selenium Python Automation Testing with Palium Skills

Palium Skills offers practical Automation Testing training for freshers, graduates, manual testers and working professionals.

The Selenium Python learning pathway can cover:

  • Python programming fundamentals.

  • Selenium WebDriver.

  • Web element handling and locators.

  • Explicit waits and dynamic elements.

  • PyTest fixtures and assertions.

  • Parameterized test execution.

  • Page Object Model.

  • Automation framework development.

  • Real-time project implementation.

  • Interview preparation.

Training is available through classroom sessions at South Kolkata and Salt Lake, Kolkata, and instructor-led live online sessions for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar, Near South City Mall, Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Frequently Asked Questions

1. What is PyTest in Selenium Python?

PyTest is a Python testing framework used to organise, execute and validate Selenium automation test cases.

2. Is PyTest better than unittest for Selenium automation?

Both are useful Python testing frameworks. PyTest offers convenient fixtures, parameterization and plugin support, making it a popular choice for Selenium automation projects.

3. What is a fixture in PyTest?

A fixture is a reusable function that provides setup and cleanup operations for test cases, such as opening and closing a browser.

4. How do I run Selenium PyTest test cases?

Use the command pytest -v from the project directory.

5. Can Selenium PyTest execute tests in parallel?

Yes. The pytest-xdist plugin supports parallel execution using commands such as pytest -n 4.

6. Can PyTest generate HTML reports?

Yes. The pytest-html plugin can generate HTML reports containing test execution results.

7. Can Selenium Python with PyTest be used for real-time projects?

Yes. It can be used for automating login, registration, e-commerce, banking, enterprise and other web application workflows.

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...