What is PyTest?

Introduction

As Selenium automation projects grow, managing test scripts using plain Python files becomes difficult. You need a better way to organize tests, execute multiple test cases, generate reports, and maintain your automation framework.

PyTest is one of the most popular testing frameworks for Python. It provides a simple and powerful way to write, organize, and execute automated tests. With features like automatic test discovery, assertions, fixtures, parameterization, and plugins, PyTest has become the preferred framework for Selenium automation projects.

In this tutorial, you’ll learn what PyTest is, why it is widely used with Selenium, how it works, and how to write your first Selenium test using PyTest.


What is PyTest?

PyTest is a free and open-source Python testing framework used to create, organize, and execute automated test cases.

Unlike a normal Python program, PyTest automatically finds and executes test functions without requiring a main() function.

A function whose name starts with test_ is automatically recognized as a test case by PyTest.

Example

Write Test Function

        │

        ▼

PyTest Discovers Test

        │

        ▼

Executes the Test

        │

        ▼

Displays Pass / Fail Result

Why Use PyTest with Selenium?

PyTest helps you:

  • Automatically discover test cases.

  • Execute multiple tests with a single command.

  • Write clean and readable test scripts.

  • Verify results using simple assert statements.

  • Generate detailed test reports.

  • Organize large automation projects.

  • Integrate easily with CI/CD pipelines.


How PyTest Works

PyTest automatically searches for:

  • Python files whose names begin with test_ or end with _test.py

  • Functions whose names begin with test_

Every discovered function is treated as an individual test case.

Example:

def test_login():
    assert True

Run all test cases using:

pytest

Or execute a specific file:

pytest test_login.py

Example

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


# Topic: 38. Introduction to PyTest - What is PyTest?
# Practice site: https://www.testmuai.com/selenium-playground/simple-form-demo
# Run: pytest -s 38_examples/test_01_what_is_pytest.py
#
# PyTest is a Python testing framework. Functions named test_* are discovered
# automatically and can assert Selenium behavior.


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

    try:
        driver.get("https://www.testmuai.com/selenium-playground/simple-form-demo")

        message_input = driver.find_element(By.ID, "user-message")
        message_input.send_keys("Hello PyTest")
        driver.find_element(By.ID, "showInput").click()

        displayed = driver.find_element(By.ID, "message").text
        assert displayed == "Hello PyTest"
    finally:
        driver.quit()

Understanding the Code

Import Required Libraries

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

These modules are required to:

  • Launch the Chrome browser.

  • Locate web elements on the webpage.


Create a Test Function

def test_what_is_pytest():

PyTest automatically discovers functions whose names start with test_.

Since this function follows the naming convention, PyTest treats it as a test case and executes it automatically.


Create a Chrome Browser Instance

driver = webdriver.Chrome()

Launches a new Chrome browser session.

Selenium Manager automatically downloads and manages the appropriate ChromeDriver in Selenium 4.6 and later.


Open the Practice Website

driver.get(
    "https://www.testmuai.com/selenium-playground/simple-form-demo"
)

Opens the Simple Form Demo page.


Locate the Input Field

message_input = driver.find_element(
    By.ID,
    "user-message"
)

Locates the text input field using its ID.


Enter Text

message_input.send_keys(
    "Hello PyTest"
)

The send_keys() method enters the text Hello PyTest into the input field.


Click the Show Message Button

driver.find_element(
    By.ID,
    "showInput"
).click()

Locates and clicks the Show Message button.

The webpage displays the entered text below the button.


Read the Displayed Message

displayed = driver.find_element(
    By.ID,
    "message"
).text

Retrieves the message displayed on the webpage.


Verify the Result

assert displayed == "Hello PyTest"

The assert statement checks whether the displayed message matches the expected value.

If both values are equal, the test passes.

Otherwise, PyTest marks the test as failed.


Close the Browser

driver.quit()

Closes all browser windows and ends the WebDriver session.

Always close the browser after test execution.


Practical Example

Suppose you’re testing a login page.

The automation script:

  • Opens the login page.

  • Enters valid credentials.

  • Clicks the Login button.

  • Uses assert to verify that the user is redirected to the dashboard.


Automation Testing Example

Consider an online shopping application.

The automation script:

  • Searches for a product.

  • Adds the product to the shopping cart.

  • Opens the cart page.

  • Uses assert to verify that the selected product appears in the cart.

PyTest reports whether the test passed or failed.


Real-World Example

PyTest is widely used in:

  • Selenium automation frameworks

  • Web application testing

  • API testing

  • Regression testing

  • Data-driven testing

  • Continuous Integration (CI/CD)

  • Enterprise automation projects

Many organizations use PyTest because it is lightweight, easy to learn, and highly scalable.


Advantages of PyTest

  • Simple and beginner-friendly.

  • Automatic test discovery.

  • Powerful assert statements.

  • Easy integration with Selenium.

  • Supports fixtures and parameterization.

  • Generates detailed test reports.

  • Suitable for small as well as enterprise-level automation projects.


Common Mistakes Beginners Make

Not Following the Naming Convention

PyTest only discovers files and functions that follow its naming convention.

Always name test functions beginning with test_.


Forgetting to Use Assertions

Without an assert statement, PyTest cannot determine whether the test passed or failed.

Always verify the expected outcome.


Writing Multiple Test Scenarios in One Function

Keep each test function focused on a single scenario.

This makes the test suite easier to understand and maintain.


Forgetting to Close the Browser

Always call driver.quit() after test execution to properly close the browser and release system resources.


Best Practices

  • Follow PyTest naming conventions for files and test functions.

  • Keep one test scenario per test function.

  • Write meaningful assert statements.

  • Keep tests independent of one another.

  • Always close the browser using driver.quit().

  • Organize test files into logical folders as your project grows.


Conclusion

PyTest is a powerful and easy-to-use testing framework that simplifies Selenium automation with Python. Its automatic test discovery, simple syntax, and built-in assertion support make it an excellent choice for creating reliable and maintainable automation frameworks. Learning PyTest is an important step toward building professional Selenium automation projects.


Frequently Asked Questions (FAQs)

What is PyTest?

PyTest is an open-source Python testing framework used to write, organize, and execute automated test cases.


Why is PyTest commonly used with Selenium?

PyTest provides automatic test discovery, powerful assertions, reporting, and excellent support for organizing Selenium automation projects.


How does PyTest identify test functions?

PyTest automatically executes functions whose names begin with test_.


Which command runs all PyTest test cases?

Use:

pytest

Can PyTest be used without Selenium?

Yes.

PyTest is a general-purpose Python testing framework that can be used for unit testing, API testing, database testing, and many other types of automated testing.


Key Takeaways

  • PyTest is one of the most popular Python testing frameworks.

  • Test functions should begin with test_ for automatic discovery.

  • Use assert statements to validate expected results.

  • PyTest automatically discovers and executes test cases.

  • PyTest integrates seamlessly with Selenium automation.

  • Learning PyTest is an essential skill for building professional Selenium automation frameworks.