Saturday, November 28, 2026

Pytest Complete Guide with Practical Examples

Complete Pytest Guide with Practical Examples

Pytest is one of the most popular Python testing frameworks. It is widely used for unit testing, functional testing, API testing, Selenium automation, database testing, and end-to-end testing.

This guide covers Pytest from beginner to advanced level, including installation, test cases, assertions, fixtures, parametrization, markers, command-line arguments, plugins, parallel execution, reporting, and CI/CD integration.

Complete Pytest Guide with Practical Examples


1. What is Pytest?

Pytest is a Python testing framework that makes it easy to write, execute, and manage automated tests.

Key Features

  • Simple and readable test syntax.
  • Automatically discovers test files and test functions.
  • Provides built-in assertions.
  • Supports fixtures for test setup and teardown.
  • Supports parameterized testing.
  • Allows test grouping using markers.
  • Supports parallel execution through plugins.
  • Supports API, UI, database, and unit testing.
  • Provides integration with CI/CD tools.
  • Supports HTML and Allure reporting.

2. Install Pytest

First, install Python and create a project directory.

mkdir pytest_project
cd pytest_project

Create a virtual environment:

python -m venv venv

Activate the virtual environment.

Windows

venv\Scripts\activate

macOS/Linux

source venv/bin/activate

Install Pytest:

pip install pytest

Verify the installation:

pytest --version

Install Commonly Used Pytest Plugins

pip install pytest-html
pip install pytest-xdist
pip install pytest-cov
pip install pytest-rerunfailures
pip install pytest-timeout
pip install pytest-order
pip install allure-pytest
pip install requests

3. Pytest Project Structure

A recommended project structure:

pytest_project/
│
├── tests/
│   ├── test_login.py
│   ├── test_user.py
│   ├── test_calculator.py
│   └── test_api.py
│
├── pages/
│   └── login_page.py
│
├── utilities/
│   └── config.py
│
├── test_data/
│   └── users.json
│
├── conftest.py
├── pytest.ini
└── requirements.txt

You can organize test cases into multiple files and folders based on application modules.

4. First Pytest Program

Create a file named test_calculator.py.

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

def test_addition():
    result = add(10, 20)
    assert result == 30

Run the test:

pytest

Expected output:

test_calculator.py .                   [100%]

1 passed

Pytest automatically discovers functions beginning with test_.

Test Discovery Naming Conventions

ElementNaming Convention
Test filetest_*.py or *_test.py
Test functiontest_*
Test classTest*
Test methodtest_*

Test Class Example

class TestCalculator:

    def test_addition(self):
        assert 10 + 20 == 30

    def test_subtraction(self):
        assert 20 - 10 == 10

Run:

pytest test_calculator.py

5. Pytest Assertions

Assertions validate the actual result against the expected result.

5.1 Equality Assertion

def test_equal():
    assert 10 == 10

5.2 Not Equal Assertion

def test_not_equal():
    assert 10 != 20

5.3 True and False Assertions

def test_boolean():
    assert True
    assert not False

5.4 Greater Than and Less Than

def test_comparison():
    assert 20 > 10
    assert 10 < 20
    assert 20 >= 20
    assert 10 <= 10

5.5 String Assertions

def test_string():
    name = "Pytest Automation"

    assert "Pytest" in name
    assert name.startswith("Pytest")
    assert name.endswith("Automation")

5.6 List Assertions

def test_list():
    numbers = [10, 20, 30]

    assert 10 in numbers
    assert len(numbers) == 3
    assert numbers == [10, 20, 30]

5.7 Dictionary Assertions

def test_dictionary():
    user = {
        "id": 101,
        "name": "Sumit",
        "active": True
    }

    assert user["id"] == 101
    assert user["name"] == "Sumit"
    assert user["active"] is True

6. Pytest Setup and Teardown

Setup and teardown operations execute before and after test execution. Pytest fixtures are the recommended approach for managing these operations.

Example Using Try and Finally

def test_example():

    print("Setup")

    try:
        assert 10 == 10

    finally:
        print("Teardown")

