Python总结----Pytest实现数据驱动测试(二)
使用Excel进行数据驱动测试
新建一个名叫ExcelDataDrivenProject的Python工程,在工程下新建两个文件名分别为ExcelUtil.py、DataDriven.py的文件
其中ExcelUtil.py中代码如下:
1 # encoding = utf-8 2 from openpyxl import load_workbook 3 4 class ParseExcel(object): 5 def __init__(self, excelPath, sheetName): 6 """ 7 初始化方法,接收文件路径和工作表名称 8 :param excelPath: Excel 文件的路径 9 :param sheetName: 工作表名称 10 """ 11 self.excelPath = excelPath 12 self.sheetName = sheetName 13 self.wb = load_workbook(self.excelPath) # 将要读取的数据加载到内存 14 self.sheet = self.wb[self.sheetName] # 通过工作表明获取工作对象 15 self.maxRowNum = self.sheet.max_row # 获取工作表中存在数据区域的最大行号 16 17 def getDatasFromSheet(self): 18 """ 19 从工作表中读取数据 20 :return: 包含从工作表中读取出来的数据的列表 21 """ 22 dataList = [] # 定义用于存放从工作表中读取出来的数据 23 rows_data = list(self.sheet.iter_rows(values_only=True)) # 获取表中所有行的数据 24 for line in rows_data[1:]: # 第一行为标题数据需要排除 25 tmpList = [] 26 for cell in line: 27 tmpList.append(cell) 28 dataList.append(tmpList) 29 return dataList 30 31 if __name__ == "__main__": 32 excelPath = "D:\\user\\Downloads\\纸箱耗材导入模板.xlsx" 33 sheetName = "Sheet0" 34 pe = ParseExcel(excelPath, sheetName) 35 for row in pe.getDatasFromSheet(): 36 print(row)
DataDriven.py中代码如下:
1 import pytest 2 from openpyxl import load_workbook 3 4 # 读取 Excel 文件中的测试数据 5 def read_excel_data(file_path, sheet_name): 6 workbook = load_workbook(file_path) 7 sheet = workbook[sheet_name] 8 test_data = [] 9 10 # 跳过标题行,从第二行开始读取数据 11 for row in sheet.iter_rows(min_row=2, values_only=True): 12 test_data.append((row[1], row[2])) # 假设第二列是输入,第三列是期望输出 13 14 return test_data 15 16 # 测试函数 17 def add(a, b): 18 return a + b 19 20 # 使用 pytest.mark.parametrize 动态生成测试用例 21 def test_addition(request): 22 test_data = read_excel_data('test_data.xlsx', 'Sheet1') 23 input_value, expected_output = request.param 24 assert add(input_value, input_value) == expected_output 25 26 # 生成测试用例 27 test_cases = read_excel_data('test_data.xlsx', 'Sheet1') 28 test_ids = [f"Test Case {i+1}" for i in range(len(test_cases))] 29 30 @pytest.mark.parametrize("test_addition", test_cases, ids=test_ids, indirect=True) 31 def test_all_cases(test_addition): 32 pass # 实际测试逻辑在 test_addition 中
使用数据库进行驱动测试
1 import pytest 2 import mysql.connector 3 from mysql.connector import Error 4 5 # 数据库连接配置 6 DB_CONFIG = { 7 'host': 'localhost', 8 'database': 'test_db', 9 'user': 'your_username', 10 'password': 'your_password' 11 } 12 13 def get_db_connection(): 14 """创建并返回数据库连接""" 15 try: 16 connection = mysql.connector.connect(**DB_CONFIG) 17 return connection 18 except Error as e: 19 print(f"数据库连接错误: {e}") 20 return None 21 22 def fetch_test_data(): 23 """从数据库获取测试数据""" 24 connection = get_db_connection() 25 if connection is None: 26 return [] 27 28 cursor = connection.cursor() 29 try: 30 cursor.execute("SELECT input_value, expected_result FROM test_data") 31 test_data = cursor.fetchall() 32 return test_data 33 except Error as e: 34 print(f"查询数据错误: {e}") 35 return [] 36 finally: 37 if cursor: 38 cursor.close() 39 if connection: 40 connection.close() 41 42 @pytest.mark.parametrize("input_value,expected_result", fetch_test_data()) 43 def test_multiply_by_two(input_value, expected_result): 44 """测试输入值乘以2是否等于预期结果""" 45 result = input_value * 2 46 assert result == expected_result, f"输入值 {input_value} 乘以 2 应该等于 {expected_result},但得到了 {result}" 47 48 def test_database_connection(): 49 """测试数据库连接是否正常""" 50 connection = get_db_connection() 51 assert connection is not None, "数据库连接失败" 52 if connection: 53 connection.close()
浙公网安备 33010602011771号