yaml文件中变量值的替换

前言

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

解决方法:

字符串的模板替换功能

具体使用可以参考这篇博客模板字符串(python基于template实现字符串替换)

实例

场景:登录接口测试用例,token需要实时替换为最新的token之后发起请求,请求体的数据也可以通过在代码中字典的方式传递参数赋值给$标记的数据

a.yml用例文件:【需要动态替换的值用$符号标识】

method: get
url: http://www.baidu.com
headers:
  Content-Type: application/json
  token: $token
data:
  username: $username
  password: $password

如:

代码如下:【首先进行yaml文件的读取,读取之后进行变量值的替换,替换后返回字典数据类型类型的值】、

【 Template 类需要传入一个字符串初始化实例对象, substitute 方法传入关键字参数或者字典,注意入参的key与yaml文件中的变量要对应起来】

# read_yaml.py

from string import Template

import yaml


def yaml_template(data: dict):
    with open("a.yml", encoding="utf-8") as f:
       #  f.read()读取的是yaml文件的文本格式数据(即读取出来的数据为字符串格式) 
       #  这里代码的作用是将data数据替换f.read()读出来的$标识的数据---简单来说就是读取yaml文件中的数据,然后替换原数据中被$符号标识的变量,得到新的数据(此时没有生成新的对象,只是改变了数据的内容)
        re = Template(f.read()).substitute(data)

        print(re, type(re))
        # method: get
        # url: http: // www.baidu.com
        # headers:
        #     Content - Type: application / json
        #     token: hdadhh21uh1283hashdhuhh2hd
        # data:
        #     username: admin
        #     password: 123456
        #
        # <class 'str'>

        print(yaml.safe_load(stream=re), type(yaml.safe_load(stream=re)))
        #  {'method': 'get', 'url': 'http://www.baidu.com', 'headers': {'Content-Type': 'application/json', 'token': 'hdadhh21uh1283hashdhuhh2hd'}, 'data': {'username': 'admin', 'password': 123456}} <class 'dict'>
        # 返回字典格式的数据---反序列化
        return yaml.safe_load(stream=re)


if __name__ == '__main__':
    print(yaml_template({'token': 'hdadhh21uh1283hashdhuhh2hd', 'username': 'admin', 'password': '123456'}))

运行结果:

 

posted @ 2021-11-25 17:30  习久性成  阅读(4676)  评论(0编辑  收藏  举报