ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python读取数据文件实现数据驱动

2022-01-30 13:03:37  阅读:200  来源: 互联网

标签:__ 读取数据 python self cell path 驱动 data name


一、背景

自动化测试中我们通常需要实现数据驱动,比如常见的方法,我们会将接口的各项数据放在Json或Excel文件中,那么如何读取操作Json或Excel文件中的数据,用于接口使用呢?

二、具体操作

2.1 读取Json文件数据:

工程目录如下图:
在这里插入图片描述

Json文件内容:test_http_post_data.json

{
  "dataItem": [
    {
      "id": "testpost-1",
      "name": "草料二维码post接口1",
      "url":"/Apis/QrCode/saveStatic",
      "headers":{
        "Content-Type":"application/x-www-form-urlencoded",
        "Accept-Encoding":"gzip, deflate, br"
      },
      "parameters": {
        "info": 11111,
        "content": 11111,
        "level": "H",
        "size": 500,
        "fgcolor": "#000000",
        "bggcolor": "#FFFFFF",
        "transparent": "false",
        "type": "text",
        "base64": "data:image/png;base64",
        "codeimg": 1
      },
      "expectdata": {
        "status": "1",
        "qrtype":"static"
      }
    },

    {
      "id": "testpost-2",
      "name": "草料二维码post接口2",
      "url":"/Apis/QrCode/saveStatic",
      "headers":{
        "Content-Type":"application/x-www-form-urlencoded",
        "Accept-Encoding":"gzip, deflate, br"
      },
      "parameters": {
        "info": 22222,
        "content": 22222,
        "level": "H",
        "size": 500,
        "fgcolor": "#000000",
        "bggcolor": "#FFFFFF",
        "transparent": "false",
        "type": "text",
        "base64": "data:image/png;base64",
        "codeimg": 1
      },
      "expectdata": {
        "status": "1",
        "qrtype":"static"
      }
    }
  ]
}

创建一个读取Json文件的工具类:read_jsonfile_utils.py,代码如下:

import json
import os


class ReadJsonFileUtils:
    def __init__(self, file_name):
        self.file_name = file_name
        self.data = self.get_data()

    def get_data(self):
        fp = open(self.file_name,encoding='utf-8')
        data = json.load(fp)
        fp.close()
        return data

    def get_value(self, id):
        return self.data[id]

    @staticmethod
    def get_data_path(folder, fileName):
        BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        data_file_path = os.path.join(BASE_PATH, folder, fileName)
        return data_file_path

if __name__ == '__main__':
    data_file_path = ReadJsonFileUtils.get_data_path("resources", "test_http_post_data.json")
    # 读取文件中的dataItem,是一个list列表,list列表中包含多个字典
    param_data = ReadJsonFileUtils(data_file_path)
    data_item = param_data.get_value('dataItem')
    print(data_item)

读取文件中的dataItem,读取结果:
在这里插入图片描述
读取出来是一个list列表,list列表中包含多个字典。用于接口中做数据驱动:

"""
@pytest.mark.parametrize是数据驱动;
data_item列表中有几个字典,就运行几次case
ids是用于自定义用例的名称

"""
@pytest.mark.parametrize("args", data_item, ids=['测试草料二维码post接口1','测试草料二维码post接口2'])
def test_caoliao_post_demo(self, args):
	# 打印用例ID和名称到报告中显示
	print("用例ID:{}".format(args['id']))
	print("用例名称:{}".format(args['name']))

2.2 读取Excel文件数据:
在这里插入图片描述
Excel表格中数据如下:
在这里插入图片描述
读取数据的工具类:get_excel_data_utils.py, 代码如下:

# coding: utf8
import xlrd
from xlrd import xldate_as_tuple
import datetime


class ExcelData(object):
    '''
    xlrd中单元格的数据类型
    数字一律按浮点型输出,日期输出成一串小数,布尔型输出0或1,所以我们必须在程序中做判断处理转换
    成我们想要的数据类型
    0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
    '''
    def __init__(self, data_path, sheetname="Sheet1"):
        #定义一个属性接收文件路径
        self.data_path = data_path
        # 定义一个属性接收工作表名称
        self.sheetname = sheetname
        # 使用xlrd模块打开excel表读取数据
        self.data = xlrd.open_workbook(self.data_path)
        # 根据工作表的名称获取工作表中的内容
        self.table = self.data.sheet_by_name(self.sheetname)
        # 根据工作表的索引获取工作表的内容
        # self.table = self.data.sheet_by_name(0)
        # 获取第一行所有内容,如果括号中1就是第二行,这点跟列表索引类似
        self.keys = self.table.row_values(0)
        # 获取工作表的有效行数
        self.rowNum = self.table.nrows
        # 获取工作表的有效列数
        self.colNum = self.table.ncols

    # 定义一个读取excel表的方法
    def readExcel(self):
        # 定义一个空列表
        datas = []
        for i in range(1, self.rowNum):
            # 定义一个空字典
            sheet_data = {}
            for j in range(self.colNum):
                # 获取单元格数据类型
                c_type = self.table.cell(i,j).ctype
                # 获取单元格数据
                c_cell = self.table.cell_value(i, j)
                if c_type == 2 and c_cell % 1 == 0:  # 如果是整形
                    c_cell = int(c_cell)
                elif c_type == 3:
                    # 转成datetime对象
                    date = datetime.datetime(*xldate_as_tuple(c_cell, 0))
                    c_cell = date.strftime('%Y/%d/%m %H:%M:%S')
                elif c_type == 4:
                    c_cell = True if c_cell == 1 else False
                sheet_data[self.keys[j]] = c_cell.replace(' ', '').replace('\n', '').replace('\r', '')

            # 再将字典追加到列表中
            datas.append(sheet_data)
        # 返回从excel中获取到的数据:以列表存字典的形式返回
        return datas


if __name__ == "__main__":
    data_path = "..\\resources\\test_http_data.xls"
    sheetname = "Sheet1"
    get_data = ExcelData(data_path, sheetname)
    datas = get_data.readExcel()
    print(datas)

注意:代码中 c_cell.replace(’ ‘, ‘’).replace(’\n’, ‘’).replace(’\r’, ‘’) 是为了从Excel表格中读取到数据后,去掉数据中的空格和换行。

成果读取Excel中的数据,结果如下:
在这里插入图片描述

[{'id': 'testpost-1', 'name': '草料二维码生成接口', 'url': 'https://cli.im/Apis/QrCode/saveStatic', 'parameters': '{"info":22222,"content":22222,"level":"H","size":500,"fgcolor":"#000000","bggcolor":"#FFFFFF","transparent":"false","type":"text","base64":"data:image/png;base64","codeimg":1}', 'expectData': '{"code":"0000","result":"成功"}'}, {'id': 'testpost-2', 'name': '草料二维码生成接口', 'url': 'https://cli.im/Apis/QrCode/saveStatic', 'parameters': '{"info":22222,"content":22222,"level":"H","size":500,"fgcolor":"#000000","bggcolor":"#FFFFFF","transparent":"false","type":"text","base64":"data:image/png;base64","codeimg":1}', 'expectData': '{"code":"0000","result":"成功"}'}]

=========================================================
以上就是本篇文章的全部内容,如果对你有帮助,

欢迎扫码关注程序员杨叔的微信公众号,获取更多测试开发干货内容资料,一起交流成长:
在这里插入图片描述

标签:__,读取数据,python,self,cell,path,驱动,data,name
来源: https://blog.csdn.net/baidu_28340727/article/details/122719446

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有