使用 Python 中 re 模块对测试用例参数化,进行搜索 search、替换 sub

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

使用 Python 中 re 模块对测试用例参数化,进行搜索 search、替换 sub

守护往昔   2020-01-05 我要评论

  自动化测试用例,如果一百个接口要在Excel写100个sheet表单,每个接口有10个字段,里面有5个都可能是变化的,需要使用参数化,先试用特定的字符进行站位,在构造参数时在进行替换占位符;

一、用力中手机号的替换,以字符串中的方法,使用 replace (译:瑞破类似) 进行替换

# 原始字符串:{"mobilephone": "${not_existed_tel}", "pwd":"123456"}
# json 字符串
src_str = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'
# 替换 json 字符串中 ${not_existed_tel} 为 18845820369
print(src_str.replace("${not_existed_tel}", "18845820369"))

# 结果:{"mobilephone": "18845820369", "pwd":"123456"}

二、使用 re 模块进行替换

  re 正则表达式,是一个查找、搜索、替换文本的一种格式语言

搜索方法一,re 模块中的 match(译:马驰)方法,match方法是从头开始匹配

import re


# 1. 创建原始字符串(待替换的字符串)
src_str4 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'

# 2. 定义模式字符串去进行匹配
# 模式字符串 == 模子,以这个模板去原始字符串中进行比对

# 方法一,re 正则中的 match(译:马驰)方法,match方法是从头开始匹配
# 从 { 开始,匹配不上, 那么就回复None
res = re.match("{not_existed_tel}", src_str4)
print(res)  # 结果:None

# 从 { 开始,能匹配上, 会返回Match对象,加r不需要转义
res = re.match(r'{"mobilephone"', src_str4)
print(res)      # 返回Match对象结果:<re.Match object; span=(0, 14), match='{"mobilephone"'>

# 获取匹配的结果内容 group (译:歌如破)
a = res.group()
print(a)        # 结果:{"mobilephone"

搜索方法二:search   (译:涩吃)方法,只匹配一次

import re


# 1. 创建原始字符串(待替换的字符串)
src_str1 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'

# 2. 定义模式字符串去进行匹配
# 模式字符串 == 模子,以这个模板去原始字符串中进行比对:"${not_existed_tel}"

# 方法二:search (译:涩吃)方法,只匹配一次
# 如果能匹配上会返回Match对象,匹配不上会返回None
# 美元符号需要转义加 r,特殊字符都需要转义
res1 = re.search(r"\${not_existed_tel}", src_str1)
print(res1)     # Match对象结果:<re.Match object; span=(17, 35), match='${not_existed_tel}'>

# 获取匹配到的结果,group(译:格如破)方法
b = res1.group()
print(b)    # 结果:${not_existed_tel}

搜索方法三:findall  (译:范德奥)方法,会匹配很多次

src_str1 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'
res2 = re.findall(r'o', src_str1)
print(res2)     # 直接返回列表结果:['o', 'o', 'o']

替换方法: sub  (译:萨博)方法

import re


# 1. 创建原始字符串(待替换的字符串)
src_str2 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'

# 第一个参数为模式字符串:${not_existed_tel}
# 第二个参数为新的字符串:18845820369
# 第三个参数为原始的字符串
# sub 方法如果能匹配上, 那么会返回替换之后的字符串
# sub 方法如果匹配不上, 那么直接返回原始的字符串

# 使用 search 方法先搜索,搜索到再用 sub 方法进行替换;count=0 默认匹配一次
if re.search(r"\${not_existed_tel}", src_str2):     # 先搜索
    res2 = re.sub(r"\${not_existed_tel}", "18845820369", src_str2)  # 在替换
    print(res2)
else:
    print("无法匹配原始字符串")
# 替换后结果:{"mobilephone": "18845820369", "pwd":"123456"}

# 使用正则匹配:\w+ 单词字符[A-Za-z0-9_],+ 多次匹配;通过正则在原始字符串中匹配
if re.search(r"\${\w+}", src_str2):     # 先搜索
    res2 = re.sub(r"\${not_existed_tel}", "18845820369", src_str2)  # 在替换
    print(res2)
else:
    print("无法匹配原始字符串")
# 替换后结果:{"mobilephone": "18845820369", "pwd":"123456"}

 

 

*******请大家尊重原创,如要转载,请注明出处:转载自:https://www.cnblogs.com/shouhu/   谢谢!!******* 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们