Pytest 是一个 Python 编写的测试框架,它可以帮助我们更方便地编写和运行测试用例。下面是 Pytest 的使用方法:
1. 安装 Pytest:使用 pip 命令安装 Pytest,命令如下:
pip install pytest
2. 编写测试用例:在项目中创建一个 test 目录,并在其中编写测试用例。测试用例的文件名必须以 test_ 开头,测试函数的名字必须以 test_ 开头。例如,下面是一个简单的测试用例:
def test_add():
assert 1 + 1 == 2
3. 运行测试用例:在命令行中进入项目根目录,执行以下命令运行测试用例:
pytest
Pytest 会自动查找 test 目录下的所有测试用例,并运行它们。如果测试用例运行成功,将会显示一个绿色的句号;如果测试用例运行失败,将会显示一个红色的 F。
4. 参数化测试:Pytest 支持参数化测试,可以用同一个测试函数测试多组数据。例如,下面是一个参数化测试的例子:
import pytest
@pytest.mark.parametrize("x, y, expected", [
(1, 2, 3),
(2, 3, 5),
(3, 4, 7),
])
def test_add(x, y, expected):
assert x + y == expected
使用 @pytest.mark.parametrize 装饰器来指定参数化的参数和期望结果。每组参数和期望结果用一个元组表示,多组参数和期望结果用一个列表表示。
5. 断言:Pytest 支持多种断言方式,例如 assert、assertEqual、assertTrue 等等。例如,下面是一个使用 assertEqual 的例子:
def test_add():
result = 1 + 1
expected = 2
assertEqual(result, expected)
这个测试用例使用 assertEqual 断言判断 result 是否等于 expected。
6. Fixture:Pytest 支持 Fixture,可以在测试用例中使用 Fixture 来提供测试数据和测试环境。例如,下面是一个使用 Fixture 的例子:
import pytest
@pytest.fixture
def my_fixture():
return "hello"
def test_mytest(my_fixture):
assert my_fixture == "hello"
这个测试用例使用 my_fixture Fixture 来提供测试数据,并在测试用例中使用 my_fixture。
以上是 Pytest 的基本使用方法,当然还有很多高级用法和插件,可以根据具体需求进行学习和使用。