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

相关推荐
鲸渔4 天前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
2601_967980117 天前
python pytest怎样测试代码
python·pytest·测试·文档·断言
2601_967980117 天前
python pytest如何编写测试
python·测试用例·pytest·函数·assert
2601_967980117 天前
Python pytest如何实现参数化测试
测试用例·pytest·python测试框架·参数化测试·ids参数
测试界的小码农24 天前
【让 AI 生成的测试用例变成 pytest API 自动化脚本】
人工智能·测试用例·pytest
2601_967987371 个月前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
Madison-No71 个月前
pytest框架
pytest
凛铄linshuo1 个月前
分析业务流程什么时候适合断言?
python·pytest
凛铄linshuo1 个月前
自动化测试:pytest第一个实例学习
学习·pytest
Helix2501 个月前
Python单元测试实战:pytest框架从入门到企业级测试体系搭建指南
python·单元测试·实战·mock·pytest·测试覆盖率·fixture