如何用pytest编写单元测试

发布时间:2025-03-30 19:01:31 作者:小樊
来源:亿速云 阅读:109

使用 pytest 编写单元测试是一个相对简单且强大的过程。以下是一些基本步骤和示例,帮助你开始使用 pytest 进行单元测试。

1. 安装 pytest

首先,你需要安装 pytest。你可以使用 pip 来安装:

pip install pytest

2. 编写测试代码

假设你有一个简单的 Python 模块 math_utils.py,其中包含一些数学函数:

# math_utils.py

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

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

3. 编写测试用例

接下来,你需要编写测试用例。测试用例通常放在一个以 test_ 开头的文件中,例如 test_math_utils.py

# test_math_utils.py

from math_utils import add, subtract, multiply, divide

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

def test_subtract():
    assert subtract(5, 3) == 2
    assert subtract(0, 0) == 0
    assert subtract(-1, -1) == 0

def test_multiply():
    assert multiply(2, 3) == 6
    assert multiply(-1, 1) == -1
    assert multiply(-1, -1) == 1

def test_divide():
    assert divide(6, 3) == 2
    assert divide(0, 1) == 0
    assert divide(-6, 3) == -2

def test_divide_by_zero():
    with pytest.raises(ValueError):
        divide(1, 0)

4. 运行测试

在命令行中,导航到包含 test_math_utils.py 文件的目录,然后运行 pytest

pytest

pytest 会自动发现并运行所有以 test_ 开头的函数,并报告测试结果。

5. 查看测试结果

pytest 会输出测试结果,包括通过的测试和失败的测试。例如:

============================= test session starts ==============================
...
collected X items

test_math_utils.py::test_add PASSED                           [ 33%]
test_math_utils.py::test_subtract PASSED                        [ 66%]
test_math_utils.py::test_multiply PASSED                       [100%]

============================== X passed in X.XXs ===============================

6. 高级功能

pytest 提供了许多高级功能,例如:

示例:使用夹具

# test_math_utils_with_fixture.py

import pytest
from math_utils import add

@pytest.fixture
def setup_data():
    return 2, 3

def test_add(setup_data):
    a, b = setup_data
    assert add(a, b) == 5

示例:参数化测试

# test_math_utils_parametrized.py

import pytest
from math_utils import add

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

通过这些步骤和示例,你应该能够开始使用 pytest 编写和运行单元测试了。更多详细信息和高级功能,请参考 pytest 官方文档

推荐阅读:
  1. 怎么在python中利用selenium对微博内容进行爬取
  2. 使用Python怎么实现一个网络聊天室功能

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

python

上一篇:参照完整性对数据一致性有何作用

下一篇:如何设计数据库以保持参照完整性

相关阅读

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

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