接口自动化测试框架实战-3-文件读写封装

上一小节我们详细介绍了项目中所使用的接口文档,本小节我们将进入到接口测试框架第一个部分通用函数commons的开发,本小节我们重点完成文件读写方法的封装。

首先为什么要封装文件读写的方法,原因有如下几点:

  1. 读接口配置:比如我们接口的一些配置信息(域名、接口路径、账号)等我们一般都是放在config.yaml文件里,我们需要先读取到配置,后续拼接成接口的请求信息
  2. 读数据库配置:比如我们的数据库信息一般是放在db.ini文件中,我们需要先读取到配置,后续可以根据配置信息连接数据库进行取数据或者数据库字段断言
  3. 读写测试数据:比如我们的本次的接口测试数据是写在api.yaml里的,我们需要先读取数据,生成测试用例,有时候我们的api.yaml还有一些动态的模板参数需要替换,这个时候我们就需要写入文件了
  4. 读日志文件:比如有时候我们日志里记录了接口报错信息,我们需要分类读取出来,放到测试报告中或者群消息通知中来做错误告警

新建commons目录,新建files.py

files.py具体代码如下:

#files.py
import yaml
import os
import pandas as pd
import openpyxl
from configparser import ConfigParser


class FileHandler:
    """处理文件读取和写入操作的类"""

    @staticmethod
    def read_file(path):
        """根据文件路径的后缀名读取文件内容"""
        _, file_extension = os.path.splitext(path)
        file_extension = file_extension.lower()

        try:
            if file_extension == '.yaml' or file_extension == '.yml':
                with open(path, 'r', encoding='utf-8') as fp:
                    # 返回dict类型
                    return yaml.safe_load(fp)
            elif file_extension == '.ini' or file_extension == '.conf':
                config = ConfigParser()
                with open(path, 'r', encoding='utf-8') as fp:
                    config.read_file(fp)
                    return config
            elif file_extension == '.csv':
                return pd.read_csv(path)
            elif file_extension == '.xlsx':
                return pd.read_excel(path, engine='openpyxl')
            else:
                with open(path, 'r', encoding='utf-8') as fp:
                    return fp.read()
        except Exception as e:
            print(f"Error reading file {path}: {e}")
            return None

    @staticmethod
    def write_file(path, data):
        """根据文件路径的后缀名写入文件内容"""
        _, file_extension = os.path.splitext(path)
        file_extension = file_extension.lower()

        try:
            if file_extension == '.yaml' or file_extension == '.yml':
                with open(path, 'w', encoding='utf-8') as fp:
                    yaml.dump(data, fp, default_flow_style=False)
            elif file_extension == '.ini' or file_extension == '.conf':
                config = ConfigParser()
                for section, options in data.items():
                    config[section] = dict(options)
                with open(path, 'w', encoding='utf-8') as fp:
                    config.write(fp)
            elif file_extension == '.csv':
                pd.DataFrame(data).to_csv(path, index=False, encoding='utf-8')
            elif file_extension == '.xlsx':
                FileHandler._write_excel(path, data)
            else:
                with open(path, 'w', encoding='utf-8') as fp:
                    fp.write(str(data))
        except Exception as e:
            print(f"Error writing to file {path}: {e}")

    @staticmethod
    def _write_excel(path, data):
        """将数据写入Excel文件"""
        workbook = openpyxl.Workbook()
        for sheet_name, sheet_data in data.items():
            worksheet = workbook.create_sheet(sheet_name)
            for row in range(len(sheet_data)):
                for col, value in enumerate(sheet_data[row]):
                    worksheet.cell(row=row + 1, column=col + 1).value = value
        workbook.save(path)


# 示例用法
file_handler = FileHandler()

# 读取文件示例
# yaml_data = file_handler.read_file('example.yaml')
# print(type(yaml_data))
# ini_data = file_handler.read_file('example.ini')
# print(ini_data[""][""])
# conf_data = file_handler.read_file('example.conf')
# print(conf_data["database"]["host"])
# csv_data = file_handler.read_file('example.csv')
# print(csv_data)
# excel_data = file_handler.read_file('example.xlsx')
# print(excel_data)
# 写入文件示例
# yaml_data_to_write = {'key': 'value'}
# file_handler.write_file('output.yaml', yaml_data_to_write, 'yaml')
#
# config_data_to_write = {'Section1': {'Option1': 'Value1'}}
# file_handler.write_file('output.ini', config_data_to_write, 'ini')
#
# csv_data_to_write = {'Column1': [1, 2, 3], 'Column2': ['a', 'b', 'c']}
# file_handler.write_file('output.csv', csv_data_to_write, 'csv')
#
# excel_data_to_write = {
#     'Sheet1': [[1, 'a'], [2, 'b'], [3, 'c']],
#     'Sheet2': [[4, 'd'], [5, 'e'], [6, 'f']]
# }
# file_handler.write_file('output.xlsx', excel_data_to_write, 'excel')

代码逻辑讲解如下:

  1. 首先我们支持我们FileHandler类支持yaml、ini、csv、xlsx、conf、txt、log等常见文件的读写
  2. 其中pyyaml用来读写yaml文件,pandas库用来读写csv/excel文件,configparser用来读写ini/conf,

openpyxl 用来写excel文件,其余文件用python系统方法读写即可。

  1. 代码结构,一个类FileHandler,三个静态方法read_file、write_file、_write_excel
  2. 代码逻辑,读文件:先用os.path.splitext(path)取得文件路径后缀,比如yaml、ini、csv、xlsx,在根据后缀来做判断,分别调用2中对应的库方法,来进行文件数据的读取,最终返回读到的数据。写文件:和读文件类似先取后缀做判断,分别调用对应的库方法,将数据写入文件,这里excel的写入pandas库不支持,所以单独写了一个写入excel文件的方法,用openpyxl库方法来写入文件。

以上就是文件读写的封装方法,大家也可以自己找一些文件读写练习一下!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值