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对所有文件都生效的话,一般建在根目录下

相关推荐
我的xiaodoujiao1 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
我的xiaodoujiao1 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 45--生成项目需要的requirements.txt依赖文件
python·学习·测试工具·pytest
月明长歌1 天前
全栈测试修炼指南:从接口策略到 Python+Pytest+Allure 企业级架构
python·架构·pytest
一晌小贪欢2 天前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
我送炭你添花2 天前
Pelco KBD300A 模拟器:20.搭建pytest集成测试基础框架 + 模拟器闭环测试
python·集成测试·pytest
我送炭你添花3 天前
Pelco KBD300A 模拟器:18. 按依赖顺序 + 复杂度由低到高逐步推进pytest单元测试
python·单元测试·log4j·pytest
生活很暖很治愈3 天前
Pytest-order插件
python·测试工具·测试用例·pytest
测试人社区—66796 天前
2025区块链分层防御指南:AI驱动的安全测试实战策略
开发语言·驱动开发·python·appium·pytest
我送炭你添花6 天前
pytest 入门指南:从零开始掌握 Python 测试框架的核心概念与使用方法
chrome·python·pytest
though the night6 天前
Python UI 自动化测试框架搭建demo(Selenium+Pytest 版)
自动化测试·selenium·测试工具·pytest