7. Pytest Fixtures

Fixtures are used to provide reusable setup and teardown functionality.

  • Open a browser before a test.
  • Connect to a database.
  • Create test data.
  • Authenticate API requests.
  • Initialize application configurations.
  • Close resources after execution.

7.1 Basic Fixture

import pytest

@pytest.fixture
def setup():
    print("Setup")
    return "Test Data"

def test_example(setup):
    print(setup)
    assert setup == "Test Data"

7.2 Fixture with Setup and Teardown

import pytest

@pytest.fixture
def setup():

    print("Opening browser")

    yield "Browser Object"

    print("Closing browser")

def test_login(setup):
    print("Executing login test")
    assert setup == "Browser Object"

Execution sequence:

  1. Open browser.
  2. Execute test.
  3. Close browser.

7.3 Fixture Scope

ScopeExecution
functionOnce per test function (default).
classOnce per test class.
moduleOnce per Python module.
packageOnce per package.
sessionOnce per test session.
import pytest

@pytest.fixture(scope="module")
def database():

    print("Connecting to database")

    yield "Database Connection"

    print("Closing database")

def test_user(database):
    assert database == "Database Connection"

def test_product(database):
    assert database == "Database Connection"

The database fixture is initialized once for the module and reused by both tests.

7.4 Class-Level Fixture

import pytest

@pytest.fixture(scope="class")
def setup_class():

    print("Class setup")

    yield

    print("Class teardown")

@pytest.mark.usefixtures("setup_class")
class TestLogin:

    def test_valid_login(self):
        assert True

    def test_invalid_login(self):
        assert True

7.5 Autouse Fixture

import pytest

@pytest.fixture(autouse=True)
def setup():

    print("Before test")

    yield

    print("After test")

def test_login():
    assert True

def test_logout():
    assert True

7.6 Multiple Fixtures

import pytest

@pytest.fixture
def username():
    return "admin"

@pytest.fixture
def password():
    return "admin123"

def test_login(username, password):

    assert username == "admin"
    assert password == "admin123"

7.7 Fixture Dependencies

import pytest

@pytest.fixture
def username():
    return "admin"

@pytest.fixture
def login(username):

    return {
        "username": username,
        "status": "success"
    }

def test_login(login):

    assert login["username"] == "admin"
    assert login["status"] == "success"

7.8 Fixture Parameterization

import pytest

@pytest.fixture(params=["Chrome", "Firefox", "Edge"])
def browser(request):
    return request.param

def test_browser(browser):

    print("Executing on:", browser)

    assert browser in ["Chrome", "Firefox", "Edge"]

This executes the test three times.

7.9 Fixtures in conftest.py

conftest.py is a special Pytest configuration file used to share fixtures across multiple test files.

pytest_project/
│
├── tests/
│   ├── conftest.py
│   ├── test_login.py
│   └── test_user.py

conftest.py

import pytest

@pytest.fixture
def user_data():

    return {
        "username": "admin",
        "password": "admin123"
    }

test_login.py

def test_login(user_data):
    assert user_data["username"] == "admin"

test_user.py

def test_user(user_data):
    assert user_data["password"] == "admin123"

Both test files can use the shared fixture without importing it.

8. Pytest Parametrization

Parametrization allows you to execute a single test function with multiple sets of test data. It is especially useful for data-driven testing.

8.1 Basic Parametrization

import pytest

@pytest.mark.parametrize(
    "a, b, expected",
    [
        (10, 20, 30),
        (5, 5, 10),
        (2, 3, 5),
        (100, 200, 300)
    ]
)
def test_addition(a, b, expected):
    assert a + b == expected

The test executes four times.

8.2 Multiple Parameters

import pytest

@pytest.mark.parametrize(
    "username, password, expected",
    [
        ("admin", "admin123", True),
        ("user", "user123", True),
        ("admin", "wrong", False),
        ("", "", False)
    ]
)
def test_login(username, password, expected):

    valid_users = {
        ("admin", "admin123"),
        ("user", "user123")
    }

    actual = (username, password) in valid_users

    assert actual == expected

