Pythonoffice

零基础小白(八)下篇 -实战Excel封装读取数据

2021-01-27  本文已影响0人  巴鶴

零基础小白 接口自动化测试集锦: https://www.jianshu.com/nb/49125734
Excel读写: 参考《Excel办公自动化》集锦分享 https://www.jianshu.com/nb/49019927

Excel 维护测试用例

承继上篇,实战Excel封装数据读取

if __name__ == "__main__":
    case_file = os.path.join(Conf.get_data_path(), ConfigYaml().get_excel_file())  # 拼接路径+文件
    # print(case_file)
    # 2).测试用例sheet名称
    sheet_name = ConfigYaml().get_excel_sheet()
    reader = ExcelReader(case_file,sheet_name)
    # reader = ExcelReader("../data/testdata.xlsx", "美多商城接口测试")
    result = reader.data()
    print(result)

代码分解讲解

  case_file = os.path.join(Conf.get_data_path(), ConfigYaml().get_excel_file())  # 拼接路径+文件

实际项目中,如果项目模块很多,同时逻辑性很强,接口测试用例使用Excel维护时可以使用一份Excel,开多个sheet,也可以按模块建立多个Excel,进行接口测试用例维护. 为了方便读取多份Excel文件,可以设置配置文件读取Excel文件名,建立专门的文件目录存放接口测试用例Excel文件,例如文件夹data存放各种格式的测试数据.

Excel文件路径设计

首先建立data文件夹存放Excel测试用例

data文件夹存放Excel测试用例.jpg

设计data目录脚本

_data_path = BASE_DIR + os.sep + "data"
print(_data_path)
data路径.jpg

conf.yml 文件配置Excel文件名和sheet

BASE:
   # log等级
  log_level: 'debug'
   #扩展名
  log_extension: ".log"
  test:
    url: "https://mmm-api.test.com"
    case_file: "doudizhu_testdata.xlsx"
    case_sheet: "斗地主接口测试"

Conf.py 读取conf.yml 配置信息

实战 读取data目录下doudizhu_testdata.xlsx 测试用例数据

conf.yml 整体代码参考

BASE:
   # log等级
  log_level: 'debug'
   #扩展名
  log_extension: ".log"
  test:
    url: "https://mmm-api.test.com"
    case_file: "doudizhu_testdata.xlsx"
    case_sheet: "斗地主接口测试"

Conf.py 整体代码参考

# -*- coding: utf-8 -*-
# @Time : 2021/1/11 16:16
# @File : Conf.py.py
# @Author : Yvon_早安阳光

import os,json
from utils.YamlUtil import YamlReader

#获取项目基本目录
current = os.path.abspath(__file__)
#获取当前项目的绝对路径
BASE_DIR = os.path.dirname(os.path.dirname(current))
#定义config目录路径
_config_path = BASE_DIR + os.sep + "config"
#定义conf.yml文件路径
_confyml_file  = _config_path + os.sep + "conf.yml"
# 定义logs文件路径
_log_path = BASE_DIR + os.sep + "logs"
#定义data目录路径
_data_path = BASE_DIR + os.sep + "data"
#定义testlogin.yml文件路径
_testlogin_config_file = _data_path + os.sep + "testlogin.yml"
#定义db_conf.yml-数据库配置文件路径
_db_config_file = _config_path + os.sep + "db_conf.yml"
#***************************************定义方法**************************************

def get_config_path():
    """
    获取config文件夹目录
    :return:
    """
    return _config_path

def get_confyml_file():
    '''
    获取conf.yml文件路径目录
    :return:
    '''
    return _confyml_file

def get_log_path():
    """
    获取log文件路径
    :return:
    """
    return _log_path

def get_data_path():
    """
    获取data文件夹目录
    :return:
    """
    return _data_path

def get_testlogin_config_file():
    """
    获取登录配置文件
    :return:
    """
    return _testlogin_config_file

def get_db_config_file():
    """
    获取数据库配置文件
    :return:
    """
    return _db_config_file


