Ejemplo n.º 1
0
def test_api(host_id, case_id, project_id, _id):
    """
    执行接口测试
    :param host_id: 测试的host域名
    :param case_id: 测试用例ID
    :param _id:  用例下接口ID
    :param project_id: 所属项目
    :return:
    """
    host = GlobalHost.objects.get(id=host_id, project=project_id)
    data = AutomationCaseApiSerializer(
        AutomationCaseApi.objects.get(id=_id, automationTestCase=case_id)).data
    http_type = data['httpType']
    request_type = data['requestType']
    address = host.host + data['apiAddress']
    head = json.loads(
        serializers.serialize(
            'json', AutomationHead.objects.filter(automationCaseApi=_id)))
    header = {}
    request_parameter_type = data['requestParameterType']
    examine_type = data['examineType']
    http_code = data['httpCode']
    response_parameter_list = data['responseData']
    if http_type == 'HTTP':
        url = 'http://' + address
    else:
        url = 'https://' + address
    if data['requestParameterType'] == 'form-data':
        parameter_list = json.loads(
            serializers.serialize(
                'json',
                AutomationParameter.objects.filter(automationCaseApi=_id)))
        parameter = {}

        for i in parameter_list:
            key_ = i['fields']['name']
            value = i['fields']['value']

            try:
                if i['fields']['interrelate']:
                    interrelate_type = re.findall('(?<=<response\[).*?(?=\])',
                                                  value)
                    if interrelate_type[0] == "JSON":
                        api_id = re.findall('(?<=<response\[JSON]\[).*?(?=\])',
                                            value)
                        a = re.findall('(?<=\[").*?(?="])', value)
                        try:
                            param_data = eval(
                                json.loads(
                                    serializers.serialize(
                                        'json',
                                        AutomationTestResult.objects.filter(
                                            automationCaseApi=api_id[0])))[0]
                                ['fields']["responseData"])
                            for j in a:
                                param_data = param_data[j]
                        except Exception as e:
                            logging.exception(e)
                            record_results(
                                _id=_id,
                                url=url,
                                request_type=request_type,
                                header=header,
                                parameter=parameter,
                                host=host.name,
                                status_code=http_code,
                                examine_type=examine_type,
                                examine_data=response_parameter_list,
                                _result='ERROR',
                                code="",
                                response_data="")
                            return 'fail'
                    elif interrelate_type[0] == "Regular":
                        api_id = re.findall(
                            '(?<=<response\[Regular]\[).*?(?=\])', value)
                        pattern = re.findall('(?<=\[").*?(?="])', value)
                        param_data = json.loads(
                            serializers.serialize(
                                'json',
                                AutomationTestResult.objects.filter(
                                    automationCaseApi=api_id[0]))
                        )[-1]['fields']["responseData"]
                        param_data = re.findall(pattern[0],
                                                param_data.replace("\'",
                                                                   "\""))[0]
                    else:
                        record_results(_id=_id,
                                       url=url,
                                       request_type=request_type,
                                       header=header,
                                       parameter=parameter,
                                       host=host.name,
                                       status_code=http_code,
                                       examine_type=examine_type,
                                       examine_data=response_parameter_list,
                                       _result='ERROR',
                                       code="",
                                       response_data="")
                        return 'fail'
                    pattern = re.compile(r'<response\[.*]')
                    parameter[key_] = re.sub(pattern, str(param_data), value)

                else:
                    parameter[key_] = value
            except KeyError as e:
                logging.exception(e)
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               host=host.name,
                               status_code=http_code,
                               examine_type=examine_type,
                               examine_data=response_parameter_list,
                               _result='ERROR',
                               code="",
                               response_data="关联有误!")
                return 'fail'
        if data["formatRaw"]:
            request_parameter_type = "raw"

    else:
        parameter = AutomationParameterRawSerializer(
            AutomationParameterRaw.objects.filter(automationCaseApi=_id),
            many=True).data
        if len(parameter):
            if len(parameter[0]["data"]):
                try:
                    parameter = eval(parameter[0]["data"])
                except Exception as e:
                    logging.exception(e)
                    record_results(_id=_id,
                                   url=url,
                                   request_type=request_type,
                                   header=header,
                                   parameter=parameter,
                                   host=host.name,
                                   status_code=http_code,
                                   examine_type=examine_type,
                                   examine_data=response_parameter_list,
                                   _result='ERROR',
                                   code="",
                                   response_data="")
                    return 'fail'
            else:
                parameter = {}
        else:
            parameter = {}

    for i in head:
        key_ = i['fields']['name']
        value = i['fields']['value']
        if i['fields']['interrelate']:

            try:
                interrelate_type = re.findall('(?<=<response\[).*?(?=\])',
                                              value)
                if interrelate_type[0] == "JSON":
                    api_id = re.findall('(?<=<response\[JSON]\[).*?(?=\])',
                                        value)
                    a = re.findall('(?<=\[").*?(?="])', value)
                    try:
                        param_data = eval(
                            json.loads(
                                serializers.serialize(
                                    'json',
                                    AutomationTestResult.objects.filter(
                                        automationCaseApi=api_id[0])))[-1]
                            ['fields']["responseData"])
                        for j in a:
                            param_data = param_data[j]
                    except Exception as e:
                        logging.exception(e)
                        record_results(_id=_id,
                                       url=url,
                                       request_type=request_type,
                                       header=header,
                                       parameter=parameter,
                                       host=host.name,
                                       status_code=http_code,
                                       examine_type=examine_type,
                                       examine_data=response_parameter_list,
                                       _result='ERROR',
                                       code="",
                                       response_data="关联有误!")
                        return 'fail'
                elif interrelate_type[0] == "Regular":
                    api_id = re.findall('(?<=<response\[Regular]\[).*?(?=\])',
                                        value)
                    pattern = re.findall('(?<=\[").*?(?="])', value)
                    param_data = json.loads(
                        serializers.serialize(
                            'json',
                            AutomationTestResult.objects.filter(
                                automationCaseApi=api_id[0]))
                    )[0]['fields']["responseData"]
                    param_data = re.findall(pattern[0],
                                            param_data.replace("\'", "\""))[0]
                else:
                    record_results(_id=_id,
                                   url=url,
                                   request_type=request_type,
                                   header=header,
                                   parameter=parameter,
                                   host=host.name,
                                   status_code=http_code,
                                   examine_type=examine_type,
                                   examine_data=response_parameter_list,
                                   _result='ERROR',
                                   code="",
                                   response_data="")
                    return 'fail'
                pattern = re.compile(r'<response\[.*]')
                header[key_] = re.sub(pattern, str(param_data), value)
            except Exception as e:
                logging.exception(e)
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               host=host.name,
                               status_code=http_code,
                               examine_type=examine_type,
                               examine_data=response_parameter_list,
                               _result='ERROR',
                               code="",
                               response_data="关联有误!")
                return 'fail'
        else:
            header[key_] = value
    header["Content-Length"] = '%s' % len(str(parameter))
    try:
        if request_type == 'GET':
            code, response_data = get(header, url, request_parameter_type,
                                      parameter)
        elif request_type == 'POST':
            code, response_data = post(header, url, request_parameter_type,
                                       parameter)
        elif request_type == 'PUT':
            code, response_data = put(header, url, request_parameter_type,
                                      parameter)
        elif request_type == 'DELETE':
            code, response_data = delete(header, url, request_parameter_type,
                                         parameter)
        else:
            return 'ERROR'
    except ReadTimeout:
        logging.exception(ReadTimeout)
        record_results(_id=_id,
                       url=url,
                       request_type=request_type,
                       header=header,
                       parameter=parameter,
                       host=host.name,
                       status_code=http_code,
                       examine_type=examine_type,
                       examine_data=response_parameter_list,
                       _result='TimeOut',
                       code="408",
                       response_data="")
        return 'timeout'
    if examine_type == 'no_check':
        record_results(_id=_id,
                       url=url,
                       request_type=request_type,
                       header=header,
                       parameter=parameter,
                       host=host.name,
                       status_code=http_code,
                       examine_type=examine_type,
                       examine_data=response_parameter_list,
                       _result='PASS',
                       code=code,
                       response_data=response_data)
        return 'success'

    elif examine_type == 'json':
        if int(http_code) == code:
            if not response_parameter_list:
                response_parameter_list = "{}"
            try:
                logging.info(response_parameter_list)
                logging.info(response_data)
                result = check_json(json.loads(response_parameter_list),
                                    response_data)
            except Exception:
                logging.info(response_parameter_list)
                result = check_json(
                    eval(
                        response_parameter_list.replace('true',
                                                        'True').replace(
                                                            'false', 'False')),
                    response_data)
            if result:
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               status_code=http_code,
                               examine_type="JSON校验",
                               examine_data=response_parameter_list,
                               host=host.name,
                               _result='PASS',
                               code=code,
                               response_data=response_data)
            else:
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               status_code=http_code,
                               examine_type="JSON校验",
                               examine_data=response_parameter_list,
                               host=host.name,
                               _result='FAIL',
                               code=code,
                               response_data=response_data)
            return result
        else:
            record_results(_id=_id,
                           url=url,
                           request_type=request_type,
                           header=header,
                           parameter=parameter,
                           status_code=http_code,
                           examine_type="JSON校验",
                           examine_data=response_parameter_list,
                           host=host.name,
                           _result='FAIL',
                           code=code,
                           response_data=response_data)
            return 'fail'

    elif examine_type == 'only_check_status':
        if int(http_code) == code:
            record_results(_id=_id,
                           url=url,
                           request_type=request_type,
                           header=header,
                           parameter=parameter,
                           status_code=http_code,
                           examine_type="校验HTTP状态",
                           examine_data=response_parameter_list,
                           host=host.name,
                           _result='PASS',
                           code=code,
                           response_data=response_data)
            return 'success'
        else:
            record_results(_id=_id,
                           url=url,
                           request_type=request_type,
                           header=header,
                           parameter=parameter,
                           status_code=http_code,
                           examine_type="校验HTTP状态",
                           examine_data=response_parameter_list,
                           host=host.name,
                           _result='FAIL',
                           code=code,
                           response_data=response_data)
            return 'fail'

    elif examine_type == 'entirely_check':
        if int(http_code) == code:
            try:
                result = operator.eq(json.loads(response_parameter_list),
                                     response_data)
            except Exception as e:
                logging.exception(e)
                result = operator.eq(
                    eval(
                        response_parameter_list.replace('true',
                                                        'True').replace(
                                                            'false', 'False')),
                    response_data)
            if result:
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               status_code=http_code,
                               examine_type="完全校验",
                               examine_data=response_parameter_list,
                               host=host.name,
                               _result='PASS',
                               code=code,
                               response_data=response_data)
                return 'success'
            else:
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               status_code=http_code,
                               examine_type="完全校验",
                               examine_data=response_parameter_list,
                               host=host.name,
                               _result='FAIL',
                               code=code,
                               response_data=response_data)
                return 'fail'
        else:
            record_results(_id=_id,
                           url=url,
                           request_type=request_type,
                           header=header,
                           parameter=parameter,
                           status_code=http_code,
                           examine_type="完全校验",
                           examine_data=response_parameter_list,
                           host=host.name,
                           _result='FAIL',
                           code=code,
                           response_data=response_data)
            return 'fail'

    elif examine_type == 'Regular_check':
        if int(http_code) == code:
            try:
                logging.info(response_parameter_list)
                result = re.findall(response_parameter_list,
                                    json.dumps(response_data))
                logging.info(result)
            except Exception as e:
                logging.exception(e)
                return "fail"
            if result:
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               status_code=http_code,
                               examine_type="正则校验",
                               examine_data=response_parameter_list,
                               host=host.name,
                               _result='PASS',
                               code=code,
                               response_data=response_data)
                return 'success'
            else:
                record_results(_id=_id,
                               url=url,
                               request_type=request_type,
                               header=header,
                               parameter=parameter,
                               status_code=http_code,
                               examine_type="正则校验",
                               examine_data=response_parameter_list,
                               host=host.name,
                               _result='FAIL',
                               code=code,
                               response_data=response_data)
                return 'fail'
        else:
            record_results(_id=_id,
                           url=url,
                           request_type=request_type,
                           header=header,
                           parameter=parameter,
                           status_code=http_code,
                           examine_type="正则校验",
                           examine_data=response_parameter_list,
                           host=host.name,
                           _result='FAIL',
                           code=code,
                           response_data=response_data)
            return 'fail'

    else:
        record_results(_id=_id,
                       url=url,
                       request_type=request_type,
                       header=header,
                       parameter=parameter,
                       status_code=http_code,
                       examine_type=examine_type,
                       examine_data=response_parameter_list,
                       host=host.name,
                       _result='FAIL',
                       code=code,
                       response_data=response_data)
        return 'fail'
