1.pytest
pytest是一种自动化测试框架,pytest向下兼容unittest
命名规范 文件名以test开头,或者test结尾 类以Test开头,且类当中不能有init方法 方法或函数以test_开头 断言必须使用assert
assert 1==1 #判断等式两边是否相等
assert 100 #判断某个语句是否为真
assert 100 in [100,200] #判断某个值是否属于某个对象
assert 1!=2 #判断某个值是否不等于另一个值
assert not False #逻辑运算符not
pytest框架使用
import os
import allure
import pytest
class Test1:
def test_100(self):
print('******************test100*********************')
assert 1==2 #判断预期结果与实际结果是否一致
def test_200(self):
print('***********************test200**********************')
assert 6==6
if __name__ == '__main__':
pytest.main(['test_pytest1.py','-s']) #-s表示允许执行print语句
setup与teardown
setup在所有用例之前执行,teardown在所有用例之后执行 setup_method,teardown_method 执行顺序①②④①③④
class Test1:
def setup_method(self): #①
print('\n开始执行用例')
def test_100(self): #②
assert 1==2 #判断预期结果与实际结果是否一致
def test_200(self): #③
assert 6==6
def teardown_method(self): #④
print('\n用例执行完毕')
if __name__ == '__main__':
pytest.main(['test_pytest1.py','-s']) #-s表示允许执行print语句
setup_class,teardown_class 执行顺序①②③④,在每个类之前和之后执行
setup_module,teardown_module 在整个模块开始之前和之后执行
class Test1:
def setup_class(self): #①
print('\n开始执行用例')
def test_100(self): #②
assert 1==2 #判断预期结果与实际结果是否一致
def test_200(self): #③
assert 6==6
def teardown_class(self): #④
print('\n用例执行完毕')
if __name__ == '__main__':
pytest.main(['test_pytest1.py','-s']) #-s表示允许执行print语句
以@pytest.fixture()实现setup与teardown
import pytest
@pytest.fixture(scope='session') #装饰器,相当于setup,缺省值为function级
#scope可以加入参数scope='class',将级别改为class
#scope可以加入参数scope='module',将级别改为module
#scope='session' 使用这个级别时,将fixture的内容写到conftest.py文件中,目录下的所有文件都使用这个配置
def some_data():
print('开始')
yield #这个关键字之后的代码相当于teardown
print('结束')
def test_some_data(some_data):
assert 1==2
if __name__ == '__main__':
pytest.main(['test_example1.py','-s'])
pytest数据驱动
list1=[[1,2],[3,4],[2**25,33554432]]
class Test10: @pytest.mark.parametrize('result,real_result',list1)
def test_10(self,result,real_result):
assert result==real_result
if __name__ == '__main__':
pytest.main(['test_pytest1.py','-s'])
allure报告
1、下载allure.zip
2、解压allure.zip到一个文件目录中
3、将allure报告安装目录\bin所在的路径添加环境变量path中
4、pip install allure-pytest
list1=[[1,2],[3,4],[2**25,33554432]]
@allure.feature('层级1')
@allure.story('层级2')
@allure.title('层级3')
class Test10: @pytest.mark.parametrize('result,real_result',list1)
def test_10(self,result,real_result):
assert result==real_result
if __name__ == '__main__':
pytest.main(['test_pytest1.py','-s','--alluredir','./report']) #-s表示允许执行print语句
os.system('allure generate ./report -o ./report/report --clean') #生成allure报告
第二节课