一、yaml簡介
yaml:一種標記語言,專門用來寫配置文件。
二、yaml基礎語法
- 區分大小寫;
- 使用縮進表示層級關系;
- 使用空格鍵縮進,而非Tab鍵縮進
- 縮進的空格數目不固定,只需要相同層級的元素左側對齊;
- 文件中的字符串不需要使用引號標注,但若字符串包含有特殊字符則需用引號標注;
- 注釋標識為#
三、yaml的數據結構
- 對象:鍵值對的集合(簡稱 "映射或字典")
鍵值對用冒號 “:” 結構表示,冒號與值之間需用空格分隔 - 數組:一組按序排列的值(簡稱 "序列或列表")
數組前加有 “-” 符號,符號與值之間需用空格分隔 - 純量(scalars):單個的、不可再分的值(如:字符串、bool值、整數、浮點數、時間、日期、null等)
None值可用null可 ~ 表示
四、使用python讀取yaml常見的數據結構
前提:python中讀取yaml文件前需要安裝pyyaml和導入yaml模塊。
python讀取yaml:
# get_yaml.py import yaml def get_yaml_data(yaml_file): print("*****獲取yaml數據*****") with open(yaml_file, encoding='utf-8')as file: content = file.read() print(content) print(type(content)) print("\n*****轉換yaml數據為字典或列表*****") # 設置Loader=yaml.FullLoader忽略YAMLLoadWarning警告 data = yaml.load(content, Loader=yaml.FullLoader) print(data) print(type(data)) print(data.get('my')) # 類型為字典 <class 'dict'>
# print(data[0]["model"]) # 若類型為列表 <class 'list'>
if __name__ == "__main__": get_yaml_data("config.yaml")
1、yaml鍵值對:即python中的字典
# config.yaml user: my pwd: 1111
運行結果:
*****獲取yaml數據***** # yaml鍵值對:即python中的字典 user: my pwd: 1111
<class 'str'> *****轉換yaml數據為字典或列表***** {'user': 'my', 'pwd': 1111} <class 'dict'> my
2、yaml鍵值對嵌套:即python中的字典嵌套字典
# config.yaml user1: name: a pwd: 111222 user2: name: b pwd: 222333
運行結果:
*****獲取yaml數據***** user1: name: a pwd: 111222 user2: name: b pwd: 222333 <class 'str'> *****轉換yaml數據為字典或列表***** {'user1': {'name': 'a', 'pwd': 111222}, 'user2': {'name': 'b', 'pwd': 222333}} <class 'dict'> {'name': 'a', 'pwd': 111222}
3、yaml鍵值對中嵌套數組
# config.yaml user3: - a - b user4: - d - e
運行結果:
*****獲取yaml數據***** user3: - a - b user4: - d - e <class 'str'> *****轉換yaml數據為字典或列表***** {'user3': ['a', 'b'], 'user4': ['d', 'e']} <class 'dict'> ['a', 'b']
4、yaml數組中嵌套鍵值對
# config.yaml - user1: aaa - pwd1: 111 user2: bbb pwd2: 222
運行結果:
*****獲取yaml數據***** - user1: aaa - pwd1: 111 user2: bbb pwd2: 222 <class 'str'> *****轉換yaml數據為字典或列表***** [{'user1': 'aaa'}, {'pwd1': 111, 'user2': 'bbb', 'pwd2': 222}] <class 'list'> # 注意,此時的類型為list而非dict, 所以用下標訪問,即data[0]["user1"] aaa
5、yaml中純量
# config.yaml s_val: hello world num_val: 15 bol_val: true nul_val: null data_val: 2020-08-17
運行結果:
*****獲取yaml數據***** s_val: hello world num_val: 15 bol_val: true nul_val: null data_val: 2020-08-17 <class 'str'> *****轉換yaml數據為字典或列表***** {'s_val': 'hello world', 'num_val': 15, 'bol_val': True, 'nul_val': None, 'data_val': datetime.date(2020, 8, 17)} <class 'dict'> hello world
案例實踐:
# config.yaml # 使用-分隔用例,則yaml讀取到的數據類型為列表 - model: 注冊模塊 title: 注冊成功 url: http://api.nnzhp.cn/api/user/user_reg method: POST data: username: yingcr8 pwd: Ace123456 cpwd: Ace123456 check: error_code: 0 msg: 注冊成功! - model: 注冊模塊 title: 用戶名長度小於6位,注冊失敗 url: http://api.nnzhp.cn/api/user/user_reg method: POST data: username: yingc pwd: Ace123456 cpwd: Ace123456 check: error_code: 3002
# get_yaml.py import requests import yaml import urllib3 import json urllib3.disable_warnings() class SignTest(): def __init__(self, file): self.file = file def test_sign(self): with open(self.file, encoding='utf-8') as fobj: content = fobj.read()
# 使用 yaml.load()將yaml數據轉換為list或dict data = yaml.load(content, Loader=yaml.FullLoader)
# 使用for循環,依次讀取測試用例 for i in range(len(data)): # 從config.yaml中提取接口的參數
# 由於讀取到的數據類型為list列表,所以只能用下標訪問 model = data[i]['model'] title = data[i]['title'] url = data[i]['url'] method = data[i]['method'] datas = data[i]['data'] check = data[i]['check'] self.sign_test(model, title, url, method, datas, check) def sign_test(self, model, title, url, method, datas, check): print("模塊:", model) print("用例標題:", title) response = requests.request(url=url, method=method, data=datas) response = json.loads(response.text) print(response) try: # 通過斷言,判斷實際結果是否與預期結果一致 assert check['error_code'] == response['error_code'] print("測試通過\n") except Exception: print("測試失敗\n") if __name__ == "__main__": signtest = SignTest("config.yaml") signtest.test_sign()
運行結果:
模塊: 注冊模塊 用例標題: 注冊成功 {'error_code': 0, 'msg': '注冊成功!'} 測試通過 模塊: 注冊模塊 用例標題: 用戶名長度小於6位,注冊失敗 {'error_code': 3002, 'msg': '用戶名長度為6-10位!'} 測試通過
參考:https://www.jianshu.com/p/eaa1bf01b3a6