Essential Pytest Fundamentals and Usage Guide

Advantages of Using Pytest

Pytest is a mature testing framework for Python that offers a robust set of features designed to simplify the testing process. It is known for its ease of use and detailed documentation. The framework supports both simple unit tests and complex functional testing scenarios. Key capabilities include parametrization, the ability to skip specific tests or mark expected failures, and mechanisms to re-run failed cases. Pytest is compatible with tests written for `unittest` and `nose`, generates HTML reports, and integrates seamlessly with CI/CD tools like Jenkins. It allows for partial test execution and supports a vast ecosystem of third-party plugins and custom extensions.

Installation and Verification

To install the framework, use the Python package manager:

pip install pytest

Once installed, verify the version to ensure it is correctly set up:

pytest --version

Quick Start Example

Create a Python file containing a function to test and the corresponding test logic. Below is an example that includes a standalone test function and a test class.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def calculate_discount(price, rate):
    return price * (1 - rate)

def test_discount_calculation():
    assert calculate_discount(100, 0.2) == 80.0

class VerifyUserProfiles:
    def test_username_length(self):
        user = "admin_user"
        assert len(user) >= 5

    def test_attributes_exist(self):
        config = {"debug": True}
        assert "debug" in config

Navigate to the directory containing the file in your terminal and execute the following command to run the tests:

pytest

Naming Conventions

Pytest relies on strict naming conventions to automatically discover test files and functions. Adherence to the following rules is required for tests to be detected and executed:

  • Filenames must match the patterns test_*.py or *_test.py.
  • Test functions must start with the prefix test_.
  • Test classes must begin with Test and must not contain an __init__ method.
  • Methods within test classes must also start with test_.
  • Directories acting as packages must include an __init__.py file.

Execution Rules and CLI Options

The following commands are used to control how tests are discovered and executed from the command line.

Basic Execution

Running pytest without arguments searches the current directory and all subdirectories for files matching the naming conventions.

pytest

Targeting a Specific File

To run tests contained in a specific file, provide the filename as an argument:

pytest example_script.py

Executing Specific Test Nodes

You can target a specific function, class, or method using the :: syntax. Adding the -v flag increases verbosity.

pytest -v example_script.py::VerifyUserProfiles::test_username_length

pytest example_script.py::test_discount_calculation

Running Marked Tests

The -m flag allows you to run tests decorated with a specific marker (e.g., @pytest.mark.smoke).

pytest -m smoke

Output Control

Use -q for quiet mode (less output) or -s to allow print statements and standard output to display in the console.

pytest -q example_script.py
pytest -s example_script.py

Stopping on Failures

To stop the test session immediately upon the first failure, use the -x flag. Alternatively, use --maxfail=num to continue testing until a specified number of failures is reached.

pytest example_script.py -x
pytest example_script.py --maxfail=2

Filtering by Expression

The -k option enables filtering tests based on their names. This supports logical operators to include or exclude specific cases.

Run tests containing the word "profile":

pytest -s -k profile example_script.py

Exclude tests containing "discount":

pytest -s -k "not discount" example_script.py

Run tests matching "user" or "admin":

pytest -s -k "user or admin" example_script.py

Tags: pytest python testing Tutorial

Posted on Mon, 05 Oct 2026 16:24:48 +0000 by Drakkie