pytest参数化数据驱动(数据库/execl/yaml)

常见的数据驱动

数据结构:

列表、字典、json串

文件:

txt、csv、excel

数据库:

数据库链接

数据库提取

参数化:

@pytest.mark.parametrize()

@pytest.fixture()

参数化

  • 数据驱动和@pytest.mark.parametrize参数化结合

1.数据库驱动(已安装MySQL)

安装mysqlclient模块

复制代码
brew install mysql pkg-config //windows不用该步骤
pip3 install mysqlclient

import MySQLdb  # 必须要安装mysqlclient模块
import pytest

# 数据库链接
conn = MySQLdb.connect(
    user='root',
    passwd='m****',
    host='localhost',
    port=3306,
    db='basejnu'  # 数据库database
)


def get_data():
    query_sql = "select customer_id,account_num,customer_region_id from customer LIMIT 20"  # 获取数据
    lst = []
    cursor = conn.cursor()  # 创建游标
    try:
        cursor.execute(query_sql)
        r = cursor.fetchall()  # 获取customer_id,account_num数据
        print(r)
        for x in r:
            u = (x[0], x[1])  # 第一列和第二列
            lst.append(u)
        return lst
    finally:
        cursor.close()
        conn.close()


@pytest.mark.parametrize('customer_id,account_num', get_data())
def test01(customer_id, account_num):
    print(customer_id, account_num)


if __name__ == '__main__':
    pytest.main(["-sv", "get_mysql.py"])

运行效果:

2. execl/csv数据驱动

安装pandas模块

复制代码
pip3 install pandas

import pandas as pd
import pytest


def get_data():
# execl文件将 read_csv改为 read_execl即可
    df = pd.read_csv('/Users/mac/Documents/study23/data_study/data/customer1997.csv', index_col=None)
    data = pd.DataFrame(df)  # 转化为列表
    data00 = data[['customer_id', 'Frequency']]  # 获取所需部分
    # data01 = data00.head()  # 获取全部数据
    data01 = data00.head(5)  #获取前5行数据
    print(data01)
    data02 = data01.values
    print(data02)
    return data02


class Test_csv():
    @pytest.mark.parametrize('id,fre', get_data())
    def test_002(self, id, fre):
        print(id)
        print(fre)
        print("*"*10)


if __name__ == '__main__':
    pytest.main(["-sv", "get_execl.py"])

运行效果:

3. yaml数据驱动

data_y.yaml

yaml_util.py

复制代码
import yaml


class YamlUtil:
    def __init__(self, yaml_file):
        """
        通过init方法把Yaml文件传入到这个类
        :param yaml_file:
        """
        self.yaml_file = yaml_file

    # 读取Yaml文件
    def read_yaml(self):
        """
        读取Yaml,对yaml反序列化,就是把我们的yaml格式转换成dict格式
        :return:
        """
        with open(self.yaml_file, encoding='utf-8')as f:
            value = yaml.load(f, Loader=yaml.FullLoader)
            return value

测试用例get_yaml.py

复制代码
import pytest
import os
from common.yaml_util import YamlUtil


# 文件地址
realpath = os.path.abspath(os.path.join(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]), '.'))
# 项目地址
project_dir = os.path.dirname(realpath)


@pytest.mark.parametrize('args', YamlUtil(project_dir + '/data_study/data/data_y.yaml').read_yaml())
def test_01_huahua(args):

    name = args['name']
    password = args['password']

    print(name)
    print(password)


if __name__ == '__main__':
    pytest.main(['-vs', "get_yaml.py"])

运行结果:

其他:DDT技术和conftest.py结合

pytest有更方便的管理数据驱动方法的办法:conftest.py

conftest.py特点:

1.conftest.py名字固定的,不可以修改

2.conftest.py文件所在目录必须存在__init__py文件

3.conftest.py文件不能被其他文件导入

4.所有同目录测试文件运行前都会执行conftest.py文件

conftest.py一般和**@pytest.fixture()**固件放在一起使用

conftest原理是,运行pytest项目之前,默认优先执行当前层的conftest.py文件,数据处理完后,加上固件赋予直接传参的能力.注意;如果想conftest.py对所有文件都生效的话,一般建在根目录下

相关推荐
我的xiaodoujiao18 小时前
API 接口自动化测试详细图文教程学习系列24--如何用Pytest去设计接口测试用例并执行
python·学习·测试工具·pytest
我的xiaodoujiao1 天前
API 接口自动化测试详细图文教程学习系列23--结合Pytest框架使用4-前后置处理
python·学习·测试工具·pytest
wanglei2007082 天前
pytest自动化测试框架项目架构
pytest
词元Max5 天前
2.12 pytest 实战:如何测试 AI 应用
人工智能·pytest
biter down6 天前
11:pytest 框架 assert 验证测试
服务器·windows·pytest
biter down6 天前
14:pytest-order 插件 顺序控制案例
开发语言·python·pytest
我的xiaodoujiao7 天前
API 接口自动化测试详细图文教程学习系列21--结合Pytest框架使用2--断言和插件
python·学习·测试工具·pytest
我的xiaodoujiao7 天前
API 接口自动化测试详细图文教程学习系列22--结合Pytest框架使用3-分组、跳过执行和参数化处理
python·学习·测试工具·pytest
测试员周周11 天前
【Appium 系列】第13节-混合测试执行器 — API + UI 的协同执行
开发语言·人工智能·python·功能测试·ui·appium·pytest