8.3 Parametrize with Multiple Decorators

import pytest

@pytest.mark.parametrize("browser", ["Chrome", "Firefox"])
@pytest.mark.parametrize("environment", ["QA", "UAT"])
def test_application(browser, environment):
    print(browser, environment)
BrowserEnvironment
ChromeQA
ChromeUAT
FirefoxQA
FirefoxUAT

8.4 Parametrize with IDs

import pytest

@pytest.mark.parametrize(
    "username, password",
    [
        ("admin", "admin123"),
        ("user", "user123")
    ],
    ids=["Admin Login", "User Login"]
)
def test_login(username, password):

    assert username
    assert password

The IDs make test results easier to understand.

9. Pytest Markers

Markers are used to categorize, select, skip, or modify test execution.

9.1 Built-in Markers

MarkerPurpose
skipSkip a test.
skipifSkip based on a condition.
xfailMark an expected failure.
parametrizeRun tests with multiple datasets.
usefixturesApply fixtures to a test or class.
filterwarningsControl warning handling.

9.2 Skip a Test

import pytest

@pytest.mark.skip(reason="Feature not implemented")
def test_payment():
    assert True

9.3 Skip Conditionally

import pytest

@pytest.mark.skipif(
    True,
    reason="Skipping this test"
)
def test_example():
    assert True

9.4 Expected Failure Using xfail

import pytest

@pytest.mark.xfail(reason="Known application bug")
def test_known_bug():
    assert 10 == 20

9.5 Strict xfail

import pytest

@pytest.mark.xfail(
    strict=True,
    reason="Known defect"
)
def test_bug():
    assert 10 == 20

With strict=True, an unexpected pass is reported as a failure.

9.6 Create Custom Markers

Create pytest.ini:

[pytest]

markers =
    smoke: Smoke test cases
    regression: Regression test cases
    sanity: Sanity test cases
    api: API test cases
    ui: UI test cases

Apply markers:

import pytest

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

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

@pytest.mark.api
def test_get_user():
    assert True

Execute selected markers:

pytest -m smoke
pytest -m regression
pytest -m "smoke or sanity"
pytest -m "not regression"
pytest -m "api and smoke"

10. Pytest Command-Line Options

Pytest provides several command-line options to control test execution.

10.1 Common Commands

CommandDescription
pytestRun all discovered tests.
pytest -vVerbose output.
pytest -qQuiet output.
pytest -sDisplay print statements.
pytest -xStop after first failure.
pytest --maxfail=2Stop after two failures.
pytest -k loginRun tests matching a keyword.
pytest -m smokeRun tests with a marker.
pytest --collect-onlyDisplay collected tests.
pytest --lfRun previously failed tests.
pytest --ffRun previously failed tests first.
pytest -rAShow extra test summary for all outcomes.
pytest --tb=shortShort traceback.
pytest --tb=lineOne-line traceback.
pytest --disable-warningsHide warning summary.
pytest --strict-markersRaise errors for unknown markers.
pytest --durations=10Show the 10 slowest tests.

10.2 Run a Specific Test File

pytest tests/test_login.py

10.3 Run a Specific Test Function

pytest tests/test_login.py::test_valid_login

10.4 Run a Specific Test Class

pytest tests/test_login.py::TestLogin

10.5 Run a Specific Class Method

pytest tests/test_login.py::TestLogin::test_valid_login

10.6 Run Tests Using Keywords

pytest -k "login"
pytest -k "login and not invalid"
pytest -k "login or registration"

10.7 Combine Command-Line Options

pytest tests/ -v -s -x --tb=short

This runs all tests in the tests folder, displays print statements, stops on the first failure, and displays a short traceback.

10.8 Run Failed Tests Again

pytest --lf
pytest --ff

These options use Pytest's cache to remember previous test outcomes.

11. Pytest Command-Line Arguments in Python

You can pass custom arguments from the command line using pytest_addoption.

conftest.py

import pytest

