项目场景:
在接口自动化测试中,使用re模块对参数进行匹配查找
问题描述
例如:从用例中匹配:#(.*?)#的数据,进行替换
def replace_data(data):
'''
1.从yaml字典匹配字符#xxx#的字符
2.将找到的字符与配置文件进行替换,如果找到了,就去配置文件中替换或者去全局变量获取
'''
# data={"username": "#username#", "password": "abcd123", "system": "GW"}
res=re.findall("#(.*?)#",data)
if res:
for item in res:
try:
value=hc.get("test_data",item)
except:
try:
value=getattr(EvnData,item)
except AttributeError:
continue
data=data.replace("#{}#".format(item),value)
return data
结果报错
Traceback (most recent call last):
File "D:/wp/tool/pycharm/test/common/handle_data.py", line 34, in <module>
case = replace_data(case)
File "D:/wp/tool/pycharm/test/common/handle_data.py", line 16, in replace_data
res=re.findall("#(.*?)#",data)
File "D:\wp\tool\python\lib\re.py", line 223, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
原因分析:
re.finall()里面是对字符串进行匹配
解决方案:
提示:将finall()里面的数据转换为字符串:
case={"url":"/admin/login",
"method": "post",
"request_data": {"username": "#username#", "password": "abcd123", "system": "GW"},
"expect": {"msg": "操作成功", "code": 200}}
case=replace_data(str(case))
print(case)
|