pytest参数化
1 利用pytest.mark.parametrize来参数化
conftest.py

test_fixture.py

执行

上面参数化的数据是通过一个函数来动态生成,每次得到一组参数传递给test函数的3个变量
也可以直接把数据放在变量名后面
all_data = [
[1,1,2],
[2,2,4],
[3,3,6]
]
@pytest.mark.parametrize('x,y,z',all_data)
def test_xx(x,y,z)
xxx
2 利用fixture来参数化
conftest.py

test_fixture.py

执行

这里也可以直接把数据放在params
all_data = [
[1,1,2],
[2,2,4],
[3,3,6]
]
@pytest.fixture(params=all_data)
def fixture_xx(request)
data = request.param
用request.param可以每次取得一组参数传到fixture,通过fixture把参数传递给test函数
生产参数的函数一定要用yield来返回值,不能用return
例子:从excel读取关于数据库查询用例,验证数据字段值
excel文件有2个表,一个存储用例,一个存储数据库配置信息


数据库

conftest.py
from openpyxl import load_workbook
import pymysql,logging
def load_excel_content(tb="cases"):
wb = load_workbook(r".\resource\test_data.xlsx")
#用例表
if tb == "cases":
if wb:
#拿到excel文件的第一张表
sheet_name = wb.get_sheet_names()[0]
ws = wb[sheet_name]
else:
ws = None
if ws:
for line in ws.iter_rows(min_row=2, max_col=ws.max_column, max_row=ws.max_row, values_only=True):
#for line in ws.values:
#sql的表达式,则返回 用正则
print(f'type(line): {type(line)}, line: {line}')
yield line
#db表
elif tb =="db":
if wb:
#拿到excel文件的第一张表
sheet_name = wb.get_sheet_names()[1]
ws = wb[sheet_name]
else:
ws = None
#db_data = []
if ws:
for line in ws.iter_rows(min_row=2, max_col=ws.max_column, max_row=ws.max_row, values_only=True):
#for line in ws.values:
print(f'type(line): {type(line)}, line: {line}')
#db_data.append(line)
yield line
#return db_data
@pytest.fixture(scope='session',params=load_excel_content('db'))
def mysql_connection(request):
logging.info("go to the fixture mysql")
db_data = request.param
logging.info(f"db_data: {db_data}")
user = db_data[2]
pd = db_data[3]
db = db_data[4]
port = db_data[1]
host = db_data[0]
conn = pymysql.connect(host=host,user=user,passwd=pd,database=db,port=int(port))
cursor = conn.cursor()
#return cursor
yield cursor
logging.info("teardown,closing the mysql connection")
conn.close()
@pytest.fixture(params=load_excel_content('cases'))
def get_excel_data(request):
line = request.param
logging.info(f"line {line}")
yield line
logging.info('teardow: fixture,get_excel_data ')
test_fixture.py

执行


浙公网安备 33010602011771号