def pytest_addoption(parser):

    parser.addoption(
        "--browser",
        action="store",
        default="chrome",
        help="Browser name"
    )

    parser.addoption(
        "--environment",
        action="store",
        default="QA",
        help="Execution environment"
    )

@pytest.fixture
def browser(request):
    return request.config.getoption("--browser")

@pytest.fixture
def environment(request):
    return request.config.getoption("--environment")

Test File

def test_application(browser, environment):

    print("Browser:", browser)
    print("Environment:", environment)

    assert browser
    assert environment

Execute:

pytest -v --browser firefox --environment UAT

Expected values:

Browser: firefox
Environment: UAT

This is useful when running automation against multiple browsers and environments.

12. Pytest Exception Handling

You can validate whether a particular exception is raised using pytest.raises().

Validate an Exception

import pytest

def divide(a, b):
    return a / b

def test_divide_by_zero():

    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

Validate Exception Message

import pytest

def test_exception():

    with pytest.raises(
        ValueError,
        match="Invalid input"
    ):
        raise ValueError("Invalid input")

Capture Exception Details

import pytest

def test_exception():

    with pytest.raises(ValueError) as exc:
        raise ValueError("Invalid username")

    assert str(exc.value) == "Invalid username"

13. Pytest Built-in Fixtures

Pytest provides several useful built-in fixtures.

FixturePurpose
tmp_pathCreate a temporary directory using pathlib.Path.
tmp_path_factoryCreate temporary directories at session or module level.
capsysCapture standard output and error.
capfdCapture file descriptor output.
monkeypatchTemporarily modify attributes, environment variables, and paths.
requestAccess information about the requesting test.
pytestconfigAccess Pytest configuration.
recwarnCapture warnings.
cacheStore and retrieve data between test runs.

13.1 tmp_path Example

def test_file(tmp_path):

    file = tmp_path / "test.txt"

    file.write_text("Hello Pytest")

    assert file.read_text() == "Hello Pytest"

13.2 capsys Example

def test_output(capsys):

    print("Hello Pytest")

    captured = capsys.readouterr()

    assert captured.out == "Hello Pytest\n"

13.3 monkeypatch Example

import os

def test_environment(monkeypatch):

    monkeypatch.setenv("ENV", "QA")

    assert os.getenv("ENV") == "QA"

The environment change is automatically restored after the test.

13.4 pytestconfig Example

def test_config(pytestconfig):

    root = pytestconfig.rootpath

    print(root)

    assert root.exists()

14. Pytest HTML Reporting

You can generate HTML reports using the pytest-html plugin.

Install

pip install pytest-html

Create an HTML Report

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

Run tests and generate the report:

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

Report Information

  • Total tests executed.
  • Passed test cases.
  • Failed test cases.
  • Skipped test cases.
  • Execution details.
  • Failure information.
  • Environment information.

Add Custom Report Title

def pytest_html_report_title(report):

    report.title = "Automation Test Execution Report"

15. Pytest Parallel Execution

Pytest supports parallel execution through the pytest-xdist plugin.

Install

pip install pytest-xdist

15.1 Run Tests Using Multiple Workers

pytest -n 4

This executes tests using four worker processes.

15.2 Use All Available CPU Cores

pytest -n auto

15.3 Distribute Tests Across Workers

pytest -n 4 --dist=load

15.4 Group Tests by File

pytest -n 4 --dist=loadfile

15.5 Run Tests in the Same Worker by Group

import pytest

@pytest.mark.xdist_group("login")
def test_login():
    assert True

@pytest.mark.xdist_group("login")
def test_logout():
    assert True

Execute:

pytest -n 4 --dist=loadgroup

Both tests in the login group execute in the same worker.

Important: When using parallel execution, avoid sharing mutable test data, browser sessions, or database records between workers unless you have proper isolation.

16. Pytest Test Execution Order

By default, Pytest does not provide a general-purpose test ordering guarantee. You can use the pytest-order plugin when a specific ordering is required.

Install

pip install pytest-order

Example

import pytest

@pytest.mark.order(1)
def test_login():
    assert True

