温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用python pytest写测试

发布时间:2026-09-24 06:06:16 来源:亿速云 阅读:86 作者:小樊 栏目:编程语言

下面从入门到常用技巧,教你如何用 Python 的 pytest 写测试。


一、安装 pytest

pip install pytest

验证:

pytest --version

二、最简单的 pytest 示例

1. 写一个被测试的函数

calc.py

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

2. 写测试文件

测试文件通常以 test_ 开头,或位于 tests/ 目录中。

test_calc.py

from calc import add

def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0

3. 运行测试

pytest

或指定文件:

pytest test_calc.py

三、断言(assert)

pytest 使用 Python 原生 assert,但失败信息更友好:

def test_example():
    assert 1 + 1 == 2
    assert "hello" in "hello world"

四、参数化测试(常用)

避免写多个重复测试函数。

import pytest
from calc import add

@pytest.mark.parametrize(
    "a,b,expected",
    [
        (1, 2, 3),
        (0, 0, 0),
        (-1, 1, 0),
    ],
)
def test_add(a, b, expected):
    assert add(a, b) == expected

五、测试异常

import pytest

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

def test_div_zero():
    with pytest.raises(ZeroDivisionError):
        div(1, 0)

六、前置与后置(fixture)

1. 基本 fixture

import pytest

@pytest.fixture
def sample_data():
    return {"name": "pytest"}

def test_sample(sample_data):
    assert sample_data["name"] == "pytest"

2. 带 setup / teardown

@pytest.fixture
def db():
    print("connect db")
    yield "db_connection"
    print("close db")

七、测试类(组织测试)

class TestCalc:
    def test_add(self):
        assert 1 + 1 == 2

    def test_sub(self):
        assert 3 - 1 == 2

八、常用运行参数

pytest -v              # 详细输出
pytest -k add         # 只跑名字含 add 的测试
pytest -x             # 第一个失败就停
pytest --maxfail=2    # 最多失败 2 次
pytest test_calc.py::test_add

九、目录结构建议

project/
├── calc.py
├── tests/
│   ├── test_calc.py
│   └── test_utils.py
└── pytest.ini

pytest.ini

[pytest]
testpaths = tests

十、一个完整小例子

# calc.py
def add(a, b):
    return a + b
# tests/test_calc.py
import pytest
from calc import add

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (2, 3, 5),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

运行:

pytest -v

如果你愿意,我可以:

  • 真实项目结构 示例教你
  • mock / pytest-mock
  • pytest + Flask / Django
  • 覆盖率 pytest-cov

你现在是打算测试什么类型的代码?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI