yaml文件詳解---實現接口自動化
一、作用
1.用於全局的配置文件 ini yaml
2.用於寫測試用例(接口測試用例)
yaml簡介:
yaml是一種數據格式支持注釋,換行,多行字符串,裸字符串(整形,字符串)
安裝:pip install PyYAML
二、語法規則:
1.區分大小寫
2.通過縮進表示層級,不能用tab建縮進,只能用空格(和python一樣)
3.縮進沒有數量,只要前面是對其的就行
4.注釋是#
三、數據組成:檢查的時候用這個網站:https://www.bejson.com/validators/yaml_editor/ 可以直接換成json對象看看對不對
1.map對象,鍵值對 鍵:(空格)值
demo:第一張是多行的 寫法,第二張是一行的寫法,第三張是檢查的格式對不對
2.數組(list):用一組橫線表示 橫線后面有空格
四、讀取yaml文件
yaml文件的反序列化:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author:xiaomin pei
import yaml
class YamlUtil: def __init__(self, yaml_file): """ 通過init方法吧yaml文件傳入到這個類 :param yaml_file: """ self.yaml_file = yaml_file # 讀取yaml文件 def read_yaml(self): """ 讀取yaml,對yaml文件反序列化,就是我們的yaml格式轉換成字典的格式 :return: """ with open(self.yaml_file, encoding='utf-8') as f: value = yaml.load(f, Loader=yaml.FullLoader) print(value, type(value))
return value if __name__ == '__main__': YamlUtil('test_api.yaml').read_yaml()
五、接口自動化實戰:
首先看一個接口:(比較粗糙)
這是yaml文件里面的內容。測試用例2條
#用例1
-
name: 獲得token鑒權碼的接口
request:
url: https://api.weixin.qq.com/cgi-bin/token
method: get
headers:
Content-Type: application/json
params:
grant_type: client_credential
appid: wx6b11b3efd1cdc290
secret: 106a9c6157c4db5f6029918738f9529d
valicate:
- eq: {expires_in: 7200}
#用例2,反例
-
name: 獲得token鑒權碼的接口
request:
url: https://api.weixin.qq.com/cgi-bin/token
method: get
headers:
Content-Type: application/json
params:
appid: wx6b11b3efd1cdc290
secret: 106a9c6157c4db5f6029918738f9529d
valicate:
- eq: {errcode: 40002}
下面是python文件
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author:xiaomin pei
import pytest, requests
from testcase.yaml_util import YamlUtil class TestApi: @pytest.mark.parametrize('args', YamlUtil('test_api.yaml').read_yaml()) def test_01_shuguo(self, args): # url = "https://api.weixin.qq.com/cgi-bin/token" # params = { # "grant_type": "client_credential", # "appid": "wx6b11b3efd1cdc290", # "secret": "106a9c6157c4db5f6029918738f9529d" # } # url = args['request']['url'] params = args['request']['params'] res = requests.get(url=url, params=params) print("蜀國:", res.json(), type(res.json())) # 斷言 if res.json().get('expires_in'): assert args['request']['valicate'][0]['eq']['expires_in'] == res.json()['expires_in'] else: assert args['request']['valicate'][0]['eq']['errcode'] == res.json()['errcode'] if __name__ == '__main__': pytest.main(['-vs'])
擴展:
1.requests二次封裝
2.多重斷言
3.多接口的場景串聯
4.日志監控(日志文件的生成,控制台調試日志,郵件日志)