接口自动化测试:yaml文件中变量替换

在做接口、UI自动化的时候,我们可以用yaml文件来管理测试用例的步骤、数据,因为每次测试的数据需要动态变换,所以yaml文件中相关参数可能需要用变量表示。那么,我们怎么进行变量的传值呢?

这里可以用到字符串的模板替换功能,官方文档:https://docs.python.org/zh-cn/3/library/string.html#template-strings

yaml文件中内容如下:

method: get
url: http://www.baidu.com
json:
  key1: $value1
  key2: $value2

其中,需要动态变换的参数值我们用$符号标识:$value1、$value2

下面进行yaml文件的读取,然后进行变量替换,替换后返回字典类型的值:

    def yaml_template(self,data:dict):
        with open("../data/test_template.yaml",encoding="utf-8") as f:
            re = Template(f.read()).substitute(data)
            return yaml.safe_load(re)

其中Template方法需要传入一个字符串,substitute方法传入关键字参数或者字典,注意key与yaml文件中的变量要对应

测试结果如下:

 

原文地址:https://www.cnblogs.com/Xiaojiangzi/p/13767459.html