直接执行 如下命令即可安装 pytest
pip install pytest
用例收集顺序:
unittest:TestLoader+Testsuit 使用discover收集用例
pytest :自动收集
1.先收集同级别的,在收集子文件夹下的。
2.同级别的根据ASCII码先后顺序执行,同py文件下的根据方法的先后顺序执行。
前置后置:
unittest :setup 、teardwon setupclass 、teardwonclass(固定写法)
pytest:使用fixture任意定义方法名
function(方法(默认))---class(类(整个类中只执行一次))---module(.py)--session(所有用例)
调用前后置:
运行结果:
获取前置的返回值:直接在yield后面接返回值,调用处的形参中调用fixture的方法名。
运行后结果:
注:当fixture有返回值,且测试用例有用到该参数时,可以不写@pytest.mark.usefixtures
session级别的前后置:
使用session前置的返回值:
运行后结果:
用例筛选:
1.项目根目录创建pytest.ini文件
2.文件中使用如下格式,smorke后面为注解,仅可以使用英文
[pytest] markers= smorke: only use english demo
3.在需要筛选的类或者方法上添加注解@pytest.mark.demo
4.命令行:pytest -s -v -m demo即可执行所有demo注解下的用例
conftest.py(固定文件名) 专门用来存放fixture
所在目录下全局都可以使用该fixture,如果当前目录下没有conftest.py会自动向上一级找
结果:
fixture使用fixture的值:
结果:
参数化:
#@pytest.mark.parammetrize("参数名",列表数据)
@pytest.mark.parammetrize("data",xxx_data)
def test_xxx(data):
print(data)
重运行:pip install pytest-rerunfailures
pytest --reruns 2(重运行次数) --reruns-delay 3(次数之间的延迟时间)
报告:pip install pytest-html
我们还需要产生测试报表,所以要安装一个第三方插件 pytest-html
,执行如下命令安装
pip install pytest-html
在pycharm命令行直接输入pytest ,就会执行项目下的所有以test_,或者以_test结尾的方法或类
可以输入pytest xxx yyy.py(xxx为指定文件夹,yyy指定文件)执行指定文件下的以test_,或者以_test结尾的方法或类
pytest --html=report.html 生成一个report.html在项目的根目录下