Pytest+requests进行接口自动化测试9.0(redis + excal文件的使用)

Redis的使用

一、Redis简介

Redis是一个基于内存的 key-value 结构数据库,主要是在内存中保存数据,加速数据访问的。

Redis基本介绍

二、下载Redis

下载工具:Redis Desktop Manager

建立连接

获取key值

从单节点服务器中获取数据

配置文件config.yaml 文件里添加 redis 配置

yaml 复制代码
redis:
  host: 127.0.0.1
  port: 6379
  username:
  password:
  db: 0

读取 config.yaml 文件中的 redis 配置

python 复制代码
    def get_section_redis(self, option):
        """快捷方法:获取redis配置"""
        return self.get('redis', option)

创建redis连接 与 读取对应key值的数据

python 复制代码
class RedisClient:
    """
    从redis中读取,设置相关数据
    """
    def __init__(self):
        self.conf = OperationYaml()
        self.__redis_conf = {
            'host':self.conf.get_section_redis('host'),
            'port':int(self.conf.get_section_redis('port')),
            'username':self.conf.get_section_redis('username'),
            'password':self.conf.get_section_redis('password'),
            'db':self.conf.get_section_redis('db'),
        }
        try:
            logs.info(f'连接到Redis服务器:ip:{self.__redis_conf["host"]}')
            pool = redis.ConnectionPool(**self.__redis_conf)
            self.redis_cluster = redis.Redis(connection_pool=pool)
        except Exception as e:
            logs.error(f'redis连接失败,{e}')

    @classmethod
    def redis_except(self,e):
        if 'MOVED' in str(e):
            logs.error(f'请检查Redis是否使用了集群模式或者主从复制的情况,数据被迁移到了另外一个Redis实例上:{e}')
        else:
            logs.error(f'Redis Error:{e}')

    def get(self,key):
        """
        获取Redis里面的数据
        :param key: Redis里面的键
        :return:
        """
        try:
            value = self.redis_cluster.get(key)
            if isinstance(value, bytes):
                return value.decode('utf-8')
            return value
        except Exception as e:
            self.redis_except(e)
            logs.error(f"从Redis中获取[{e}]失败,失败原因:{e}")
            raise

    def set(self,key,value,ex=None):
        """
        设置Redis的值
        :param key: Redis
        :param value: 需要设置的内容
        :param ex: 过期时间,单位秒(s)
        :return:
        """
        try:
            self.redis_cluster.set(name=key, value=value, ex=ex)
        except Exception as e:
            logs.redis_except(e)

从集群环境中获取数据

yaml 复制代码
redis:
  startup_nodes: 172.17.33.214:6479,172.17.33.214:6380
  host: 127.0.0.1
  port: 6379
  username:
  password:
  db: 0

集群读取

python 复制代码
class RedisClient:
    """
    从redis中读取,设置相关数据
    """
    def __init__(self):
        self.conf = OperationYaml()
        self.__redis_conf = {
            'host':self.conf.get_section_redis('host'),
            'port':int(self.conf.get_section_redis('port')),
            'username':self.conf.get_section_redis('username'),
            'password':self.conf.get_section_redis('password'),
            'db':self.conf.get_section_redis('db'),
        }
        redis_nodes_str = self.conf.get_section_redis('startup_nodes')
        self.nodes_list = []
        if redis_nodes_str:
            nodes_str_list = redis_nodes_str.split(',')
            print(nodes_str_list)
            for node_str in nodes_str_list:
                host, port = node_str.split(':')
                node_data = {'host': 'host', 'port': 'port'}
                self.nodes_list.append(node_data)
            # startup_nodes: 集群的格式[{'host':'host','port':'port'},{'host2':'host2','port2':'port2'},{},....]
            self.redis_cluster = RedisCluster(startup_nodes=self.nodes_list)
            logs.info(f"连接到Redis集群服务,host:{redis_nodes_str}")
        elif self.__redis_conf['host'] and self.__redis_conf['port']:
            try:
                logs.info(f'连接到Redis服务器:ip:{self.__redis_conf["host"]}')
                pool = redis.ConnectionPool(**self.__redis_conf)
                self.redis_cluster = redis.Redis(connection_pool=pool)
            except Exception as e:
                logs.error(f'redis连接失败,{e}')

pycharm向git远程仓库提交、推送和pull代码

在 git 里克隆 url 地址

点击提交,将更改的项目推送上去

提交并推送,在文字描述处填写此次更改内容

三、excel文件的使用

Python 自动化测试中 Excel 数据驱动实战:手把手教你封装一个 HandleExcel 类


  • 目标

  • 读取 Excel 表格数据

  • 获取行数、列数、单元格值

  • 写入数据回 Excel

  • 支持配置化路径管理


  • 技术栈
库名 作用
xlrd 读取 .xls 文件(注意:不支持 .xlsx)
xlwt 写入 .xls 文件
xlutils.copy 在保留原格式的基础上复制并修改 Excel

安装命令

python 复制代码
pip install xlrd==1.2.0 xlwt xlutils

目录结构

此处存放全局路径

python 复制代码
import os
# 项目根目录
DIR_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

FILE_PATH = {
    'EXCEL': os.path.join(DIR_path, r'data\新建 XLS 工作表.xls')
}
  • xls文件:
  • 核心代码解析:HandleExcel 类

1. 导入依赖

python 复制代码
import xlrd
import xlwt
from xlutils.copy import copy
from conf import setting
import os
from common.recordlog import logs

2. 初始化方法 init

调用 xls_obj( ) 加载 Excel 表格对象

python 复制代码
def __init__(self, file_path=None):
    if file_path is not None:
        self.file_path = file_path
    else:
        self.file_path = setting.FILE_PATH['EXCEL']
    
    self.__global_table = self.xls_obj()

3. 加载 Excel 表格对象 xls_obj()

使用 os.path.splitext() 判断文件扩展名;

formatting_info=True:保留原有样式(字体、颜色等),便于后续写入时保持美观;

sheet_by_index(0):获取第一个工作表(索引从 0 开始);

不支持 .xlsx,遇到则报错并记录日志。

python 复制代码
def xls_obj(self):
    if os.path.splitext(self.file_path)[-1] != '.xlsx':
        obj = xlrd.open_workbook(self.file_path, formatting_info=True)
        xls_obj = obj.sheet_by_index(0)  # 取第一个 sheet
        return xls_obj
    else:
        logs.error('Excel文件必须是.xls格式!')

4. 常用读取方法

获取行列数,nrows 和 ncols 是 xlrd 提供的属性,直接调用即可

python 复制代码
def get_cols(self):
    """获取Excel的总列数"""
    return self.__global_table.ncols

def get_rows(self):
    """获取Excel的总行数"""
    return self.__global_table.nrows

获取单个单元格值,索引从 0 开始,例如 (0,0) 表示 A1 单元格

python 复制代码
def get_cell_value(self, row, col):
    return self.__global_table.cell_value(row, col)

获取一整行/列数据,返回 list 类型,可用于参数化测试

python 复制代码
def get_each_line(self, row):
    return self.__global_table.row_values(row)

def get_each_column(self, col):
    return self.__global_table.col_values(col)

5. 写入数据方法 write_xls_value

python 复制代码
def write_xls_value(self, row, col, value):
    try:
        init_table = xlrd.open_workbook(self.file_path, formatting_info=True)
        copy_table = copy(init_table)
        sheet = copy_table.get_sheet(0)  # 修改第0个工作表
        sheet.write(row, col, value)
        copy_table.save(self.file_path)
    except PermissionError:
        logs.error('请关闭Excel文件再操作!')
        exit()

输出结果:

python 复制代码
表格总行数: 6
表格总列数: 8
第一行第一列: 接口名称
B1单元格内容: /dar/user/login
相关推荐
蜗牛沐雨4 小时前
详解c++中的文件流
c++·1024程序员节
左&耳4 小时前
完整的 React + Umi 状态体系全景图
react.js·1024程序员节
dubochao_xinxi4 小时前
Nginx 配置解析与性能优化
1024程序员节
还是大剑师兰特5 小时前
TypeScript 面试题及详细答案 100题 (91-100)-- 工程实践与框架集成
前端·javascript·typescript·1024程序员节
我谈山美,我说你媚5 小时前
flutter使用getx做一个todolist
1024程序员节
m0_739030005 小时前
springboot中的怎么用JUnit进行测试的?
junit·1024程序员节
街尾杂货店&6 小时前
webpack - 常用的 CSS 加载器(webpack与其常见loader加载器使用方式)
1024程序员节
海域云赵从友6 小时前
中国企业跨境云组网指南:低延迟访问德国AWS云做数据分析的实操方案
1024程序员节
可涵不会debug6 小时前
依托金仓数据库的医疗信创多院区实践与 KingbaseES 操作详解
1024程序员节