pytest 默认收集名字以 test 开头的函数、以及 Test 开头的类里的 test_* 方法。方法名不要用 pytest 当开头,会和内置撞车。
跑起来
在项目目录:
bash
pytest -vv test_demo.py
pytest -vv不写文件名,就按配置收集当前目录。-vv 把每条用例的名字打出来,失败时比较好看。
同一条逻辑、多组数据
python
import pytest
def add(a, b):
return a + b
@pytest.mark.parametrize(
"a, b, expected",
[
(1, 1, 2),
(2, 2, 4),
(2, 3, 5),
],
)
def test_add(a, b, expected):
assert add(a, b) == expected一组数据失败,不会拖死其它组。
分组跑
pytest.ini:
ini
[pytest]
markers =
smoke: 冒烟
slow: 慢用例用例上打标记:
python
@pytest.mark.smoke
def test_login():
assert True只跑这一组:
bash
pytest -vv -m smoke未知 marker 现在会警告。长期用的标记,都写进 pytest.ini。