pytest是python语言中一款强大的单元测试框架,用来管理和组织测试用例,可应用在单元测试、自动化测试工做中。html
unittest也是python语言中一款单元测试框架,可是功能有限,没有pytest灵活。python
就像:苹果电脑mac air 和mac pro同样。都是具有一样的功能,可是好用,和更好用。session
本文包含如下几个内容点:框架
1)pytest的简单示例dom
2)pytest的安装函数
3)pytest的特征、与unittest的区别。单元测试
4) pytest如何自动识别用例。测试
5)pytest框架中,用例的运行顺序。ui
1)pytest写用例很简单,下面是一个简单的例子:spa
1 import random 2 3 4 def test_demo(): 5 assert 7 == random.randint(0,10)
运行结果以下:
============================= test session starts ============================= platform win32 -- Python 3.7.2, pytest-4.6.3, py-1.8.0, pluggy-0.12.0 rootdir: D:\Pychram-Workspace\STUDY_PYTEST plugins: allure-pytest-2.6.5, html-1.21.1, metadata-1.8.0, rerunfailures-7.0collected 1 item simple.py F simple.py:10 (test_demo) 7 != 6 Expected :6 Actual :7 ========================== 1 failed in 0.14 seconds ===========================
2)pytest的安装
安装命令:pip install pytest
3)pytest的特征、与unittest的区别。
pytest的特征以下:
3.1 自动识别测试用例。(unittest当中,须要引入TestSuite,主动加载测试用例。)
3.2 简单的断言表达:assert 表达式便可。(unittest当中,self.assert*)
3.3 有测试会话、测试模块、测试类、测试函数级别的fixture。(unittest当中是测试类、测试函数级别的fixture)
3.4 有很是丰富的插件,目前在600+,好比allure插件。(unittest无)
3.5 测试用例不须要封装在测试类当中。(unittest中须要自定义类并继承TestCase)
那么pytest是如何自动识别测试用例的呢?咱们在编写pytest用例的时候,须要遵照哪些规则呢?
4) pytest如何自动识别用例
识别规则以下:
一、搜索根目录:默认从当前目录中搜集测试用例,即在哪一个目录下运行pytest命令,则从哪一个目录当中搜索;
二、搜索规则:
1)搜索文件:符合命名规则 test_*.py 或者 *_test.py 的文件
2)在知足1)的文件中识别用例的规则:
2.1)以test_开头的函数名;
2.2)以Test开头的测试类(没有__init__函数)当中,以test_开头的函数
示例:在D:\pycharm_workspace目录下,建立一个python工程,名为study_pytest。在工程下,建立一个python包,包名为TestCases。
在包当中,建立一个测试用例文件:test_sample_1.py。文件内容以下:
1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 # Name: test_sample_1.py 4 # Author: 简 5 # Time: 2019/6/27 6 7 # 定义py文件下的测试用例 8 def test_sample(): 9 print("我是测试用例!") 10 11 class TestSample: 12 13 def test_ss(self): 14 print("我也是测试用例!") 15 16 def hello_pytest(self): 17 print("hi,pytest,我不是用例哦!!")
按照上面定义的搜索规则,须要跳转到工程目录,而后再执行命令:pytest -v 。 执行结果以下:
让咱们愉快的加进来第2个测试文件:test_sample_2.py,内容以下:
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Name: test_sample_2 # Author: 简 # Time: 2019/6/27 def add(a,*args): sum = a for item in args: sum += item return sum def test_add_two_number(): assert 33 == add(11,22) assert 55.55 == add(22.22,33.33) def test_add_three_number(): assert 101 == add(10,90,1)
再次运行命令:pytest -v 获得以下结果:
经过多个用例文件的执行,能够看出用例的执行顺序。
5) pytest中用例的执行顺序
原则:先搜索到的py文件中的用例,先执行。在同一py文件当中,按照代码顺序,先搜索到的用例先执行。