Pytest使用教程分享

当你需要编写和运行Python单元测试时,pytest是一个功能强大且流行的库。以下是一个全面的pytest使用教程,涵盖了常见的用法和示例:

步骤 1: 安装pytest 首先,确保你的系统上已经安装了Python。然后,使用以下命令安装pytest:

Copy code

pip install pytest

步骤 2: 创建测试文件在你的项目目录中,创建一个新的Python文件,并以test_开头命名,例如test_example.py。在该文件中,你将编写测试用例。

步骤 3: 编写测试用例在测试文件中,你可以使用pytest提供的装饰器(如@pytest.fixture、@pytest.mark.parametrize)来定义测试用例和测试数据。示例如下:

python

import pytest

# 测试函数

def add(a, b):

    return a + b

# 测试用例

def test_add():

    assert add(2, 3) == 5

# 使用装饰器定义参数化测试用例

@pytest.mark.parametrize("a, b, expected", [(2, 3, 5), (5, 7, 12)])

def test_add_parametrized(a, b, expected):

    assert add(a, b) == expected

# 使用fixture准备测试环境

@pytest.fixture

def setup():

    # 执行前置操作

    print("Setup")

    # 返回一个值供测试用例使用

    yield "test data"

    # 执行后置操作

    print("Teardown")

# 使用fixture进行测试

def test_fixture_example(setup):

    data = setup

    assert data == "test data"

步骤 4: 运行测试在命令行中,导航到你的项目目录,并运行以下命令来执行测试:

pytest

pytest将自动搜索并执行项目目录中以test_开头的测试文件,并输出测试结果。

猜你喜欢

转载自blog.csdn.net/m0_73291751/article/details/131008696
今日推荐