Python中如何使用pytest()进行单元测试
发布时间:2024-01-02 23:09:58
pytest是一个用于编写简单而又可扩展的Python单元测试的框架。它具有很多功能,包括自动发现测试模块和测试方法、断言测试结果、参数化测试等。
在使用pytest进行单元测试时,需要遵循以下几个步骤:
1. 安装pytest:
pip install pytest
2. 编写测试代码:
pytest要求测试代码必须以test_开头,并且测试方法也必须以test_开头。下面是一个简单的示例:
# test_calc.py
def add(x, y):
return x + y
def test_add():
assert add(1, 2) == 3
assert add(-1, -1) == -2
assert add(0, 0) == 0
3. 运行测试:
在命令行中进入测试代码所在的目录,然后运行以下命令:
pytest
pytest将自动发现并执行该目录下的所有测试代码。
4. 查看测试结果:
pytest会输出测试结果的摘要,包括测试用例的数量和通过的数量。如果有测试未通过,它们将被列出。
下面是一个完整的例子,展示了如何使用pytest进行单元测试:
# calc.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
# test_calc.py
import pytest
from calc import add, subtract
def test_add():
assert add(1, 2) == 3
assert add(-1, -1) == -2
assert add(0, 0) == 0
def test_subtract():
assert subtract(3, 2) == 1
assert subtract(5, 7) == -2
assert subtract(0, 0) == 0
def test_invalid_input():
with pytest.raises(TypeError):
add(1, '2')
在示例中,calc.py中定义了两个简单的计算函数,而test_calc.py中定义了三个测试方法,分别对应了add函数、subtract函数和异常情况的测试。
运行pytest命令后,会输出以下结果:
=========== test session starts =========== platform darwin -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y rootdir: /path/to/test/calc collected 3 items test_calc.py ... [100%] =========== X passed, X warnings in X seconds ===========
表示共有3个测试用例,全部通过。
通过pytest的assert语句,可以在测试中进行断言,来验证预期的测试结果是否与实际结果一致。
除了简单的断言外,pytest还支持参数化测试,可以通过@pytest.mark.parametrize装饰器来实现。
下面的例子演示了如何使用参数化测试:
# test_calc.py
import pytest
from calc import add
@pytest.mark.parametrize('a, b, expected', [
(1, 2, 3),
(-1, -1, -2),
(0, 0, 0),
])
def test_add(a, b, expected):
assert add(a, b) == expected
在该示例中,test_add方法通过@pytest.mark.parametrize装饰器,为add函数提供了多组参数,并且验证了计算结果。
通过以上介绍,你应该已经了解了如何使用pytest进行单元测试,以及它的一些基本用法。在实际应用中,你可以根据需要继续研究pytest的更多高级用法,例如各种fixture的使用、测试覆盖率等。
