思路:1.根據(jù)yapi提供的開(kāi)放接口孽尽,獲取接口數(shù)據(jù)田巴,生成yaml文件
2.根據(jù)yaml文件內(nèi)容生成pytest文件
效果圖
生成的文件結(jié)構(gòu).png
生成的yaml模板.png
image.png
···
生成的代碼.png
已下是主要代碼
# 測(cè)試代碼中,判斷期望值用的查詢(xún)json值的方法
#遞歸查詢(xún)多級(jí)json直到找出所需要的key值
def josnFind(jsonb, key):
for k in jsonb:
if k == key:
return jsonb[k]
chlidType = type(jsonb[k])
if dict == chlidType:
return josnFind(jsonb[k], key)
# 測(cè)試代碼和生成代碼均需使用的方法
# yamlkey傳入值時(shí)锡凝,返回yaml文件中該key的值
# yamlkey不傳入時(shí)粘昨,默認(rèn)返回yaml 文件所有值
def get_test_data(filepath, yamlkey=0):
# validate = [] # 存放斷言
# path = str(os.path.abspath(
# os.path.join(os.path.dirname(__file__), os.pardir))) + r"\TestProject\Mallproject" + "\\" + filepath
path = filepath
# print(path)
with open(path, encoding='utf-8') as f:
data = yaml.load(f.read(), Loader=yaml.SafeLoader)
# print(data)
if yamlkey == 0:
return data
return data.get(yamlkey)
import json
import os
from string import Template
import yaml
import requests
from Util.common import get_test_data
token = "yapi 項(xiàng)目token"
YApibaseUrl = "yapi請(qǐng)求地址"
requests.adapters.DEFAULT_RETRIES = 100
#接口信息獲取
def get_list_menu(parm):
# time.sleep(5)
print("獲取菜單")
data = zrequests('/api/interface/getCatMenu', parm)
return data
def get_list_cat(parm, ):
# time.sleep(5)
print("獲取分類(lèi)下接口id")
# print()
data = zrequests('/api/interface/list_cat', parm)
return data
def get_interface(parm):
# time.sleep(5)
print("獲取接口詳情數(shù)據(jù)")
data = zrequests('/api/interface/get', parm)
return data
def zrequests(api, parm):
i = 0
while i < 3:
try:
data = requests.get(url=YApibaseUrl + api, params=parm, timeout=(60, 7))
s = requests.session()
s.keep_alive = False
break
except requests.exceptions.ConnectionError:
print('重試請(qǐng)求' + api, "第" + str(i) + "次")
i = i + 1
return data
# 創(chuàng)建yaml文件
#生成yaml模板數(shù)據(jù)
def createYamlData(data):
BorC = str(data['title'])[0:2]
path = str(data['path'])
method = str(data['method'])
body = getBody(data)
yamlData = {path.replace(r'/', '_'): {'method': method, 'path': path, 'parm': body, 'BorC': BorC, 'expect': None}}
return yamlData
#獲取接口請(qǐng)求參數(shù)
def getBody(data):
if 'req_body_other' in data:
jsonbody = json.loads(data['req_body_other'])['properties']
for key in jsonbody:
jsonbody[key] = getJsonValue(jsonbody[key], 'description') + ' ' + getJsonValue(jsonbody[key], 'type')
return jsonbody
else:
return None
def getJsonValue(jsonD, key):
if key in jsonD:
return jsonD[key]
else:
return 'NULL'
#創(chuàng)建yaml文件
def createDirandYaml(project_id, filedir):
#獲取接口分類(lèi)目錄,根據(jù)分類(lèi)創(chuàng)建文件夾
menu_catParm = {"token": token, "project_id": project_id}
menu_data = get_list_menu(menu_catParm).json()['data']
for menu in menu_data:
_id = menu['_id']
name = menu['name']
desc = str(menu['desc']).replace(' ', '')
if name == '公共分類(lèi)':
continue
menu_dir = filedir + desc
try:
os.mkdir(menu_dir)
except FileExistsError:
print("當(dāng)文件夾已存在時(shí)窜锯,無(wú)法創(chuàng)建該文件夾张肾。")
with open(menu_dir + "/" + desc + '.yaml', 'w', encoding='utf-8') as f: # 'a'代表持續(xù)寫(xiě)入,‘w’代表覆蓋寫(xiě)入
#創(chuàng)建yaml 文件衬浑,并寫(xiě)入數(shù)據(jù)
list_catParm = {"token": token, "catid": _id, "limit": 1000}
list_catData = get_list_cat(list_catParm).json()['data']['list']
apilist = []
for api in list_catData:
# 接口詳情
# print(list_catData)
api_catParm = {"token": token, "id": api['_id']}
api_data = get_interface(api_catParm).json()['data']
# print(type(api_data))
api_dataYaml = createYamlData(api_data)
apilist.append(api_dataYaml)
yaml.dump(api_dataYaml, f, allow_unicode=True, sort_keys=False)
def createCaseCode(path):
# 測(cè)試方法模板
a = Template("\n\ndef test${casename}():\n\
yamlpath = str(os.getcwd())+'${path}'\n\
parm = get_test_data(yamlpath, '_login_checkUserIsNew')\n\
print('\\n請(qǐng)求數(shù)據(jù):' + str(parm))\n\
response = requestsUtil(parm).json()\n\
print('返回?cái)?shù)據(jù):' + str(response))\n\
expect = parm['expect']\n\
for key in expect:\n\
assert str(josnFind(response, key)) == str(expect[key])\n")
for root, dirs, files in os.walk(path):
# print(type(root))
for file in files:
if '.yaml' in file:
# print(root + str(file).replace('.yaml', '.py'))
yamlPath = root + '\\' + str(file)
with open(root + '\\' + str(file).replace('.yaml', '.py'), 'w', encoding='utf-8') as f:
data = get_test_data(root + '\\' + file)
# 默認(rèn)導(dǎo)入
f.write("from TestProject.Mallproject.requestsUtil import requestsUtil\n\
from Util.common import get_test_data, josnFind\n\
import os\n")
for key in data:
f.write(a.substitute(casename=key, path=file))
print(data)