@pytest.mark.order(2)
def test_dashboard():
    assert True

@pytest.mark.order(3)
def test_logout():
    assert True

Run:

pytest

Best practice: Keep test cases independent instead of depending on execution order.

17. Pytest Retry Failed Tests

Use pytest-rerunfailures to retry failed test cases.

Install

pip install pytest-rerunfailures

Retry Failed Tests Twice

pytest --reruns 2

Add a Delay Between Retries

pytest --reruns 2 --reruns-delay 3

Apply Retry to a Specific Test

import pytest

@pytest.mark.flaky(reruns=3)
def test_application():
    assert True

Retries can help diagnose intermittent failures, but should not be used to hide genuine application defects.

18. Pytest Timeout

Use pytest-timeout to prevent tests from running indefinitely.

Install

pip install pytest-timeout

Set a Global Timeout

pytest --timeout=30

Set a Timeout for an Individual Test

import pytest

@pytest.mark.timeout(10)
def test_example():
    assert True

The timeout is measured in seconds.

19. Pytest Code Coverage

Code coverage measures how much of your application code is executed by tests.

Install

pip install pytest-cov

Run Coverage

pytest --cov

Generate a Terminal Report

pytest --cov=src --cov-report=term-missing

Generate an HTML Coverage Report

pytest --cov=src --cov-report=html

The HTML report is generated in:

htmlcov/index.html

Generate Multiple Coverage Reports

pytest --cov=src --cov-report=term --cov-report=html

20. Pytest Logging

You can use Python's logging module to capture test execution details.

Logging Example

import logging

logger = logging.getLogger(__name__)

def test_login():

    logger.info("Starting login test")

    username = "admin"

    assert username == "admin"

    logger.info("Login test completed")

Execute:

pytest -v --log-cli-level=INFO

Save Logs to a File

pytest --log-file=pytest.log --log-file-level=INFO

21. Pytest Hooks

Hooks allow you to customize the Pytest execution lifecycle. Hooks are generally implemented in conftest.py or a Pytest plugin.

21.1 pytest_configure

Executed during initial configuration.

def pytest_configure(config):
    print("Pytest configuration started")

21.2 pytest_sessionstart

Executed at the beginning of the test session.

def pytest_sessionstart(session):
    print("Test session started")

21.3 pytest_sessionfinish

Executed when the test session finishes.

def pytest_sessionfinish(session, exitstatus):

    print("Test session completed")
    print("Exit status:", exitstatus)

21.4 pytest_runtest_setup

Executed before an individual test.

def pytest_runtest_setup(item):
    print("Setting up:", item.name)

21.5 pytest_runtest_teardown

Executed after an individual test.

def pytest_runtest_teardown(item, nextitem):
    print("Tearing down:", item.name)

21.6 pytest_collection_modifyitems

Modify or inspect collected test cases.

def pytest_collection_modifyitems(items):

    for item in items:
        print("Collected test:", item.name)

These hooks are useful for implementing custom reporting, test selection, environment setup, and automation framework integrations.

22. Pytest API Testing with Requests

Pytest can be used with the Python Requests library to automate REST API testing.

Install Dependencies

pip install requests pytest

22.1 GET Request

import requests

def test_get_user():

    url = "https://jsonplaceholder.typicode.com/users/1"

    response = requests.get(url)

    assert response.status_code == 200

    data = response.json()

    assert data["id"] == 1
    assert data["name"]
    assert data["email"]

22.2 POST Request

import requests

def test_create_user():

    url = "https://jsonplaceholder.typicode.com/posts"

    payload = {
        "title": "Pytest API Testing",
        "body": "Testing POST request",
        "userId": 1
    }

    response = requests.post(url, json=payload)

    assert response.status_code == 201

    data = response.json()

    assert data["title"] == payload["title"]
    assert data["userId"] == 1

22.3 PUT Request

import requests

def test_update_user():

    url = "https://jsonplaceholder.typicode.com/posts/1"

    payload = {
        "id": 1,
        "title": "Updated Title",
        "body": "Updated Body",
        "userId": 1
    }

    response = requests.put(url, json=payload)

    assert response.status_code == 200

    assert response.json()["title"] == "Updated Title"