#读取配置文件,创建类
class ConfigYaml:

    def __init__(self):
        # 初始化读取yaml配置文件
        self.config = YamlReader(get_confyml_file()).data()
        # 初始化读取testlogin yaml配置文件
        self.testlogin_config = YamlReader(get_testlogin_config_file()).data_all()
        # 初始化读取数据库yaml配置文件
        self.db_config = YamlReader(get_db_config_file()).data()

    # 定义方法获取重要信息
    def get_conf_url(self):
        '''
        获取confyml配置文件中url地址
        :return:
        '''
        return self.config["BASE"]["test"]["url"]

    def get_conf_log(self):
        """
        获取日志级别
        :return:
        """
        return self.config["BASE"]["log_level"]

    def get_conf_log_extension(self):
        """
        获取文件扩展名
        :return:
        """
        return self.config["BASE"]["log_extension"]

    def get_testlogin_conf_info(self):
        """
        返回testlogin yaml文档所有内容
        :return:
        """
        return self.testlogin_config

    def get_db_conf_info(self,db_alias):
        """
        根据db_alias获取该名称下的数据库信息
        :param db_alias:
        :return:
        """
        return self.db_config[db_alias]

    def get_excel_file(self):
        """
        获取测试用例excel名称
        :return:
        """
        return self.config["BASE"]["test"]["case_file"]

    def get_excel_sheet(self):
        """
        获取测试用例sheet名称
        :return:
        """
        return self.config["BASE"]["test"]["case_sheet"]

if __name__ == "__main__":
    conf_read = ConfigYaml()
    res = conf_read.get_db_conf_info('db_1')
    print(json.dumps(res, sort_keys=True, ensure_ascii=False, indent=4, separators=(', ', ': ')))

ExcelUtil.py 整体代码参考

# -*- coding: utf-8 -*-
# @Time : 2020/11/26 17:43
# @File : ExcelUtil.py
# @Author : Yvon_早安阳光

import os
import xlrd ,json
from config.Conf import ConfigYaml
from config import Conf

#目的:参数化,pytest list文件形式读取
# 自定义异常
class SheetTypeError:
    pass
#1、验证文件是否存在,存在读取,不存在报错
class ExcelReader:
    def __init__(self,excel_file,sheet_by):
        if os.path.exists(excel_file):
            self.excel_file = excel_file
            self.sheet_by = sheet_by
            self._data = list()
        else:
            raise FileNotFoundError("文件不存在")

#2、读取sheet方式.名称,索引
    def data(self):
        # 存在不读取,不存在读取
        if not self._data:
            workbook = xlrd.open_workbook(self.excel_file)
            if type(self.sheet_by)  not in [str,int]:
                raise SheetTypeError("请输入int or str")
            elif type(self.sheet_by) == int:
                sheet = workbook.sheet_by_index(self.sheet_by)  # int型
            elif type(self.sheet_by) == str:
                sheet = workbook.sheet_by_name(self.sheet_by)  # str型

    #3、sheet内容
            # 返回list,元素:字典
            #格式[{'company': '可口可乐', 'manager': 'Shirley'}, {'company': '北极光', 'manager': 'marry'}]
            #1.获取首行信息
            title = sheet.row_values(0)
            #2.遍历测试行,与首行组成dict,放在list
                #1.循环,过滤首行,从1开始
            for col in range(1,sheet.nrows):
                col_value = sheet.row_values(col)
                #2.与首行组成字典,放list
                self._data.append(dict(zip(title, col_value)))

#4、返回结果
        return self._data

if __name__ == "__main__":
    case_file = os.path.join(Conf.get_data_path(), ConfigYaml().get_excel_file())  # 拼接路径+文件
    # print(case_file)
    # 2).测试用例sheet名称
    sheet_name = ConfigYaml().get_excel_sheet()
    reader = ExcelReader(case_file,sheet_name)
    result = reader.data()
    # print(result)
    print(json.dumps(result, sort_keys=True, ensure_ascii=False, indent=4, separators=(', ', ': ')))  # Json格式打印

执行ExcelUtil.py 脚本

运行结果.jpg
对比Excel文件.jpg
上一篇下一篇

猜你喜欢

热点阅读