python 自動生成yaml測試模板,測試代碼

思路:1.根據(jù)yapi提供的開放接口,獲取接口數(shù)據(jù),生成yaml文件
2.根據(jù)yaml文件內(nèi)容生成pytest文件

效果圖

生成的文件結(jié)構(gòu).png

生成的yaml模板.png

image.png

···


生成的代碼.png

已下是主要代碼

# 測試代碼中,判斷期望值用的查詢json值的方法
#遞歸查詢多級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)

#    測試代碼和生成代碼均需使用的方法
#    yamlkey傳入值時,返回yaml文件中該key的值
#    yamlkey不傳入時,默認(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 項目token"
YApibaseUrl = "yapi請求地址"
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("獲取分類下接口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('重試請求' + 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

#獲取接口請求參數(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):
#獲取接口分類目錄,根據(jù)分類創(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 == '公共分類':
            continue
        menu_dir = filedir + desc
        try:
            os.mkdir(menu_dir)
        except FileExistsError:
            print("當(dāng)文件夾已存在時,無法創(chuàng)建該文件夾。")
        with open(menu_dir + "/" + desc + '.yaml', 'w', encoding='utf-8') as f:  # 'a'代表持續(xù)寫入,‘w’代表覆蓋寫入
   #創(chuàng)建yaml 文件,并寫入數(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):
    #  測試方法模板
    a = Template("\n\ndef test${casename}():\n\
    yamlpath = str(os.getcwd())+'${path}'\n\
    parm = get_test_data(yamlpath, '_login_checkUserIsNew')\n\
    print('\\n請求數(shù)據(jù):' + str(parm))\n\
    response = requestsUtil(parm).json()\n\
    print('返回數(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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容