22.4 DELETE Request

import requests

def test_delete_user():

    url = "https://jsonplaceholder.typicode.com/posts/1"

    response = requests.delete(url)

    assert response.status_code == 200

22.5 API Testing Using Fixtures

You can create a reusable Requests session using a fixture.

conftest.py

import pytest
import requests

@pytest.fixture(scope="session")
def api_session():

    session = requests.Session()

    session.headers.update({
        "Content-Type": "application/json",
        "Accept": "application/json"
    })

    yield session

    session.close()

test_api.py

def test_get_user(api_session):

    response = api_session.get(
        "https://jsonplaceholder.typicode.com/users/1"
    )

    assert response.status_code == 200
    assert response.json()["id"] == 1

def test_get_posts(api_session):

    response = api_session.get(
        "https://jsonplaceholder.typicode.com/posts"
    )

    assert response.status_code == 200
    assert len(response.json()) > 0

This approach allows you to reuse session configuration, headers, cookies, and connection pooling across API tests.

23. Pytest Selenium Automation

Pytest can be integrated with Selenium WebDriver for browser automation.

Install Dependencies

pip install pytest selenium

23.1 Selenium Fixture

Create conftest.py:

import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

@pytest.fixture
def driver():

    options = Options()

    options.add_argument("--start-maximized")

    browser = webdriver.Chrome(options=options)

    yield browser

    browser.quit()

23.2 Selenium Test Case

Create test_google.py:

from selenium.webdriver.common.by import By

def test_google_title(driver):

    driver.get("https://www.google.com")

    assert "Google" in driver.title

Run:

pytest -v

23.3 Selenium Screenshot on Failure

You can use a hook in conftest.py to capture screenshots when tests fail.

import pytest
from pathlib import Path

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):

    outcome = yield

    report = outcome.get_result()

    if report.when == "call" and report.failed:

        driver = item.funcargs.get("driver")

        if driver:

            Path("screenshots").mkdir(
                parents=True,
                exist_ok=True
            )

            driver.save_screenshot(
                f"screenshots/{item.name}.png"
            )

This is useful when debugging failed Selenium automation tests.

24. Pytest Database Testing

Pytest can also be integrated with database libraries. For example, use SQLite to demonstrate database testing.

import sqlite3
import pytest

@pytest.fixture
def database():

    connection = sqlite3.connect(":memory:")

    cursor = connection.cursor()

    cursor.execute("""
        CREATE TABLE users (
            id INTEGER PRIMARY KEY,
            name TEXT,
            email TEXT
        )
    """)

    cursor.execute("""
        INSERT INTO users VALUES
        (1, 'Sumit', 'sumit@example.com')
    """)

    connection.commit()

    yield connection

    connection.close()

def test_user(database):

    cursor = database.cursor()

    cursor.execute(
        "SELECT name FROM users WHERE id = ?",
        (1,)
    )

    result = cursor.fetchone()

    assert result[0] == "Sumit"

The in-memory database is created for the test and automatically closed afterward.

25. Pytest Configuration Using pytest.ini

The pytest.ini file allows you to maintain common test execution configurations.

Example

[pytest]

testpaths = tests

python_files = test_*.py

python_classes = Test*

python_functions = test_*

addopts = -v -ra --strict-markers

markers =
    smoke: Smoke tests
    regression: Regression tests
    api: API tests
    ui: UI tests
    sanity: Sanity tests

log_cli = true

log_cli_level = INFO

Now simply execute:

pytest

Pytest automatically reads the configuration.

26. Pytest with Environment Variables

You can use environment variables to maintain separate configurations for QA, UAT, and production environments.

Install

pip install python-dotenv

Create .env

BASE_URL=https://example.com
ENVIRONMENT=QA

Read the Values

import os
from dotenv import load_dotenv

load_dotenv()

