欢迎访问宙启技术站
智能推送

Pythonpytest()库的使用指南。

发布时间:2024-01-02 23:11:13

pytest 是 Python 中常用的测试框架,提供了方便的测试运行和断言功能。pytest 的使用指南如下:

1. 安装 pytest

可以使用以下命令安装 pytest:

pip install pytest

2. 创建测试文件

在项目的根目录下创建一个以 "test_" 开头的文件,例如 "test_example.py"。在该文件中编写测试用例。

3. 编写测试用例

使用 pytest 编写测试用例非常简单,只需要创建一个以 "test_" 开头的函数即可。例如:

# test_example.py

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

def test_subtraction():
    assert 5 - 3 == 2

在上面的例子中,两个测试用例分别测试了加法和减法的结果是否符合预期。使用 assert 语句来进行断言判断。

4. 运行测试

使用以下命令在终端中运行测试:

pytest

pytest 会自动搜索当前目录及其子目录中的测试文件,并执行其中的测试用例。

5. 断言判断

pytest 提供了丰富的断言方法,用来判断结果是否符合预期。以下是一些常用的断言方法:

- assert:判断表达式是否为 True,如果不是,则抛出 AssertionError 异常。

- assertEqual(a, b):判断 a 和 b 是否相等。

- assertNotEqual(a, b):判断 a 和 b 是否不相等。

- assertTrue(x):判断 x 是否为 True。

- assertFalse(x):判断 x 是否为 False。

- assertIn(a, b):判断 a 是否在 b 中。

- assertNotIn(a, b):判断 a 是否不在 b 中。

其中,多数断言方法都支持自定义消息,例如:

def test_addition():
    assert 1 + 1 == 2, "1 + 1 应该等于 2"

6. 参数化测试

pytest 提供了参数化测试的功能,可以用于对相同的测试用例使用不同的参数进行测试。使用 @pytest.mark.parametrize 装饰器来指定参数化的参数。

import pytest

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

在上面的例子中,test_addition 函数被参数化为三组参数进行测试。

7. 跳过测试

使用 @pytest.mark.skip 装饰器可以跳过某个测试用例的执行。

import pytest

@pytest.mark.skip
def test_this_test_will_be_skipped():
    assert False

在上面的例子中,test_this_test_will_be_skipped 函数将不会被执行。

8. Fixture 定义

Fixture 是 pytest 的一个重要特性,用于提供测试环境的搭建和清理功能。通过使用 @pytest.fixture 装饰器来定义 Fixture。

import pytest

@pytest.fixture
def my_fixture():
    return "Hello, world!"

def test_use_fixture(my_fixture):
    assert my_fixture == "Hello, world!"

在上面的例子中,my_fixture 函数被定义为 Fixture,可以在其他测试函数中使用。

以上就是 pytest 的一些基本使用指南和示例。pytest 还提供了很多其他的功能和插件,例如测试报告生成、命令行参数配置等,可以根据实际需求进行使用。