• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

API自动化工具:案例

武飞扬头像
YiHong_Li
帮助1

项目GitHub地址:GitHub - muzili0903/APIframework

如果有疑问欢迎留言,当然如果觉得写得不错可以收藏或推荐一下,可以的话,麻烦GitHub帮忙给个小星星!!!

        案例解析分请求头解析以及请求报文解析,通过对请求报文与请求报文解析函数,将特定格式的script脚本接口文档转为json格式的报文体

请求头解析:

        请求头中固定的参数优先从script脚本中获取,获取不到从配置文件中获取。(请求头支持用户参数化)

  1.  
    def ini_request_headers(request_headers: dict, test_data: dict, con) -> dict:
  2.  
    """
  3.  
    请求头处理
  4.  
    :param request_headers:
  5.  
    :param test_data
  6.  
    :return:
  7.  
    """
  8.  
    try:
  9.  
    default_headers = dict(con.get_items('request_headers'))
  10.  
    default_project = dict(con.get_items('project'))
  11.  
    except Exception as e:
  12.  
    logging.error("配置文件request_headers 或 default_project 不存在: >>>{default_headers}, {default_project}".format(
  13.  
    default_headers=default_headers, default_project=default_project))
  14.  
    logging.error("报错信息: >>>{}".format(e))
  15.  
    # headers
  16.  
    method = request_headers.get('Method') or default_headers.get('Method')
  17.  
    content_type = request_headers.get('Content-Type') or default_headers.get('Content-Type')
  18.  
    user_agent = request_headers.get('User-Agent') or default_headers.get('User-Agent')
  19.  
    connection = request_headers.get('Connection') or default_headers.get('Connection')
  20.  
    timeout = request_headers.get('timeout') or default_headers.get('timeout')
  21.  
    cookie = request_headers.get('cookie') or default_headers.get('cookie')
  22.  
    save_cookie = request_headers.get('save_cookie') or default_headers.get('save_cookie')
  23.  
    sleep_time = request_headers.get('sleep_time') or default_headers.get('sleep_time')
  24.  
    path = request_headers.get('path') or default_headers.get('path')
  25.  
    # project 兼容上游与管理台之间的交互
  26.  
    base_url = request_headers.get('base_url') or default_project.get('base_url')
  27.  
    env = request_headers.get('env') or default_project.get('env')
  28.  
    logging.info("request_headers处理前: >>>{}".format(request_headers))
  29.  
    try:
  30.  
    header = {'Method': method, 'Content-Type': content_type, 'User-Agent': user_agent, 'Connection': connection,
  31.  
    'timeout': int(timeout), 'cookie': cookie, 'save_cookie': save_cookie, 'path': path,
  32.  
    'base_url': base_url, 'env': env, 'sleep_time': int(sleep_time)}
  33.  
    header = eval(replaceData.replace_user_var(str(header), test_data))
  34.  
    request_headers.update(header)
  35.  
    except Exception as e:
  36.  
    logging.error("request_headers处理失败: >>>{}".format(e))
  37.  
    logging.info("request_headers处理后: >>>{}".format(request_headers))
  38.  
    return request_headers
学新通

用户参数化: 

  1.  
  2.  
    def replace_user_var(case, data: dict):
  3.  
    """
  4.  
    替换请求报文中的用户参数值 ${变量名}
  5.  
    :param case: 用例报文
  6.  
    :param data: 用例数据
  7.  
    :return:
  8.  
    """
  9.  
    if re.search('\$\{.*?\}', case) is not None:
  10.  
    res = re.findall('\$\{.*?\}', case)
  11.  
    else:
  12.  
    return case
  13.  
    try:
  14.  
    for index in range(len(res)):
  15.  
    var = res[index].split('{')[1].split('}')[0]
  16.  
    case = case.replace(res[index], str(data[var]), 1)
  17.  
    except KeyError:
  18.  
    logging.error("获取不到变量值: >>>{}".format(var))
  19.  
    return case
  20.  
     
  21.  
学新通

请求报文解析:

  1.  
    def ini_params(test_info: dict, test_data: dict) -> dict:
  2.  
    """
  3.  
    初始化报文
  4.  
    :param test_info:测试报文
  5.  
    :param test_data: 测试数据
  6.  
    :return:
  7.  
    """
  8.  
    logging.info("body处理前: >>>{}".format(test_info))
  9.  
    # 用户自定义参数化
  10.  
    if re.search('\$\{.*?\}', str(test_info)) is not None:
  11.  
    test_info = eval(replaceData.replace_user_var(str(test_info), test_data))
  12.  
    # 系统函数参数化
  13.  
    if re.search('\$\(f.*?\)', str(test_info)) is not None:
  14.  
    test_info = eval(replaceData.replace_func(str(test_info)))
  15.  
    # 用户自定义函数参数化
  16.  
    if re.search('\$\(u.*?\)', str(test_info)) is not None:
  17.  
    test_info = eval(replaceData.replace_user_func(str(test_info)))
  18.  
    # 从请求报文获取参数值
  19.  
    if re.search('\$Req\{.*?\}', str(test_info)) is not None:
  20.  
    test_info = eval(replaceData.replace_req(str(test_info)))
  21.  
    # 从响应报文获取参数值
  22.  
    if re.search('\$Resp\{.*?\}', str(test_info)) is not None:
  23.  
    test_info = eval(replaceData.replace_resp(str(test_info)))
  24.  
    # 从数据库获取参数值
  25.  
    if re.search('\$DB\{.*?\}', str(test_info)) is not None:
  26.  
    test_info = eval(replaceData.replace_db(str(test_info), test_data))
  27.  
    logging.info("body处理后: >>>{}".format(test_info))
  28.  
    return test_info
