pytest参数化

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

conftest.py
image
test_fixture.py
image

执行
image
上面参数化的数据是通过一个函数来动态生成,每次得到一组参数传递给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
image
test_fixture.py
image
执行
image

这里也可以直接把数据放在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个表,一个存储用例,一个存储数据库配置信息
image
image

数据库
image

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
image

执行
image

posted @   工作手记  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示