需求:
TestCase有时需要分批测试,请在@artt({....})内为文件内所有缺失应有tag的test case添加指定的测试tag.
例:
@artt({'P0': True, 'P1': True, 'reqId': ["12345"]})
添加 tag P2
-->
@artt({'P0': True, 'P1': True, 'P2': True, 'reqId': ["12345"]})
- re模块内的.sub()方法可以实现
https://lzone.de/examples/Python%20re.sub
with open("testpy.py") as f:
code_content = f.read()
pattern = re.compile(r"(@artt\({(?!.*P2.*).*?)'reqId'")
new = re.sub(pattern,r"\1 'P2': True, 'reqId'",code_content)
print(new)
要点
.sub(pattern, replace, string)
中的replace会替换掉整个match而不是哪一个capture group,
如果你想要保留match的其它部分只替换掉你想要的capture group,你非得将其他需要保留的部分也单独作为capture group用括号括起来,并在replace部分用/1 /2 /3
....的格式指代,在这种情况下,replace部分也要在引号前加r
标用来跳过/
符号。
如本例中,我先匹配所有@artt({
开头reqId
结尾的内部不含P2
的行,把'reqId'
前面的所有部分保留,把'reqId'
替换为'P2': True, 'reqId'
注意,replace部分的写法要为r"\1 'P2': True, 'reqId'"
最后,如果希望在正则表达式内使用变量,可以用string类型的.format()
方法将括号内的变量传入花括号{}
的位置。
def add_Tag_To_File(path,tag):
with open("testpy.py") as f:
code_content = f.read()
pattern = re.compile(r"(@artt\({(?!.*'P2'.*).*?)'reqId'")
replace = r"\1 '{}': True, 'reqId'"
new_code_content = re.sub(pattern,replace.format(tag),code_content)
return new_code_content
网友评论