Template strings模板技术
在接口测试时,会使用到模板技术,当接口的参数字段特别多,而构造一条测试数据需要填很多的参数,从而导致效率低下,因此可以采用模板技术,对关键的一些参数进行替换,而不用每个参数都进行替换修改,减少了重复劳动。
一、Template strings
模板字符串提供了更简单的字符串替换,它是python自带的库。引入方式如下:
from string import Template
Template strings的规则如下:
- 模板字符串基于 $符号进行替换
- {}括号相当于占位符
- ${ identifier }等价于 $identifier
- Template接受的是字符串,所以python字典格式需要转换为字符串后再进行替换操作,否则报错
二、简单使用
1、模板初探
比如有构造书的接口,需要对书的名称、价格、出版社等字段进行替换,那么使用模板技术可以进行如下操作替换字符串。如下:
import json
from string import Template
template_data = {
"books": [
{
"name": "${name}", # {}括号相当于占位符
"price": "$price", # ${price}等价于$price
"publisher": "$publisher haha"
},
]
}
template = Template(json.dumps(template_data, indent=2)) #Template接受的是字符串,所以字典格式需要转换为字符串
Substitute = template.substitute(name="西游记", price="30", publisher="人民出版社") # substitute()按照Template中string输出,并给相应key赋值
print(f"替换后字符串:\n{Substitute}")
结果:
替换后字符串:
{
"books": [
{
"name": "西游记",
"price": "30",
"publisher": "人民出版社 haha"
}
]
}
成功将${name}、${price}、$publisher替换为想要的字符串。此时在测试时,利用参数化就可以批量造出大量的测试数据。
2、推荐使用方法
这里推荐使用${name},括号相当于占位符,避免当想替换的参数与其他参数相连,导致出错,如下:
import json
from string import Template
template_data = {
"books": [
{
"name": "${name}", # {}括号相当于占位符
"price": "${price}", # ${price}等价于$price
"publisher": "$publisherhaha" #参数关连导致报keyvalue错误
},
]
}
template = Template(json.dumps(template_data, indent=2))
Substitute = template.substitute(name="西游记", price="30", publisher="人民出版社") # substitute()按照Template中string输出,并给相应key赋值
print(f"替换后字符串:\n{Substitute}")
报错:
KeyError: 'publisherhaha'
三、substitute和safe_substitute
1、substitute
简单讲,使用substitute函数时,当传入的参数缺少key值,则报错KeyError。如下:
import json
from string import Template
template_data = {
"books": [
{
"name": "${name}", # {}括号相当于占位符
"price": "${price}", # ${price}等价于$price
"publisher": "${publisher}"
},
]
}
template = Template(json.dumps(template_data, indent=2))
Substitute = template.substitute(name="西游记", price="30") # 缺少参数
print(f"替换后字符串:\n{Substitute}")
报错:
KeyError: 'publisher'
这里template.substitute(name="西游记", price="30")缺少了参数publisher="人民出版社",所以会报错,提示有些参数没有替换。
2、safe_substitute
了解了substitute函数,反过来再了解safe_substitute就简单了,其作用就是当传入的参数缺少key值,不会报错,并且会把原来未替换的参数原封不动的打印出来。如下:
import json
from string import Template
template_data = {
"books": [
{
"name": "${name}", # {}括号相当于占位符
"price": "${price}", # ${price}等价于$price
"publisher": "$publisher"
},
]
}
template = Template(json.dumps(template_data, indent=2))
Substitute = template.safe_substitute(name="西游记", price="30") # 缺少参数
print(f"替换后字符串:\n{Substitute}")
结果:
替换后字符串:
{
"books": [
{
"name": "西游记",
"price": "30",
"publisher": "$publisher" #不会报错,并且会报原来未替换的参数原封不动的打印出来
}
]
}

浙公网安备 33010602011771号