原数据:
[{'ID': 1, 'title': '新增平台药品', 'project_name': 'add_platform_drug', 'is_upload': None, 'method': 'POST', 'content_type': None, 'url': '/web-admin/webhis/appmanage/main_drug_save.do', 'data': '{"a_b":"qqq${a_b()}","condition.baseunit":"g","condition.classify":"2","condition.code":"csyp003","condition.name":"测试饮片${num}","condition.pharmacopoeia":"测试生产厂家","condition.spec":"g","condition.spell":"csyp02","condition.alias":"","condition.chemicname":"","condition.id":"","condition.num":"","b_d":"aaa${b_d()}sss"}', 'expected_data': '{"code":0,"message":"添加成功!","object":null}', 'extract_data': None, 'assert_db': None}]
import json
import re
import os
from utils.excel_handle import ExcelHandle
from utils.path_handle import data_path
from string import Template
# re+Template 替换字符串中特定标识作为新值
def exec_func(func: str) -> str:
"""执行函数(exec可以执行Python代码)
:params func 字符的形式调用函数
: return 返回的将是个str类型的结果
"""
# 得到一个局部的变量字典,来修正exec函数中的变量,在其他函数内部使用不到的问题
loc = locals()
exec(f"result = {func}")
return str(loc['result'])
# 生成不重复的随机数
def a_b():
return 3
def b_d():
return 5
# 测试用例路径
excel_path = os.path.join(data_path,'test.xlsx')
# 读取测试用例
test_data = ExcelHandle(excel_path).get_data_case('test')
print(test_data)
# 将list格式的测试用例转化为 字符串格式
test_data = json.dumps(test_data,ensure_ascii=False)
print(type(test_data))
dict_data = {
"num" : 123
}
# 使用Template模板类 进行数据替换
test_data = Template(test_data).safe_substitute(dict_data)
# 使用函数值 替换 字符串中的 函数
for fun in re.findall('\\${(.*?)}',test_data):
print(fun)
try:
test_data = test_data.replace('${%s}' %fun, exec_func(fun))
except Exception as e:
print(e)
# 将 字符串 转化为 list
test_data = json.loads(test_data)
print(test_data)
print(type(test_data))
替换后的数据:
[{'ID': 1, 'title': '新增平台药品', 'project_name': 'add_platform_drug', 'is_upload': None, 'method': 'POST', 'content_type': None, 'url': '/web-admin/webhis/appmanage/main_drug_save.do', 'data': '{"a_b":"qqq3","condition.baseunit":"g","condition.classify":"2","condition.code":"csyp003","condition.name":"测试饮片123","condition.pharmacopoeia":"测试生产厂家","condition.spec":"g","condition.spell":"csyp02","condition.alias":"","condition.chemicname":"","condition.id":"","condition.num":"","b_d":"aaa5sss"}', 'expected_data': '{"code":0,"message":"添加成功!","object":null}', 'extract_data': None, 'assert_db': None}]