方法:@pytest.mark.prameterize(args_name,arge_value)
args_name:参数名
args_value:参数值(一般为list,tuple,字典列表,字典元组等)有多少个值,用例执行多少次。
import pytest
class TestLoge:
@pytest.mark.parametrize('args', ['admin', 'ceshi', 'test'])
# 一个变量
def test_loging1(self, args):
print(args)
# 多个变量
@pytest.mark.parametrize('name1, name2, name3', [['admin1', 'ceshi1', 'test1'], ['admin2', 'ceshi2', 'test2']])
def test_loging2(self, name1, name2, name3):
print(name1, name2, name3)
Excel读取:xlrd,openpyxl
import openpyxl
def read_excel(excel_url, sheet_name):
# 加载Excel
wb = openpyxl.load_workbook(excel_url)
# 获取sheet的数据
sheet = wb[sheet_name]
# print(sheet)
# 打印sheet最大行数和列数
# print(sheet.max_row, sheet.max_column)
# 读取Excel数据,组成列表格式的数据。
# 行数循环
row_list = []
# 从第二行开始获取Excel数据:2, sheet.max_row + 1
for row in range(2, sheet.max_row + 1):
# print(row)
col_list = []
if sheet.cell(row, 5).value == 'y':
# 获取每一行数据
for col in range(1, sheet.max_column + 1):
# print(' '+str(col))
# 把每行数据按照列组成列表
col_list.append(sheet.cell(row, col).value)
# print(col_list)
# 把每一行数据按照列组成嵌套列表
row_list.append(col_list)
print(row_list)
return row_list
if __name__ == '__main__':
read_excel('./testcase.xlsx', 'test_01_login')
用例层代码修改:
import time
import allure
import pytest
from selenium import webdriver
from login_page import LoginPage
from excel_util import read_excel
# import unittest
class TestLogin:
def setup_class(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(3)
def tearDown(self) -> None:
time.sleep(1)
@pytest.mark.parametrize('caseinfo', read_excel('./Utest/testcase.xlsx', 'test_01_login'))
def test_01_login(self, caseinfo):
try:
lp = LoginPage(self.driver)
lp.login_ecshop(caseinfo[2], caseinfo[3])
# 断言 1 =2
# assert 1 == 2
except Exception as e:
# 报存错误截图
file_path = r".\error_image\login.png"
self.driver.save_screenshot(file_path)
# 把错误截图加入到allure报告
with open(file_path, mode='rb') as f:
allure.attach(f.read(), 'login.png', allure.attachment_type.PNG)