Web自动化测试(10)- 参数化与数据驱动

Web自动化测试(10)- 参数化与数据驱动 参数化与数据驱动1 ddt针对unittest框架1.1 安装第三方包pip install ddt1.2 核心修饰器1ddt装饰测试类标记该类支持数据驱动2data(数据列表)传入测试数据用于解包列表3unpack解包每组数据将列表 / 元组拆分为单个参数1.3 示例代码import unittest import csv from ddt import data, unpack, ddt ​ def read_csv_data(csv_file): test_data [] with open(csv_file, r, encodingutf-8) as file: reader csv.reader(file) next(reader) for row in reader: test_data.append(row) return test_data ddt class TestLogin(unittest.TestCase): data(*read_csv_data(../data/login_data.csv)) unpack def test_login_fail(self,test_name,username: str,password: str,msg: str): print(f执行{test_name}...) self.driver.find_element(By.ID,username).send_keys(username) self.driver.find_element(By.ID,password).send_keys(password) self.driver.find_element(By.CLASS_NAME,J-login-submit).click() excepted_msg self.driver.find_element(By.CLASS_NAME,layui-layer-content).text assert msg in excepted_msg2 parameterized多框架兼容2.1 安装第三方包pip install parameterized2.2 核心装饰器parameterized.expand(数据列表)直接装饰测试方法2.3 支持框架unittest/pytest/nose 通用2.4 示例代码import unittest from parameterized import parameterized ​ class TestLogin(unittest.TestCase): # 测试数据 login_data [ (user1, pass1, 登录成功), (user2, wrong, 密码错误) ] ​ parameterized.expand(login_data) def test_login(self, username, password, expected): actual 登录成功 if (username user1 and password pass1) else 密码错误 self.assertEqual(actual, expected)3 pytest.mark.parametrizepytest 内置3.1 核心装饰器pytest.mark.parametrize(参数名1,参数名2, 数据列表)3.2 示例代码import pytest import pandas as pd ​ pytest.mark.parametrize(query_data,trem_data,limit_data,msg,[ tuple(row) for row in pd.read_csv(../data/search.csv).values ]) def test_login(self,query_data,trem_data,limit_data,msg): ......4 pytest.fixture (params[])pytest 内置4.1 核心语法通过fixture的params参数传入数据测试方法通过request对象获取参数4.2 示例代码import pytest ​ # 定义带参数的fixture pytest.fixture(params[ (user1, pass1, 登录成功), (user2, wrong, 密码错误) ]) def login_data(request): return request.param # 返回每组参数 ​ # 测试方法使用fixture def test_login(login_data): username, password, expected login_data actual 登录成功 if (username user1 and password pass1) else 密码错误 assert actual expected