Exemple #1
0
def request_api(host, params, headers, request_method):
    """
    接口请求
    :param host:
    :param params:
    :param headers:
    :param request_method:
    :return:
    """
    if request_method == "post":
        res = Http.post(host, params=params, headers=headers)
    elif request_method == "get":
        res = Http.get(host, params=params, headers=headers)
    else:
        log.error("ERRRR:暂不支持{}这种请求方式".format(method))
        return "ERRRR:暂不支持{}这种请求方式".format(method)
        # 如果调用创建用户或登录接口,将headers信息写入配置文件
    if "login.mobile" in host or "create_user" in host and res is not None:
        dis4 = re.findall(pat, res.headers["Set-Cookie"])
        if len(dis4) > 1:
            pc.wirte_info(HEADERS, "cookie", "DIS4={}".format(dis4[1]))
            log.info("headers信息写入配置文件成功--->{}".format(dis4[1]))
        else:
            pc.wirte_info(HEADERS, "cookie", "DIS4={}".format(dis4[0]))
            log.info("headers信息写入配置文件成功--->{}".format(dis4[0]))
    return res
Exemple #2
0
            #     apiParams = ""
            # if 0 != i and apiParams:
            #     # apiParams = json.loads(str(apiParams), encoding="utf8")
            #     apiParams = string.Template(apiParams)
            #     apiParams = apiParams.substitute(vars())
            #     result["apiParams"] = apiParams
            #     params = json.loads(apiParams, encoding="utf8")
            relatedApiId = a[RELATEDAPI]
            print("apiParmas----->{}".format(apiParams))
            if 0 != i and apiParams:
                apiParams = string.Template(apiParams)
                apiParams = apiParams.substitute(vars())
                apiParams = json.loads(apiParams, encoding="utf8")

            if apiMethod == "post":
                res = Http.post(apiHost, params=apiParams, headers=apiHeaders)
            else:
                res = Http.get(apiHost, params=apiParams, headers=apiHeaders)
            try:
                respJson = res.json()
            except:
                log.error("接口调用出错{}".format(res))
                respJson = {}
            # 判断relatedParams的数据类型,可能为list和str
            print("ssss")
            print("relatedParams------<>><><>{}".format(relatedParams))
            if relatedParams is not None and respJson:
                print("ggggg")
                if isinstance(relatedParams, str):
                    print("mmmm")
                    if relatedParams == HEADERS:
