Pytest 测试框架:Python 自动化测试入门指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Pytest:Python 测试完全指南

Pytest 简介

测试是软件开发中至关重要的一环。没有高质量的测试,代码的可靠性和修改后的稳定性都难以保障。Pytest 是一个现代化、功能强大且易用的 Python 自动化测试框架,它极大地简化了编写和执行测试的过程。

Pytest 凭借其简洁的语法、丰富的扩展能力和强大的 Fixture(夹具)系统,在开发者社区中广受欢迎。在易用性和测试开发速度方面,它显著优于 Python 标准库中的 unittest 模块。

Pytest 安装与配置

通过 pip 安装

pip install pytest

验证安装

pytest --version

编写第一个简单测试

创建文件 test_example.py:

def test_addition():
    assert 2 + 2 == 4

def test_string_operations():
    text = "Hello, World!"
    assert "Hello" in text
    assert len(text) == 13

运行测试

pytest

Pytest 会自动发现所有符合命名约定的测试文件和测试函数。

测试结构与组织

命名约定

Pytest 使用以下约定来自动发现测试:

  • 测试文件:test_*.py 或 *_test.py
  • 测试函数:def test_...()
  • 测试类:class Test...(不包含 __init__ 方法)
  • 类中的测试方法:def test_...()

组织测试目录结构

project/
├── src/
│   ├── calculator.py
│   └── utils.py
├── tests/
│   ├── test_calculator.py
│   ├── test_utils.py
│   └── conftest.py
└── pytest.ini

使用不同参数运行测试

# 运行所有测试
pytest

# 运行指定目录下的测试
pytest tests/

# 运行指定测试文件
pytest test_calculator.py

# 运行指定测试函数
pytest test_calculator.py::test_add

# 运行测试类中的所有测试
pytest test_calculator.py::TestCalculator

# 运行类中的指定测试方法
pytest test_calculator.py::TestCalculator::test_multiply

编写测试基础

使用 assert 进行断言

Pytest 使用 Python 标准的 assert 语句来检查条件:

def test_basic_assertions():
    # 检查相等
    assert 2 + 2 == 4
    
    # 检查不相等
    assert 3 * 3 != 8
    
    # 检查包含关系
    assert "Python" in "Python testing"
    
    # 检查类型
    assert isinstance(42, int)
    
    # 检查真值
    assert bool([1, 2, 3])
    
    # 检查假值
    assert not bool([])

测试异常

import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero is not allowed")
    return a / b

def test_division_by_zero():
    with pytest.raises(ValueError):
        divide(10, 0)

def test_exception_message():
    with pytest.raises(ValueError, match="Division by zero"):
        divide(10, 0)

def test_exception_type():
    with pytest.raises(ZeroDivisionError):
        1 / 0

将测试组织到类中

class TestCalculator:
    def test_addition(self):
        assert 2 + 3 == 5
    
    def test_subtraction(self):
        assert 5 - 3 == 2

推荐