Fundamentals 8 min read

Introduction to Pytest: Installation, Usage, Assertions, and Common Commands

This article provides a comprehensive overview of the Pytest framework, covering its key features, installation steps, test file conventions, execution commands, assertion methods, and examples of API testing with detailed code snippets.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Introduction to Pytest: Installation, Usage, Assertions, and Common Commands

Pytest is a mature, full‑featured Python testing framework that makes it easy to write small unit tests while also scaling to complex functional testing for applications and libraries.

Key features include:

Simple, flexible, and easy to learn.

Supports parametrization.

Handles both simple unit tests and complex functional tests, suitable for automation.

Rich third‑party plugin ecosystem and extensibility.

Built‑in support for skip and xfail handling.

Seamless integration with Jenkins.

Can run tests written for Nose or unittest.

Installation is straightforward using pip:

pip install -U pytest    # -U upgrades to the latest version if already installed

Verify the installation with:

pytest --version    # displays the installed version

Test files must follow the naming convention test_*.py or *_test.py . Test classes should start with Test and must not define an __init__ method. Individual test functions must be prefixed with test_ .

Running tests can be done via the command line or programmatically with pytest.main() . Common command‑line options include:

-m=tag : run tests with a specific marker.

-reruns=N : rerun failed tests up to N times.

-q : quiet mode, suppress environment info.

-v : verbose mode, show detailed test information.

-s : show print/log output.

--resultlog=./log.txt : generate a plain‑text log.

--junitxml=./log.xml : generate an XML report.

--maxfail=N : stop after N failures.

--tb=line : display tracebacks in a single line.

Assertions in Pytest rely on Python’s native assert statement. Typical forms are:

== : both value and type must match.

in : checks that the actual result contains the expected element.

is : checks object identity.

Example of simple assertion tests:

import pytest

def add(x, y):
    return x + y

def test_add():
    assert add(1, 2) == 3  # passes

def test_in():
    str1 = "Python,Java,Ruby"
    assert "PHP" in str1  # fails

if __name__ == "__main__":
    pytest.main(["-v", "test_pytest.py"])

An API‑testing example demonstrates how to send a POST request and assert the response:

# -*- coding: utf-8 -*-
import pytest
import requests

def test_agent():
    r = requests.post(
        url="http://127.0.0.1:9000/get_user",
        data={"name": "吴磊", "sex": 1},
        headers={"Content-Type": "application/json"}
    )
    print(r.text)
    assert r.json()["data"]["retCode"] == "00" and r.json()["data"]["retMsg"] == "调用成功"

if __name__ == "__main__":
    pytest.main(["-v", "test_api.py"])

These examples illustrate how Pytest can be used for both simple unit tests and more complex integration or API tests, providing flexible execution options and detailed reporting.

test automationunit testingCommand-linepytestpython testingAssertions
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.