(五)零代码封装pytest框架(接口关联之热加载替换)

一、Template与热加载替换

1、在接口关联中Template存在一些问题

(1)数字类型字符串替换时类型会产生变化

(2)不能做二次处理(加随机数、加密、签名处理等)

2、热加载替换

热加载替换:来源于httprunner框架

作用:在yaml文件中能调用python方法

二、步骤

1、首先在extract_util.py的ExtractUtil类下建立hotload_replace方法

前面提到过使用${token}的方法去替换token变量,现在改为${函数名(token)}去替换

将${函数名(token)}改为正则表达式即:" \\$\\{(.*?)\\((.*?)\\)\\} "   ((.*?)表示任意字符)

def hotload_replace(self, data_str: str):
    # 定义一个正则表达式去做匹配
    regexp = "\\$\\{(.*?)\\((.*?)\\)\\}"
    # 通过正则表达式在data_str中去匹配,得到所有表达式的列表
    fun_list = re.findall(regexp, data_str)
    for f in fun_list:
        if f[1] == "":      # 没有参数
            new_value = getattr(DebugTalk(), f[0])()
        else:               # 有参数1个或多个
            new_value = getattr(DebugTalk(), f[0])(*f[1].split(","))
        # 如果value是一个数字格式的字符串
        if isinstance(new_value, str) and new_value.isdigit():
            new_value = "'"+new_value+"'"
        # 拼接旧的值
        old_value = "${"+f[0]+"("+f[1]+")}"
        data_str = data_str.replace(old_value, new_value)
    return data_str

2、将use_extract_value方法的Template方法改成hotload_replace方法

def use_extract_value(self, data: dict):
    # 把字典转换成字符串
    data_str = yaml.safe_dump(data)
    # 字符串替换,替换${变量名}的值
    new_request_data = self.hotload_replace(data_str)
    # 把字符串转换成字典
    data_dict = yaml.safe_load(new_request_data)
    return data_dict

3、新建hotload python文件夹来保存相关函数的类

建debug_talk.py(文件下保存的就是在yaml文件下调用python方法的定义)

class DebugTalk:

    # 读取extract.yaml文件中提取的变量
    def read_yaml(self, key):
        with open("extract.yaml", encoding="utf-8") as f:
            value = yaml.safe_load(f)
            return value[key]

4、在yaml文件中需要提取使用变量的地方改为${函数名(参数)}格式

token: ${read_yaml(token)}

你可能感兴趣的:(pytest,python,单元测试,自动化,模块测试)