以下总结基于:
7.2.x
官网:https://docs.pytest.org/en/7.2.x/
$ pip install -U pytest
$ pytest --version
pytest 7.2.0
$ pytest --version # 查看`pytest`版本(或检查是否安装成功)
$ pytest --fixtures # 查看`pytest`自带的函数
$ pytest -h | --help # 获取帮助
$ pytest --durations=10 --durations-min=1.0 # 获取测试执行时间大于1秒的10个用例
$ pytest -p some_plugins # 提前加载插件
$ pytest -p no:some_plugins # 禁用插件
按照以下命名规则,
pytest
会自动找到(collect
)并导入(import
)
测试文件(
module
)名称
test_*.py
*_test.py
测试函数(
function
)名称
- func test_xxx()
测试类(
class
)名称
- class TestXXX()
- 按
module
执行测试
pytest test_*.py- 运行某个目录下的所有测试
pytest testing/ # pytest会自动导入(import
)当前目录或其子目录下的以test_*.py
或*_test.py
的测试文件- 按关键字执行(按提供的字符串
不区分大小写模糊匹配
,会自动匹配module
/class
/func
)
pytest -k “test_file_names/class_names/function_names
”
- 【特别的】pytest -k “类名
and not
方法名”
- 模糊匹配含“类名”的所有类,并匹配到这些类下的所有方法
- 排除含”方法名“的方法
- 按
node ids
执行测试
node ids
组成:由文件名、类名、方法名、参数组成,使用::
分隔- 执行
module
下的某个func
- pytest test_mod.py::test_func
- pytest test_mod.py::TestClass::test_func
- 按
marker
执行测试
- pytest -m
marker_name
- marker定义方法:加上
@pytest.mark.marker_name
的语法糖即可- 按
packages
执行测试
- Pytest --pyargs pkg.testing