def test_environment():

    base_url = os.getenv("BASE_URL")

    environment = os.getenv("ENVIRONMENT")

    assert base_url
    assert environment == "QA"

You can maintain separate environment files:

.env.qa
.env.uat
.env.prod

Never store real passwords, API keys, or production secrets in source control.

27. Pytest Allure Reporting

Allure provides detailed and interactive test execution reports.

Install

pip install allure-pytest

Create a Test

import allure

@allure.feature("Login")
@allure.story("Valid Login")
@allure.title("Verify login using valid credentials")
def test_login():

    with allure.step("Enter username"):

        username = "admin"

        assert username == "admin"

    with allure.step("Verify login"):

        assert True

Execute

pytest --alluredir=allure-results

Generate the Report

allure generate allure-results --clean -o allure-report

Open the Report

allure open allure-report

The Allure command-line application must also be installed separately.

28. Pytest GitHub Actions Integration

You can execute Pytest automatically whenever code is pushed to GitHub.

Create:

.github/workflows/pytest.yml

Example Workflow

name: Python Pytest Automation

on:
  push:
    branches:
      - main

  pull_request:
    branches:
      - main

  workflow_dispatch:

jobs:

  pytest:

    runs-on: ubuntu-latest

    steps:

      - name: Checkout Code
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install Dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: Execute Pytest
        run: |
          pytest tests/ -v --junitxml=results.xml

      - name: Upload Test Results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: pytest-results
          path: results.xml

Pipeline Execution Steps

  1. Checks out the repository.
  2. Installs Python.
  3. Installs dependencies.
  4. Executes automated tests.
  5. Generates JUnit XML results.
  6. Uploads test results as an artifact.

29. Pytest Exit Codes

Pytest returns different exit codes depending on the test execution result.

Exit CodeMeaning
0All tests passed.
1Tests were collected and some failed.
2Test execution was interrupted.
3Internal error occurred.
4Command-line usage error.
5No tests were collected.
6Warning limit exceeded.

These exit codes are useful when integrating Pytest with Jenkins, GitHub Actions, GitLab CI, and other CI/CD systems.

30. Important Pytest Plugins

Here is a list of commonly used Pytest plugins.

PluginInstallationPurpose
pytest-htmlpip install pytest-htmlHTML reports.
pytest-xdistpip install pytest-xdistParallel execution.
pytest-covpip install pytest-covCode coverage.
pytest-rerunfailurespip install pytest-rerunfailuresRetry failed tests.
pytest-timeoutpip install pytest-timeoutTest timeout.
pytest-orderpip install pytest-orderTest ordering.
allure-pytestpip install allure-pytestAllure reporting.
pytest-mockpip install pytest-mockMocking support.
pytest-bddpip install pytest-bddBDD testing.
pytest-djangopip install pytest-djangoDjango testing.
pytest-asynciopip install pytest-asyncioAsync testing.
pytest-envpip install pytest-envEnvironment variables.

31. Pytest vs Unittest

Both Pytest and Unittest are popular Python testing frameworks.

FeaturePytestUnittest
InstallationExternal packageBuilt into Python
Test syntaxSimple functionsTest classes
AssertionsPython assertself.assertEqual() etc.
FixturesPowerful fixture systemsetUp/tearDown
ParameterizationBuilt-in markerAdditional implementation needed
PluginsLarge plugin ecosystemMore limited
Parallel executionpytest-xdistAdditional tools
HTML reportingPluginsAdditional tools
Test discoveryAutomaticAutomatic
Learning curveEasyModerate

Recommendation: Pytest is an excellent choice for new Python automation projects because of its fixture system, parametrization, assertion support, and plugin ecosystem.

32. Best Practices for Pytest Automation Frameworks

