pytest是一个用于编写和执行Python单元测试的框架。它提供了丰富的功能和灵活性,使得编写和运行测试变得简单而高效。
pytest的一些主要特点和解释如下:
总结来说,pytest是一个功能强大且易于使用的Python单元测试框架,它提供了丰富的特性和灵活的配置选项,使开发人员能够高效地进行测试驱动的开发,并保证代码质量和可靠性。
1、pytest 安装
安装命令: pip install -U pytest
查看版本: pytest --version
2、pytest 扩展插件
pip install pytest-cov
pip install pytest-html
pip install pytest-xdist
pip install pytest-repeat
pip install pytest-mock
pip install pytest-selenium
pip install pytest-timeout
pip install pytest-django
pip install pytest-flask
pip install pytest-bdd
pip install pytest-datadir
pip install pytest-ordering
pip install pytest-rerunfailures
pip install pytest-base-url
pip install allure-pytest
pip install pytest-randomly
pip install pytest-asyncio
文件名要求: 通常 pytest 会自动发现以 test_ 开头或 _test 结尾的文件作为测试文件,但也可以通过配置进行自定义。例如 test_example.py 或 example_test.py 都符合命名约定。
以 test_ 开头的函数: pytest 将识别以 test_ 开头的函数作为测试用例,这些函数应该包含您要测试的特定行为或功能。例如 def test_addition(): 是一个以 test_ 开头的测试用例函数。
以 Test 开头的类和以 test_ 开头的方法: pytest 另一个常见的约定是,以 Test 开头的类用于组织相关的测试用例,并且类中以 test_ 开头的方法被识别为独立的测试用例。请注意,这些方法不能包含 __ init __ 方法。
使用 assert 进行断言: 在 pytest 中,使用 assert 语句进行断言是推荐的做法。例如 assert add(2, 3) == 5 可以用于断言 add() 函数的结果是否符合预期。
1、测试函数和测试类
# content of test_sample.py
# 测试函数
def func(x):
return x + 1
def test_answer():
assert func(3) == 4
# 可以看到pytest自动地运行了test_answer函数,同时提示测试通过,因为func函数的返回值是4
# 测试类,把多条用例放到一个类中
class TestClass:
def func(self, x):
return x + 1
def test_B(self):
assert self.func(3) == 6, '结果不符合预期'
def test_A(self):
assert self.func(3) == 5
# 可以看到,pytest自动地运行了test_B和test_A函数,同时都提示测试失败,\
# 因为TestClass类中的func方法的返回值是4,而不是6和5,所以assert语句报错
2、参数化测试
# content of test_sample.py
import pytest
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(4, 5, 9),
(6, 7, 13)
])
def test_addition(a, b, expected):
assert a + b == expected
通过 @pytest.mark.parametrize 装饰器,指定了要传入 test_addition 函数的参数和预期结果。在这个例子中,我们定义了三组参数 (2, 3, 5)、(4, 5, 9) 和 (6, 7, 13)。
然后,test_addition 函数会依次接收每组参数,并执行断言语句 assert a + b == expected 进行验证。如果断言条件成立,即两数相加等于预期结果,那么测试通过;否则,会触发断言错误,测试失败。
3、跳过测试
# content of test_sample.py
import pytest
@pytest.mark.skip(reason="Not implemented yet")
def test_multiply():
assert 3 * 4 == 12
使用@pytest.mark.skip装饰器将其标记为跳过的测试,并提供了一个说明信息"Not implemented yet"
由于该测试函数被标记为跳过,因此在运行测试套件时,这个测试不会被执行。这可以作为一个占位符,表示该测试还没有实现。一旦实现了相应的功能,可以删除@pytest.mark.skip行或注释掉它,以便让测试函数正常运行。
4、分组和标记
# content of test_sample.py
import pytest
@pytest.mark.group1
def test_addition():
assert (1 + 2) == 3
@pytest.mark.group1
def test_subtraction():
assert (5 - 3) == 2
@pytest.mark.group2
@pytest.mark.skip(reason="Not implemented yet")
def test_multiplication():
assert (2 * 3) == 6
@pytest.mark.group2
def test_division():
assert (10 / 2) == 5
@pytest.mark.group1和@pytest.mark.group2是自定义标记,可以用来对测试函数进行分组或分类。通过在运行测试时指定标记,可以选择性地运行特定的测试组
例如,可以使用以下命令只运行被标记为group1的测试:
pytest -m group1
这样只会执行test_addition()和test_subtraction()函数,而跳过test_multiplication()和test_division()函数
[pytest]
markers =
group1: group1 测试的描述
group2: group2 测试的描述
5、异常处理
# content of test_sample.py
import pytest
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
def test_divide():
with pytest.raises(ZeroDivisionError) as exc_info:
divide(10, 0)
assert str(exc_info.value) == "Cannot divide by zero"
在上面的示例中,divide 函数用于执行除法运算。如果除数 b 为零,则会抛出 ZeroDivisionError 异常。在测试函数 test_divide 中,我们使用 pytest.raises 上下文管理器捕获该异常,并断言其异常信息是否与预期相符。
当运行 pytest 命令来执行测试时,它将检测到 divide 函数引发了 ZeroDivisionError 异常,并且断言通过。这表明异常处理机制正常工作。
assert x == y:判断x是否等于y
assert x != y:判断x是否不等于y
assert x > y:判断x是否大于y
assert x < y:判断x是否小于y
assert x >= y:判断x是否大于等于y
assert x <= y:判断x是否小于等于y
assert x 判断x为真
assert not x 判断x不为真
assert item in collection:判断item是否在collection中
assert item not in collection:判断item是否不在collection中
1、Pytest执行命令
pytest: 运行所有以test_*.py或*_test.py命名的文件中的测试函数。
pytest test_sample.py: 运行指定的test_sample.py文件中的测试函数。
pytest testing/: 运行指定目录下所有以test_*.py命名的文件中的测试函数。
pytest -k "test_B": 按关键字匹配运行包含test_B关键字的测试函数。
pytest test_sample.py::test_B: 运行指定的test_sample.py文件中的test_B函数。
pytest test_sample.py::TestClass::test_B: 运行指定的test_sample.py文件中的TestClass测试类中的test_B方法。
2、其他执行命令
pytest -q: 使用-q/--quiet标志可以使输出保持简短。
pytest -v: 显示每个测试用例的执行结果。
pytest -s: 用于显示测试函数中的print()函数输出。
pytest -x: 第一次遇到错误后停止测试。
pytest --maxfail=2: 遇到两次错误后停止测试。
pytest -rs: -rs选项可以显示测试报告的摘要,包括已跳过的测试、错误和失败的数量以及原因。
在使用 Pytest 进行单元测试时,你可以按照以下目录结构组织你的测试用例:
project/
├── src/
│ ├── module1.py
│ └── module2.py
└── tests/
├── test_module1.py
└── test_module2.py
你可以根据需要在 tests/ 目录下创建更多的测试用例文件,每个文件可以包含多个测试函数。在测试用例文件中,你可以使用 Pytest 提供的各种断言和装饰器来编写测试逻辑。
请注意,这只是一种常见的组织结构示例,你可以根据自己的项目需要进行调整和扩展。