介面自動化測試:yaml檔案中變數替換
阿新 • • 發佈:2020-10-04
在做介面、UI自動化的時候,我們可以用yaml檔案來管理測試用例的步驟、資料,因為每次測試的資料需要動態變換,所以yaml檔案中相關引數可能需要用變量表示。那麼,我們怎麼進行變數的傳值呢?
這裡可以用到字串的模板替換功能,官方文件:https://docs.python.org/zh-cn/3/library/string.html#template-strings
yaml檔案中內容如下:
method: get
url: http://www.baidu.com
json:
key1: $value1
key2: $value2
其中,需要動態變換的引數值我們用$符號標識:$value1、$value2
下面進行yaml檔案的讀取,然後進行變數替換,替換後返回字典型別的值:
def yaml_template(self,data:dict):
with open("../data/test_template.yaml",encoding="utf-8") as f:
re = Template(f.read()).substitute(data)
return yaml.safe_load(re)
其中Template方法需要傳入一個字串,substitute方法傳入關鍵字引數或者字典,注意key與yaml檔案中的變數要對應
測試結果如下: