工具层handle_response

  1. **__handle_str**:利用 str.replace 清洗 Excel 数据中的换行符和空格,确保格式合法;
  2. **handle_response**:基于 isinstancerequestsjson()/text 方法,标准化 JSON/文本响应,输出统一结构;
  3. **assert_reponse**:通过 jsonpath 动态提取字段、ast.literal_eval 安全转换预期值为字典,结合 unittestassertEqual 实现灵活断言,避免硬编码;
  4. **assert_db**:直接调用 assertEqual 验证数据库数据一致性。
  1. __handle_str(清洗输入)
  2. handle_response(标准化响应)
  3. assert_reponse(动态断言)
  4. assert_db(数据库断言)
自定义函数 所用模块/方法 函数作用
handle_response(response) isinstance 判断对象的数据类型并返回布尔值;区分响应数据格式(JSON 或纯文本),确保后续处理逻辑适配不同接口返回类型
assert_reponse(expected_data, response)动态提取实际响应字段,并与预期数据对比,执行自动化断言 __handle_str()清洗数据 清洗excel中的预期结果的换行符(\n)和空格,避免因数据格式错误(如 JSON 中存在非法空格)导致解析失败或断言不匹配
assert_reponse(expected_data, response)动态提取实际响应字段,并与预期数据对比,执行自动化断言 isinstance 判断对象的数据类型是字典dict并返回布尔值
assert_reponse(expected_data, response)动态提取实际响应字段,并与预期数据对比,执行自动化断言 ast.literal_eval(expected_data)字符串转字典 将字符串格式的预期值(如 "{'token_type': 'bearer'}")安全转换为字典,避免 eval 的安全风险。
assert_reponse(expected_data, response)动态提取实际响应字段,并与预期数据对比,执行自动化断言 jsonpath(response, "$..key")动态字段提取 通过 JSONPath 表达式(如 $..token_type)从响应中提取动态字段值,支持嵌套结构,避免硬编码路径。
assert_db(extract_data, actual_data) self.assertEqual() 直接比对数据库查询结果与预期数据,验证数据一致性。
python 复制代码
import ast
import unittest
from jsonpath import jsonpath

class HandleResponse(unittest.TestCase):

    def __handle_str(self,data:str):    #data:excel中获取的请求参数
        for str_data in ["\n"," "]:
            data = data.replace(str_data,"")
        return data             #去掉空格后的请求参数

    # 响应结果处理
    def handle_response(self,response):
        try:
            if isinstance(response.json(),dict): #判断一个对象是否时一个已知的类型
                return {"response_type":"json","response":response.json()}
        except Exception as e :
            if isinstance(response.text,str):
                return {"response_type":"str","response":response.text}
            else:
                return {}

    def assert_reponse(self,expected_data,response):
        # 期望结果: expected_data = {"token_type": "bearer"}
        # 实际结果: actual_data = {"token_type":"bearer"}
        if expected_data:
            #去空格
            expected_data = self.__handle_str(data=expected_data)
            # 三元运算符 [结果为真的值] if [条件] else [结果为假的值]
            expected_data = expected_data if isinstance(expected_data,dict) else ast.literal_eval(expected_data)
            actual_data = {}
            if response["response_type"] == "json":
                for key in expected_data:
                    actual_data[key]=jsonpath(response,f"$..{key}")[0]
                self.assertEqual(expected_data,actual_data)
            else:
                for key in expected_data:
                    actual_data[key] = response["response"]
                self.assertEqual(expected_data, actual_data)
        else:
            print("预期结果为空,不需要做接口响应的断言")

    # 断言数据库
    def assert_db(self,extract_data,actual_data):
        self.assertEqual(extract_data,actual_data)



if __name__ == '__main__':
    cl = HandleResponse()
相关推荐
疯狂成瘾者1 小时前
语义分块提升RAG检索精度
python
小陈工3 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
A__tao7 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
研究点啥好呢7 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
迷藏4947 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
明日清晨8 小时前
python扫码登录dy
开发语言·python
bazhange8 小时前
python如何像matlab一样使用向量化替代for循环
开发语言·python·matlab
人工干智能8 小时前
科普:python中你写的模块找不到了——`ModuleNotFoundError`
服务器·python
unicrom_深圳市由你创科技8 小时前
做虚拟示波器这种实时波形显示的上位机,用什么语言?
c++·python·c#
小敬爱吃饭8 小时前
Ragflow Docker部署及问题解决方案(界面为Welcome to nginx,ragflow上传文件失败,Docker中的ragflow-cpu-1一直重启)
人工智能·python·nginx·docker·语言模型·容器·数据挖掘