Follow these practices when creating a professional automation framework.

  1. Use fixtures: Keep browser, API, and database setup reusable.
  2. Use conftest.py: Maintain shared fixtures and hooks centrally.
  3. Use parametrization: Avoid writing duplicate test functions.
  4. Use markers: Separate smoke, regression, API, and UI tests.
  5. Keep tests independent: Avoid depending on the execution order of other tests.
  6. Use meaningful names: Test names should describe expected behavior.
  7. Separate test data: Keep test data outside test implementation.
  8. Use environment configurations: Maintain QA, UAT, and production configurations separately.
  9. Use proper reporting: Generate HTML, Allure, or JUnit reports.
  10. Use parallel execution carefully: Make tests independent and isolate shared resources.
  11. Capture logs and screenshots: Make failures easier to troubleshoot.
  12. Manage secrets securely: Use environment variables or CI/CD secret stores.
  13. Avoid unnecessary retries: Investigate flaky tests instead of hiding failures.
  14. Use version control: Maintain your automation framework in Git.

33. Complete Pytest Execution Command Cheat Sheet

The following commands are useful in day-to-day automation testing.

RequirementCommand
Execute all testspytest
Verbose executionpytest -v
Display print statementspytest -s
Execute a particular filepytest test_login.py
Execute a particular testpytest test_login.py::test_login
Execute a classpytest test_login.py::TestLogin
Run smoke testspytest -m smoke
Run regression testspytest -m regression
Run tests by keywordpytest -k login
Stop after first failurepytest -x
Stop after three failurespytest --maxfail=3
Rerun failed testspytest --lf
Show failed tests firstpytest --ff
Collect tests onlypytest --collect-only
Generate HTML reportpytest --html=report.html
Generate coveragepytest --cov
Generate JUnit reportpytest --junitxml=results.xml
Run parallel testspytest -n 4
Use available CPU corespytest -n auto
Retry failed testspytest --reruns 2
Apply timeoutpytest --timeout=30
Show slowest testspytest --durations=10
Run with short tracebackpytest --tb=short
Show all outcomespytest -rA

34. Recommended Learning Roadmap

Beginner Level

  • Installation and configuration.
  • Test discovery.
  • Assertions.
  • Test classes and functions.
  • Setup and teardown.

Intermediate Level

  • Fixtures and fixture scopes.
  • conftest.py.
  • Parametrization.
  • Markers.
  • Command-line arguments.
  • Built-in fixtures.

Advanced Level

  • Hooks.
  • Custom plugins.
  • Mocking.
  • Parallel execution.
  • Retry and timeout.
  • Logging and reporting.

Professional Automation

  • REST API automation.
  • Selenium automation.
  • Database automation.
  • Page Object Model.
  • CI/CD integration.
  • Docker-based execution.

35. Final Project: Recommended Pytest Framework

For a real-world automation project, you can use the following structure:

pytest_automation/
│
├── config/
│   ├── config.py
│   └── environment.py
│
├── tests/
│   ├── api/
│   │   ├── test_get_user.py
│   │   └── test_create_user.py
│   │
│   ├── ui/
│   │   ├── test_login.py
│   │   └── test_dashboard.py
│   │
│   └── database/
│       └── test_user_db.py
│
├── pages/
│   ├── login_page.py
│   └── dashboard_page.py
│
├── fixtures/
│   └── test_data.py
│
├── utilities/
│   ├── logger.py
│   ├── api_client.py
│   └── database.py
│
├── reports/
│
├── conftest.py
├── pytest.ini
├── requirements.txt
└── README.md

Suggested Dependencies

pytest
requests
selenium
pytest-html
pytest-xdist
pytest-cov
pytest-rerunfailures
pytest-timeout
pytest-mock
allure-pytest
python-dotenv

Example Execution Commands

# Execute all tests
pytest

# Execute API tests
pytest tests/api -v

# Execute UI tests
pytest tests/ui -v

# Execute smoke tests
pytest -m smoke

# Execute tests in parallel
pytest -n 4

# Generate HTML report
pytest --html=reports/report.html --self-contained-html

# Generate coverage report
pytest --cov=utilities --cov-report=html

Conclusion

Pytest is a powerful and flexible framework for Python automation. By combining fixtures, parametrization, markers, API testing, Selenium, reporting, and CI/CD integration, you can build a maintainable automation framework suitable for enterprise-level projects.

Official Documentation

No comments:

Post a Comment