学新通

系统函数参数化:

  1.  
    def replace_func(case):
  2.  
    """
  3.  
    替换请求报文中的函数变量值 $(f函数名)
  4.  
    :param case:
  5.  
    :return:
  6.  
    """
  7.  
    if re.search('\$\(f.*?\)', case) is not None:
  8.  
    res = re.findall('\$\(f.*?\)', case)
  9.  
    else:
  10.  
    return case
  11.  
    try:
  12.  
    for index in range(len(res)):
  13.  
    func_params = res[index].split('(', 1)[1].split(')', 1)[0]
  14.  
    if "::" in func_params: # 带参函数
  15.  
    func_name, params = func_params.split("::")
  16.  
    func = func_name '(' params ')'
  17.  
    else: # 不带参函数
  18.  
    func = func_params '()'
  19.  
    func = eval('sysFunc.' func)
  20.  
    case = case.replace(res[index], func, 1)
  21.  
    except AttributeError:
  22.  
    logging.error("获取不到系统函数: >>>{}".format(func))
  23.  
    return case
学新通

请求报文参数化:

  1.  
    def replace_req(case):
  2.  
    """
  3.  
    从其它接口的请求报文中替换请求报文中的参数值 $Req{接口名.变量名}
  4.  
    :param case:
  5.  
    :return:
  6.  
    """
  7.  
    if re.search('\$Req\{.*?\}', case) is not None:
  8.  
    res = re.findall('\$Req\{.*?\}', case)
  9.  
    else:
  10.  
    return case
  11.  
    # 测试专用
  12.  
    # GolStatic.set_file_temp('test', 'request_body',
  13.  
    # {'businessNo': '123456', 'j': [{'businessNo': '1111'}, {'businessNo': '2222'}]})
  14.  
    try:
  15.  
    for index in range(len(res)):
  16.  
    var = res[index].split('{')[1].split('}')[0]
  17.  
    filename, var_name = var.split('.', 1)
  18.  
    request_body = GolStatic.get_file_temp(filename=filename, key='request_body')
  19.  
    value = jsonpath(request_body, var_name)
  20.  
    if value:
  21.  
    case = case.replace(res[index], value[0], 1)
  22.  
    else:
  23.  
    case = case.replace(res[index], '', 1)
  24.  
    logging.error("获取不到请求报文字段值: >>>{}".format(var_name))
  25.  
    except KeyError:
  26.  
    logging.error("获取不到请求报文字段值: >>>{}".format(var))
  27.  
    except ValueError:
  28.  
    logging.error("jsonpath表达式有误: >>>{}".format(var))
  29.  
    return case
学新通

结果展示:

2022-06-16 08:26:15,854 - initializeParam.py - INFO: body处理前>>>{'appId': '${appId}', 'appKey': '${appKey}', 'data': {'invoiceAmt': 610.0, 'immediateInvoice': 1, 'payTaxpayerName': '${payTaxpayerName}', 'invoiceHead': 1, 'bizId': 'biz$(fdate)$(ftime)', 'invoiceType': 3, 'remarks': '票面备注:客户名称:${payTaxpayerName}, bizId=biz$(fdate)$(ftime)$(fnum::2)', 'taxpayerCode': '${taxpayerCode}', 'businessNo': '$(fdate)$(ftime)$(fnum::4)', 'detailList': [{'standards': 'MT-TZBKC01', 'taxRate': 0.13, 'taxUnitPrice': 180.0, 'businessNo': '$(fdate)$(ftime)$(fnum::2)', 'goodCount': 1, 'goodUnit': '台', 'bizDetailId': 'bdid$(fnum::11)', 'amtContainTax': 180.0, 'taxCode': '1080422', 'goodsName': 'Micca 炊具'}, {'standards': 'MP-SJ20W101', 'taxRate': 0.13, 'taxUnitPrice': 430.0, 'businessNo': '$(fdate)$(ftime)$(fnum::2)', 'goodCount': 1, 'goodUnit': '台', 'bizDetailId': 'bdid$(fnum::11)', 'amtContainTax': 430.0, 'taxCode': '107060112', 'goodsName': 'Midea/美的 餐饮具'}]}}
2022-06-16 08:26:15,854 - initializeParam.py - INFO: body处理后>>>{'appId': 'IBCP', 'appKey': '123456', 'data': {'invoiceAmt': 610.0, 'immediateInvoice': 1, 'payTaxpayerName': 'muzili_blue', 'invoiceHead': 1, 'bizId': 'biz20220616082615', 'invoiceType': 3, 'remarks': '票面备注:客户名称:muzili_blue, bizId=biz2022061608261516', 'taxpayerCode': '4429999441', 'businessNo': '202206160826153552', 'detailList': [{'standards': 'MT-TZBKC01', 'taxRate': 0.13, 'taxUnitPrice': 180.0, 'businessNo': '2022061608261574', 'goodCount': 1, 'goodUnit': '台', 'bizDetailId': 'bdid52138607243', 'amtContainTax': 180.0, 'taxCode': '1080422', 'goodsName': 'Micca 炊具'}, {'standards': 'MP-SJ20W101', 'taxRate': 0.13, 'taxUnitPrice': 430.0, 'businessNo': '2022061608261533', 'goodCount': 1, 'goodUnit': '台', 'bizDetailId': 'bdid49965521408', 'amtContainTax': 430.0, 'taxCode': '107060112', 'goodsName': 'Midea/美的 餐饮具'}]}}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggakfk
系列文章
更多 icon
同类精品
更多 icon
继续加载