Exemple #3
0
def run():
    global cid, describe, host, method, params, checkPints, con, relatedApi, relatedParams, apiInfo, sqlStatement, databaseExpect, sqlResult

    '''
    是否为第一条用例,每次执行是获取第一条用例执行的headers信息写入配置文件
    之后接口测试用例中如果headers信息为空,则自动调用配置文件中的headers信息
    '''
    defaultHeaders = get_default_headers()  # 头信息
    # 开始测试之前先清除数据库前一次测试储存的数据
    con.truncate_data("testCase")
    con.truncate_data("testResult")
    con.truncate_data("apiInfo")
    # 测试结果集
    resultSet = []
    start_time = time.time()
    # 获取所有用例
    cases = HandleCase().get_cases()
    for case in cases:

        # 将用例存入数据库临时保存
        con.insert_data("testcase", **case)
        # 将接口数据插入数据库apiInfo表中暂时保存
        apiInfo = {"apiId": int(case["apiId"]), "apiHost": case["apiHost"], "apiParams": case["apiParams"],
                   "method": case["method"], "relatedApi": case["relatedApi"], "relatedParams": case["relatedParams"]}
        # 如果数据库中不存在apiId的接口,则插入
        if not con.query_all("select * from apiInfo  where apiId={}".format(apiInfo["apiId"])):
            con.insert_data("apiInfo", **apiInfo)

    for case in cases:
        allRelatedApi = []  # 所有关联api的信息
        result = {}
        relatedApi = case["relatedApi"]
        # relatedParams = case["relatedParams"]
        cid = case["caseId"]
        log.info("正在执行第{}条用例".format(cid))
        describe = str(case["caseDescribe"])
        host = str(case["apiHost"])
        checkPints = case["expect"]
        method = str(case["method"])
        params = str(case["apiParams"])
        headers = case["apiHeaders"]
        sqlStatement = str(case["sqlStatement"])
        databaseExpect = case["databaseExpect"]
        result["caseId"] = cid
        caseApi = con.query_one("select * from apiInfo where apiId={}".format(cid))  # 用例对应的api信息
        allRelatedApi.append(caseApi)
        result["caseDescribe"] = describe
        result["apiHost"] = host
        # 如果用例中headers信息没写,则调用配置文件中的headers信息
        if headers:
            headers = json.loads(headers, encoding="utf8")
        else:
            if host != "/s5/create_user":
                headers = defaultHeaders
            else:
                headers = ""
        if databaseExpect:
            result["databaseExpect"] = databaseExpect
        else:
            result["databaseExpect"] = " "
        if sqlStatement:
            sqlResult = con_server.query_all(sqlStatement)
        else:
            sqlResult = ""
        if sqlResult:
            result["databaseResult"] = str(sqlResult)
        else:
            result["databaseResult"] = " "
        if checkPints:
            result["expect"] = str(checkPints)
        else:
            result["expect"] = ""
        # 先获得用例执行时相关联的接口信息
        while True:
            if relatedApi is not None:
                relatedApiInfo = con.query_one("select * from apiInfo where apiId={}".format(relatedApi))
                relatedApi = relatedApiInfo["relatedApi"]
                allRelatedApi.append(relatedApiInfo)
                allRelatedApi.reverse()
            else:
                break
        if allRelatedApi:
            apiHeaders=headers
            for i in range(len(allRelatedApi)):
                if i < len(allRelatedApi) - 1:
                    a = allRelatedApi[i]  # 当前执行
                    b = allRelatedApi[i + 1]  # 下一个
                else:
                    a = allRelatedApi[i]
                    b = allRelatedApi[i]
                apiHost = a["apiHost"]
                apiParams = a["apiParams"]
                apiMethod = a["method"]
                relatedParams = b["relatedParams"]
                if relatedParams and ";" in relatedParams:
                    relatedParams = relatedParams.split(";")
                relatedApiId = a["relatedApi"]
                if 0 != i and apiParams:
                    # apiParams = json.loads(str(apiParams), encoding="utf8")
                    apiParams = string.Template(apiParams)
                    apiParams = apiParams.substitute(vars())
                    result["apiParams"] = apiParams
                    params = json.loads(apiParams, encoding="utf8")
                if apiMethod == "post":
                    resp = Http.post(apiHost, apiParams, headers=apiHeaders)
                else:
                    resp = Http.get(apiHost, params=apiParams, headers=apiHeaders)
                try:
                    respJson = resp.json()
                except:
                    log.error("接口调用出错{}".format(resp))
                    respJson = {}
                # 判断relatedParams的数据类型,可能为list和str
                if relatedParams is not None and respJson:
                    if isinstance(relatedParams, str):
                        if relatedParams == "headers":
                            apiHeaders={"cookie": resp.headers["Set-Cookie"]}
                    elif isinstance(relatedParams, list):
                        for i in relatedParams:
                            if isinstance(i, str):
                                var = locals()
                                var[i] = respJson[i]
                            elif isinstance(i, list):
                                var = locals()
                                var[i[1]] = respJson[i[0]][i[1]]
                            else:
                                log.error("参数错误")
                if apiHost == host:
                    result["fact"] = resp.text
                    check(expect=checkPints, fact=resp, result=result, databaseExpect=databaseExpect,
                          databaseResult=sqlResult)
                    # 如果调用了creat_user的接口,就将接口的headers信息写入配置文件
                    if host == "/s5/create_user" or host == "/s4/login.mobile":
                        write_headers((str(resp.headers["Set-Cookie"])))

        # 将执行结果写入数据库临时保存
        con.insert_data("testResult", **result)
        resultSet.append(result)
    end_time = time.time()
    time_consum = end_time - start_time  # 测试耗时
    case_count = con.query_all("SELECT caseId FROM testresult")  # 执行用例
    fail_case = con.query_all("SELECT caseId FROM testresult WHERE ispass='******'")  # 执行失败的用例
    block_case = con.query_all("SELECT caseId FROM testresult WHERE ispass='******'")  # 执行阻塞的用例
    success_case = con.query_all("SELECT caseId FROM testresult WHERE ispass='******'")  # 执行成功的用例
    if case_count is None:
        case_count = 0
    else:
        case_count = len(case_count)
    if fail_case is None:
        fail_case = 0
    else:
        fail_case = len(fail_case)
    if block_case is None:
        block_case = 0
    else:
        block_case = len(block_case)
    if success_case is None:
        success_case = 0
    else:
        success_case = len(success_case)
    result_info = "本次测试执行完毕,共耗时{}秒,共执行用例:{}条,成功:{}条,失败:{}条,阻塞:{}条".format(float("%.2f" % time_consum), case_count,

                                                                          success_case, fail_case, block_case)
    log.info(result_info)
    # 将测试结果写入测试报告
    report = Report()
    report.set_result_info(result_info)
    report.get_report(resultSet)
    # 关闭数据库
    con.close()
    con_server.close()