当前位置:主页 > 查看内容

测试驱动技术(TDD)系列之-pytest实现测试数据驱动

发布时间:2021-05-24 00:00| 位朋友查看

简介:本篇文章则介绍如何使用Python进行数据驱动。这里以pytest测试框架为例,重点讲解pytest参数化相关知识。(关于pytest的环境配置以及基础使用不在本文的讨论范围) pytest中使用标签@pytest.mark.parametrize 实现参数化功能,在执行用例的时候该标签迭代中的……

本篇文章则介绍如何使用Python进行数据驱动。这里以pytest测试框架为例,重点讲解pytest参数化相关知识。(关于pytest的环境配置以及基础使用不在本文的讨论范围)

pytest中使用标签@pytest.mark.parametrize 实现参数化功能,在执行用例的时候该标签迭代中的每组数据都会作为一个用例执行。

一组参数化数据

定义参数化数据,代码如下:

  1. class TestDemo1: 
  2. @pytest.mark.parametrize('actual_string, expect_string', [(1, 1), ('BB''BB'),('AA''BB')]) 
  3.  
  4.       def test_1(self, actual_string, expect_string): 
  5.  
  6.            assert (expect_string == actual_string) 

运行结果如下,三组数据在三条测试用例中运行,其中数据('AA', 'BB')运行失败!


多组参数化数据

在一个测试类中,可以定义多组参数化数据(参数化数据个数不同,test_1二个,test_2三个),代码如下:

  1. class TestDemo1: 
  2.  
  3.    @pytest.mark.parametrize('actual_string, expect_string', [(1, 1), ('BB''BB'),('AA''BB')]) 
  4.  
  5.    def test_1(self, actual_string, expect_string): 
  6.  
  7.        assert (expect_string == actual_string) 
  8.  
  9.  
  10.    @pytest.mark.parametrize('result, a,b', [(1, 1,0),(2, 1,0) ]) 
  11.  
  12.    def test_2(self, result, a,b): 
  13.  
  14.        assert (result == a+b) 

运行结果如下,二组数据分别在test_1和test_2中运行!


从excel中读取数据作为参数

我们可以自定义一些方法,对外部文件进行读取,然后把读取的数据作为参数在pytest

中引用。把测试数据保存在excel中,如下图


写一个读取excel类文件的方法,使用模块pandas ,使用命令pip install pandas 安装模块,源码如下:

  1. import pandas as pd 
  2.  
  3. # 读取Excel文件 -- Pandas 
  4.  
  5. def read_data_from_pandas(excel_file, sheet_name): 
  6.  
  7.     if not os.path.exists(excel_file): 
  8.  
  9.         raise ValueError("File not exists"
  10.  
  11.     s = pd.ExcelFile(excel_file) 
  12.  
  13.     df = s.parse(sheet_name)#解析sheet页的数据 
  14.  
  15.     return df.values.tolist()#数据返回为list 

从excel中读取数据,并赋值给变量进行参数化,代码如下:

  1. @pytest.mark.parametrize('actual_string, expect_string', read_data_from_pandas('E:/TestData.xls''data1')) 
  2.  
  3. def test_3(self, actual_string, expect_string): 
  4.  
  5.     assert (expect_string == actual_string) 

运行结果如下,三组数据在三条测试用例中运行!


注意:excel中的首行,默认不会作为测试数据处理。


本文转载自网络,原文链接:https://www.toutiao.com/i6926715256693621255/
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