下面从入门到常用技巧,教你如何用 Python 的 pytest 写测试。
pip install pytest
验证:
pytest --version
calc.py
def add(a, b):
return a + b
测试文件通常以 test_ 开头,或位于 tests/ 目录中。
test_calc.py
from calc import add
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
pytest
或指定文件:
pytest test_calc.py
pytest 使用 Python 原生 assert,但失败信息更友好:
def test_example():
assert 1 + 1 == 2
assert "hello" in "hello world"
避免写多个重复测试函数。
import pytest
from calc import add
@pytest.mark.parametrize(
"a,b,expected",
[
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
],
)
def test_add(a, b, expected):
assert add(a, b) == expected
import pytest
def div(a, b):
return a / b
def test_div_zero():
with pytest.raises(ZeroDivisionError):
div(1, 0)
import pytest
@pytest.fixture
def sample_data():
return {"name": "pytest"}
def test_sample(sample_data):
assert sample_data["name"] == "pytest"
@pytest.fixture
def db():
print("connect db")
yield "db_connection"
print("close db")
class TestCalc:
def test_add(self):
assert 1 + 1 == 2
def test_sub(self):
assert 3 - 1 == 2
pytest -v # 详细输出
pytest -k add # 只跑名字含 add 的测试
pytest -x # 第一个失败就停
pytest --maxfail=2 # 最多失败 2 次
pytest test_calc.py::test_add
project/
├── calc.py
├── tests/
│ ├── test_calc.py
│ └── test_utils.py
└── pytest.ini
pytest.ini
[pytest]
testpaths = tests
# calc.py
def add(a, b):
return a + b
# tests/test_calc.py
import pytest
from calc import add
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(2, 3, 5),
])
def test_add(a, b, expected):
assert add(a, b) == expected
运行:
pytest -v
如果你愿意,我可以:
你现在是打算测试什么类型的代码?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。