本文介绍如何使用Python进行数据驱动。这里以pytest测试框架为例,重点讲解pytest参数化相关知识。(pytest的环境配置和基本使用不在本文讨论范围内。)pytest使用@pytest.mark.parametrize这个标签来实现参数化功能。在执行一个用例时,标签迭代中的每组数据都会作为一个用例来执行。一组参数化数据定义参数化数据,代码如下:classTestDemo1:@pytest.mark.parametrize('actual_string,expect_string',[(1,1),('BB','BB'),('AA','BB')])deftest_1(self,actual_string,expect_string):assert(expect_string==actual_string)结果如下,三个测试用例跑三组数据,数据('AA','BB')无法运行!多组参数化数据在一个测试类中,可以定义多组参数化数据(参数化数据的个数不同,test_1两个,test_2三个),代码如下:classTestDemo1:@pytest.mark.parametrize('actual_string,expect_string',[(1,1),('BB','BB'),('AA','BB')])deftest_1(self,actual_string,expect_string):assert(expect_string==actual_string)@pytest。mark.parametrize('result,a,b',[(1,1,0),(2,1,0)])deftest_2(self,result,a,b):assert(result==a+b)运行结果如下。两组数据分别在test_1和test_2中运行!我们可以自定义一些方法,从excel中读取数据作为参数,读取外部文件,然后将读取到的数据作为pytest中的参数。将测试数据保存在excel中,如下图,写一个读取excel类文件的方法,使用模块pandas,使用命令pipinstallpandas安装模块,源码如下:importpandasaspd#ReadExcelfiles--Pandasdefread_data_from_pandas(excel_file,sheet_name):ifnotos.path.exists(excel_file):raiseValueError("Filenotexists")s=pd.ExcelFile(excel_file)df=s.parse(sheet_name)#解析sheet页面的数据returndf.values.tolist()#数据以列表的形式返回,从excel中读取数据,并为变量赋值,进行参数化。代码如下:@pytest.mark.parametrize('actual_string,expect_string',read_data_from_pandas('E:/TestData.xls','data1'))deftest_3(self,actual_string,expect_string):assert(expect_string==actual_string)结果如下,三个测试用例跑三组数据!注意:excel中第一行默认不会作为测试数据处理。