Ejemplo n.º 2
0
def test_api(host_id, case_id, project_id, _id):
    """
    执行接口测试
    :param host_id: 测试的host域名
    :param case_id: 测试用例ID
    :param _id:  用例下接口ID
    :param project_id: 所属项目
    :return:
    """
    host = GlobalHost.objects.get(id=host_id, project=project_id).host
    data = AutomationCaseApiSerializer(AutomationCaseApi.objects.get(id=_id, automationTestCase=case_id)).data
    if data['requestParameterType'] == 'form-data':
        parameter_list = json.loads(serializers.serialize('json',
                                                          AutomationParameter.objects.filter(automationCaseApi=_id)))
        parameter = {}

        for i in parameter_list:
            key_ = i['fields']['name']
            value = i['fields']['value']

            try:
                if i['fields']['interrelate']:
                    api_id = re.findall('(?<=<response\[).*?(?=\])', value)
                    a = re.findall('(?<=\[").*?(?="])', value)
                    try:
                        value = eval(json.loads(serializers.serialize(
                            'json',
                            AutomationTestResult.objects.filter(automationCaseApi=api_id[0])))
                                     [0]['fields']["responseData"])
                        for j in a:
                            value = value[j]
                    except:
                        return 'fail'
            except KeyError:
                return 'fail'

            parameter[key_] = value
    else:
        parameter = AutomationParameterRawSerializer(AutomationParameterRaw.objects.filter(automationCaseApi=_id),
                                                     many=True).data
        if len(parameter[0]["data"]):
            try:
                parameter = eval(parameter[0]["data"])
            except:
                parameter = []
        else:
            parameter = []
    http_type = data['httpType']
    request_type = data['requestType']
    address = host + data['address']
    head = json.loads(serializers.serialize('json', AutomationHead.objects.filter(automationCaseApi=_id)))
    header = {}

    for i in head:
        key_ = i['fields']['name']
        value = i['fields']['value']
        if i['fields']['interrelate']:

            try:
                api_id = re.findall('(?<=<response\[).*?(?=\])', value)
                a = re.findall('(?<=\[").*?(?="])', value)
                value = eval(json.loads(serializers.serialize(
                    'json',
                    AutomationTestResult.objects.filter(automationCaseApi=api_id[0])))[0]['fields']["responseData"])
                for j in a:
                    value = value[j]
            except Exception as e:
                logging.exception("ERROR")
                logging.error(e)
                return 'fail'

        header[key_] = value

    request_parameter_type = data['requestParameterType']
    examine_type = data['examineType']
    if http_type == 'HTTP':
        url = 'http://'+address
    else:
        url = 'https://'+address
    if request_type == 'GET':
        code, response_data = get(header, url, request_parameter_type, parameter)
    elif request_type == 'POST':
        code, response_data = post(header, url, request_parameter_type, parameter)
    elif request_type == 'PUT':
        code, response_data = post(header, url, request_parameter_type, parameter)
    elif request_type == 'DELETE':
        code, response_data = post(header, url, request_parameter_type, parameter)
    else:
        return 'fail'

    http_code = data['httpCode']
    response_parameter_list = data['responseData']
    header["Content-Length"] = '%s' % len(str(parameter))
    if examine_type == 'no_check':
        record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                       status_code=http_code, examine_type="不校验", examine_data=response_parameter_list,
                       _result='PASS', code=code, response_data=response_data)
        return 'success'

    elif examine_type == 'json':
        if int(http_code) == code:
            try:
                result = check_json(eval(response_parameter_list), response_data)
            except:
                return 'fail'
            if result:
                record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                               status_code=http_code, examine_type="JSON校验", examine_data=response_parameter_list,
                               _result='PASS', code=code, response_data=response_data)
            else:
                record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                               status_code=http_code, examine_type="JSON校验", examine_data=response_parameter_list,
                               _result='FAIL', code=code, response_data=response_data)
            return result
        else:
            record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                           status_code=http_code, examine_type="JSON校验", examine_data=response_parameter_list,
                           _result='FAIL', code=code, response_data=response_data)
            return 'fail'

    elif examine_type == 'only_check_status':
        if int(http_code) == code:
            record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                           status_code=http_code, examine_type="校验HTTP状态", examine_data=response_parameter_list,
                           _result='PASS', code=code, response_data=response_data)
            return 'success'
        else:
            record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                           status_code=http_code, examine_type="校验HTTP状态", examine_data=response_parameter_list,
                           _result='FAIL', code=code, response_data=response_data)
            return 'fail'

    elif examine_type == 'entirely_check':
        if int(http_code) == code:
            try:
                result = operator.eq(eval(response_parameter_list), response_data)
            except:
                return 'fail'
            if result:
                record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                               status_code=http_code, examine_type="完全校验", examine_data=response_parameter_list,
                               _result='PASS', code=code, response_data=response_data)
                return 'success'
            else:
                record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                               status_code=http_code, examine_type="完全校验", examine_data=response_parameter_list,
                               _result='FAIL', code=code, response_data=response_data)
                return 'fail'
        else:
            record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                           status_code=http_code, examine_type="完全校验", examine_data=response_parameter_list,
                           _result='FAIL', code=code, response_data=response_data)
            return 'fail'

    elif examine_type == 'Regular_check':
        if int(http_code) == code:
            try:
                result = re.findall(response_parameter_list, str(response_data))
            except:
                return "fail"
            if result:
                record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                               status_code=http_code, examine_type="正则校验", examine_data=response_parameter_list,
                               _result='PASS', code=code, response_data=response_data)
                return 'success'
            else:
                record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                               status_code=http_code, examine_type="正则校验", examine_data=response_parameter_list,
                               _result='FAIL', code=code, response_data=response_data)
                return 'fail'
        else:
            record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                           status_code=http_code, examine_type="正则校验", examine_data=response_parameter_list,
                           _result='FAIL', code=code, response_data=response_data)
            return 'fail'

    else:
        record_results(_id=_id, url=url, request_type=request_type, header=header, parameter=parameter,
                       status_code=http_code, examine_type=examine_type, examine_data=response_parameter_list,
                       _result='FAIL', code=code, response_data=response_data)
        return 'fail'