您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
使用 pytest
编写单元测试是一个相对简单且强大的过程。以下是一些基本步骤和示例,帮助你开始使用 pytest
进行单元测试。
首先,你需要安装 pytest
。你可以使用 pip
来安装:
pip install pytest
假设你有一个简单的 Python 模块 math_utils.py
,其中包含一些数学函数:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
接下来,你需要编写测试用例。测试用例通常放在一个以 test_
开头的文件中,例如 test_math_utils.py
。
# test_math_utils.py
from math_utils import add, subtract, multiply, divide
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(-1, -1) == -2
def test_subtract():
assert subtract(5, 3) == 2
assert subtract(0, 0) == 0
assert subtract(-1, -1) == 0
def test_multiply():
assert multiply(2, 3) == 6
assert multiply(-1, 1) == -1
assert multiply(-1, -1) == 1
def test_divide():
assert divide(6, 3) == 2
assert divide(0, 1) == 0
assert divide(-6, 3) == -2
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(1, 0)
在命令行中,导航到包含 test_math_utils.py
文件的目录,然后运行 pytest
:
pytest
pytest
会自动发现并运行所有以 test_
开头的函数,并报告测试结果。
pytest
会输出测试结果,包括通过的测试和失败的测试。例如:
============================= test session starts ==============================
...
collected X items
test_math_utils.py::test_add PASSED [ 33%]
test_math_utils.py::test_subtract PASSED [ 66%]
test_math_utils.py::test_multiply PASSED [100%]
============================== X passed in X.XXs ===============================
pytest
提供了许多高级功能,例如:
@pytest.mark.parametrize
装饰器来运行相同的测试函数,但使用不同的输入。pytest
的功能。# test_math_utils_with_fixture.py
import pytest
from math_utils import add
@pytest.fixture
def setup_data():
return 2, 3
def test_add(setup_data):
a, b = setup_data
assert add(a, b) == 5
# test_math_utils_parametrized.py
import pytest
from math_utils import add
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(-1, 1, 0),
(-1, -1, -2),
])
def test_add_parametrized(a, b, expected):
assert add(a, b) == expected
通过这些步骤和示例,你应该能够开始使用 pytest
编写和运行单元测试了。更多详细信息和高级功能,请参考 pytest 官方文档。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。