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

相关推荐
一个处女座的测试17 小时前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
思则变4 天前
[Pytest][Part 1]Pytest 自动化测试框架
pytest
思则变5 天前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
思则变6 天前
[Pytest][Part 3]检测python package状态
pytest
cooldream200920 天前
pytest 框架详解与实战指南
pytest·测试
慕城南风20 天前
【pytest进阶】Pytest之conftest详解
pytest
编程小白gogogo21 天前
AI自动化测试速成(Pytest框架)
pytest
慕城南风21 天前
【pytest进阶】pytest详解及进阶使用
linux·服务器·pytest
Tom Boom1 个月前
Pytest断言全解析:掌握测试验证的核心艺术
自动化测试·python·测试开发·pytest