前言:之前在网上查了不少关于pytest的资料,总结了一下pytest比较重要的点:
1、可以更好的控制测试用例
2、支持很多第三方插件,并可以自定义扩展
3、执行失败的测试用例可以重复执行
4、可以很好的与jenkins结合
5、需要遵循pytest框架的一些用例设计原则,以便更好的识别case:
1)测试文件名需要满足test_*.py或*_test.py文件格式
2)测试类以Test开头,并且不能带有 init 方法
3)测试函数/方法以test_开头
4)断言使用assert xxxxx即可
一、断言
首先从简单的断言开始,-s表示执行,-q即-quiet,作用是减少冗长,不在展示pytest的版本信息
import pytestdef test_01():print('hello pytest')assert 1>2def test_02():assert 1if __name__ == '__main__':pytest.main(["-s",'-q','test_seven.py'])
![7192a383fa1ed986d0e7b8310997b21e.png](https://img-blog.csdnimg.cn/img_convert/7192a383fa1ed986d0e7b8310997b21e.png)
二、setup/teardown函数
用法:运行于测试方法的始末,并且每个测试函数都会执行一次
import pytest#setup_class,teardown_class表示前后只执行一次#setup,teardown表示每个case都执行一次class Test_Pytest:def setup(self): print("------->setup")def teardown(self): print("------->teardown")def test_01(self):print('hello pytest')assert 1>2def test_02(self):assert 1 ==1if __name__ == '__main__':pytest.main(['-s','-q','test_six.py'])
![dd8097700b0cb76505560ea9ede0f318.png](https://img-blog.csdnimg.cn/img_convert/dd8097700b0cb76505560ea9ede0f318.png)
三、setup_class/teardown_class函数
用法:运行于测试方法的始末,并且每个测试类都会执行一次
import pytest#setup_class,teardown_class表示前后只执行一次#setup,teardown表示每个case都执行一次class Test_one:def setup_class(self): print("------->setup_class")def teardown_class(self): print("------->teardown_class")def test_01(self):print('hello pytest')assert 1>2def test_02(self):assert 1 ==1class Test_two:def setup_class(self):print("=========>setup_class")def teardown_class(self):print("=========>teardown_class")def test_03(self):assert 1def test_04(self):assert 10>100if __name__ == '__main__':pytest.main(['-s','-q','test_six.py'])
![3365e752b8f7d0bb85a8057417c33222.png](https://img-blog.csdnimg.cn/img_convert/3365e752b8f7d0bb85a8057417c33222.png)
总结
上面三点是pytest基本用法,后面会继续介绍pytest的精髓fixture装饰器