pytest官网
参考:link
pytest安装
pip install pytest
pytest案例规则
pytest --help 可以查看pytest的帮助文档
C:\Users\Administrator>pytest --help
usage: pytest [options] [file_or_dir] [file_or_dir] […]
运行pytest时可以指定目录和文件,如果不指定,pytest会搜索配置文件testpaths 定义的目录或者当前目录及其子目录中以test_开头或以_test结尾的py文件
[file_or_dir]可以指定文件或者目录
我们把pytest搜索测试文件和测试用例的过程称为测试搜索(test discovery),只要遵守pytest的命名规则,pytest就能自动搜索所有待执行的测试用例,规则如下:
(1)测试文件应当命名为test_.py或者test.py,一定要以test_开头或者结尾,下划线不能省略
(2) 测试函数、测试类方法应当命名为test
(3)测试类应当命名为Test,并且不能有__init__方法
如何运行pytest—pytest命令行参数
-v : --verbose increase verbosity 显示详细信息
使用这个参数,就可以详细展示出每个测试用例的运行结果
collected 2 items
test_simpleexample.py::test_inc PASSED [ 50%]
test_simpleexample.py::test_inc2 FAILED
–collect-only : 展示哪些用例会被运行,只展示案例不运行
collected 2 items
<Package pytestlearn>
<Module test_simpleexample.py>
<Function test_inc>
<Function test_inc2>
-k: 使用表达式指定需要运行的案例 ,可以使用 or and等
比如:两条测试用例的名字时test_asdict()和test_defaults(),使用–k这参数时
pytest -k "asdict or defaults"
-m: 指定标记来运行
测试用例可以使用pytest.mark.mock或者pytest.mark,regression这样的装饰器来标记分组测试用例,使用参数-m就可以选择标记来运行
如,需要运行标记为冒烟阶段的测试用例 pytest -m “mock”
-m后面跟一个字符串,字符串可以使用and or not等
如下是一个简单的测试用例,使用pytest.mark.mock和pytest.mark.regression来标记哪些是冒烟测试用例,哪些是regression的测试用例
import pytest
def inc(x):
return x+1
def test_inc():
assert inc(5)==6
def test_inc2():
assert inc(3)==7
@pytest.mark.mock
def test_mock_01():
assert inc(1)==2
@pytest.mark.mock
def test_mock_02():
assert inc(3)==4
@pytest.mark.regression
def test_regression_01():
assert inc(3)==4
- 如果想要只运行冒烟测试用例
sh-3.2$ pytest -m "mock"
========================================================