Ejemplo n.º 1
0
def deal_ssh_command(root):
    step = importOfflineCase_step()
    step.set_stepname(root.get("testname"))
    step.set_stepdes(root.get("testname"))
    steps = [step.get_step()]

    # 添加脚本
    script_name = "ssh_jmeter_smart_route"
    ssh_connect = "smart_route_jmeter_ssh"
    ds = dealScriptData(base_name)
    ds.set_ssh_with_default(script_name, ssh_connect, root.get("testname"))
    resp, script_id = post_blade.dealScriptData(ds)
    # 添加数据
    data_content = list()
    temp = dict()
    temp["sheet0"] = list()
    data_chose_row = random_uuid(32)
    one = [random_uuid(32), "序号", "期望", "command"]
    two = [random_uuid(32), "参数说明", "", "脚本文件需要事先放到redis的bin目录下"]
    three = [
        data_chose_row, "", "keyword=OK", "EXEC,sh {};".format(
            root.element.find(".//stringProp[@name='command']").text)
    ]
    temp["sheet0"].append(one)
    temp["sheet0"].append(two)
    temp["sheet0"].append(three)
    data_content.append(temp)

    step.set_scriptcontent(script_id)
    step.set_dataarrcontent(data_chose_row, data_content)

    return steps
Ejemplo n.º 2
0
def deal_redis_beanshellsampler(root):
    # 添加脚本
    script_name = "redis_jmeter_smart_route"
    ssh_connect = "smart_route_jmeter_redis"
    ds = dealScriptData(base_name)
    ds.set_ssh_with_default(script_name, ssh_connect, root.get("testname"))
    resp, script_id = post_blade.dealScriptData(ds)
    # 添加数据
    data_content = list()
    temp = dict()
    temp["sheet0"] = list()
    data_chose_row = random_uuid(32)
    one = [random_uuid(32), "序号", "期望", "command"]
    two = [random_uuid(32), "参数说明", "", "脚本文件需要事先放到redis的bin目录下"]
    three = [
        data_chose_row, "", "keyword=OK", "EXEC,sh clear_redis_smart_route.sh;"
    ]
    temp["sheet0"].append(one)
    temp["sheet0"].append(two)
    temp["sheet0"].append(three)
    data_content.append(temp)

    step = importOfflineCase_step()
    step.set_stepname(root.tag + root.get("testname"))
    step.set_stepdes(root.get("testname"))
    step.set_scriptcontent(script_id)
    step.set_dataarrcontent(data_chose_row, data_content)
    return step.get_step()
Ejemplo n.º 3
0
def deal_transaction_controller(root, node_path):
    steps = []

    sub_elements = root.get_sub_elements()
    # 获取到所有关键组件
    step_num = len(steps)
    for sub_element in sub_elements:
        # 组件为禁用状态, 不读取
        if not sub_element.isEnabled():
            continue

        if sub_element.tag == "HTTPSamplerProxy":
            step_num += 1
            path = sub_element.element.find(
                ".//stringProp[@name='HTTPSampler.path']").text
            script_name = path.split("/")[-1]
            logger.debug("script_name:%s" % script_name)
            # 先添加脚本
            ds = dealScriptData(node_path)
            ds.set_data_with_default(script_name, root_url, path)
            resp, script_id = post_blade.dealScriptData(ds)
            # 再添加数据
            steps.append(
                deal_HTTPSampler(sub_element, "步骤-" + str(step_num),
                                 script_id))
        elif sub_element.tag == "JDBCSampler":
            steps += deal_JDBCSample(sub_element)
    return steps
Ejemplo n.º 4
0
def deal_transaction_controller(root, node_path, steps):
    sub_elements = root.get_sub_elements()
    # 获取到所有关键组件
    step_num = len(steps)
    step_object = None

    for sub_element in sub_elements:
        # 组件为禁用状态, 不读取
        if not sub_element.isEnabled():
            continue

        if sub_element.tag == "HTTPSamplerProxy":
            step_num += 1
            path = sub_element.element.find(".//stringProp[@name='HTTPSampler.path']").text
            script_name = path.split("/")[-1]
            logger.debug("script_name:%s" % script_name)
            # 先添加脚本
            ds = dealScriptData(node_path)
            ds.set_data_with_default(script_name, root_url, path)
            resp, script_id = post_blade.dealScriptData(ds)
            # 再添加数据
            steps.append(deal_HTTPSampler(sub_element, "步骤-" + str(step_num), script_id))
        elif sub_element.tag == "ConstantTimer":
            wait_time_text = sub_element.element.find(".//stringProp[@name='ConstantTimer.delay']").text
            wait_time = int(wait_time_text) // 1000
            if wait_time == 0:
                wait_time = 1
            script_name = "wait_" + str(wait_time) + "s"
            # 新增一个定时延迟的脚本
            ds = dealScriptData(node_path)
            ds.set_wait_with_default(script_name, wait_time, sub_element.get("testname"))
            resp, script_id = post_blade.dealScriptData(ds)
            # 处理定时器
            steps.append(deal_constanttimer(sub_element, "步骤-" + str(step_num), script_id))
        elif sub_element.tag == "JDBCSampler":
            steps.append(deal_JDBCSample(sub_element))
        elif sub_element.tag == "BeanShellSampler":
            # redis beanshell 脚本处理
            if "redis" in sub_element.get("testname"):
                # 添加脚本
                script_name = "redis_jmeter"
                ssh_connect = "redis_jmeter"
                ds = dealScriptData(node_path)
                ds.set_ssh_with_default(script_name, ssh_connect, sub_element.get("testname"))
                resp, script_id = post_blade.dealScriptData(ds)
                # 添加数据
                steps.append(deal_redis_beanshellsampler(sub_element, "步骤-" + str(step_num), script_id))
            else:
                # 其他处理方式, 默认为报文
                step_object = deal_msg_beanshellsampler(sub_element, "步骤-" + str(step_num))
        elif sub_element.tag == "org.apache.jmeter.protocol.MQComm.sampler.MQPutMessageSampler":
            if step_object is not None:
                ibm_mq_message = dict()
                ibm_mq_message["connect"] = ibm_mq_connect
                manager = jmeter_get_argument_value(sub_element.element.find(
                    ".//stringProp[@name='MQPutMessageSampler.MQ_MANAGER']").text)
                logger.debug(manager)
                ibm_mq_message["manager"] = manager
                queue = jmeter_get_argument_value(sub_element.element.find(
                    ".//stringProp[@name='MQPutMessageSampler.MQ_QUEUE']").text)
                logger.debug(queue)
                ibm_mq_message["queue"] = queue
                channel = jmeter_get_argument_value(sub_element.element.find(
                    ".//stringProp[@name='MQPutMessageSampler.MQ_CHANNEL']").text)
                logger.debug(channel)
                ibm_mq_message["channel"] = channel
                ccsid = jmeter_get_argument_value(sub_element.element.find(
                    ".//stringProp[@name='MQPutMessageSampler.MQ_CCSID']").text)
                logger.debug(ccsid)
                ibm_mq_message["ccsid"] = ccsid
                # 添加脚本
                ds = dealScriptData(node_path)
                ds.set_mq_with_default(ibm_mq_connect, ibm_mq_message)
                resp, script_id = post_blade.dealScriptData(ds)
                # 添加数据
                step_object.set_scriptcontent(script_id)
                step = step_object.get_step()
                steps.append(step)
            else:
                logger.debug("IBM MQ 组件前没有获取到对应的Msg BeanShell 组件")
Ejemplo n.º 5
0
def deal_HTTPSampler(root, step_name, request_body="", check_message=""):
    # 没有传入报文内容, 自行获取当前报文内容, 否则使用传入内容
    # 通过获取到的报文参数个数确认是否为json格式或者其他格式
    content_type = None
    if not request_body:
        arguments = root.element.findall(
            ".//elementProp[@elementType='HTTPArgument']")
        if len(arguments) == 1 and arguments[0].find(
                ".//stringProp[@name='Argument.name']") is None:
            request_body = arguments[0].find(
                ".//stringProp[@name='Argument.value']").text
        else:
            content_type = "application/x-www-form-urlencoded"
            body = dict()
            for argument in arguments:
                key = argument.find(
                    ".//stringProp[@name='Argument.name']").text
                value = argument.find(
                    ".//stringProp[@name='Argument.value']").text
                body[key] = value
                logger.debug(key)
                logger.debug(value)
            request_body = str(body)

    # 生成脚本
    path = root.element.find(".//stringProp[@name='HTTPSampler.path']").text
    logger.debug(path)
    # 先添加脚本
    ds = dealScriptData(base_name)
    ds.set_data_with_default(root.get("testname"),
                             root_url,
                             path,
                             content_type=content_type)
    resp, script_content = post_blade.dealScriptData(ds)

    check_string = ""
    # 报文提取
    step = dict()
    step_json = dict()
    data_content = dict()
    step["stepName"] = step_name
    step["stepJson"] = step_json
    step_json["dataContent"] = data_content
    step_json["stepDes"] = root.get("testname")
    # 0—前置,1-后置,2-空
    step_json["precisionTest"] = "2"
    pre_sqls = list()
    step_json["preSqlContent"] = pre_sqls
    step_json["scriptContent"] = script_content

    # request 特殊处理, 将其中使用的变量替换成blade变量
    argument_re = re.compile(r'\${(.*?)}', re.S)
    arguments = re.findall(argument_re, request_body)
    for argument in arguments:
        # 不替换 jmeter 自带变量
        if argument.startswith("__"):
            continue
        # 变量的写法可能是 ${test}, '${test}', "${test}"
        # 三种都替换
        jmeter_argument = '"${' + argument + '}"'
        blade_argument = '"varc_' + argument + '"'
        request_body = request_body.replace(jmeter_argument, blade_argument)
        jmeter_argument = "'${' + argument + '}'"
        request_body = request_body.replace(jmeter_argument, blade_argument)
        jmeter_argument = '${' + argument + '}'
        request_body = request_body.replace(jmeter_argument, blade_argument)

    sub_elements = root.get_sub_elements()
    for sub_element in sub_elements:
        # 前置提取
        if sub_element.tag == "JDBCPreProcessor":
            data_source = sub_element.element.find(
                ".//stringProp[@name='dataSource']").text
            sql = sub_element.element.find(".//stringProp[@name='query']").text
            logger.debug(sql)
            pre_sql = {
                # 暂没遇到, 遇到后修改
                "connection": data_sources[data_source],
                "id": "",
                "type": "2",
                "content": "%s" % sql
            }
            pre_sqls.append(pre_sql)
        # 后置提取
        # 验证提取
        elif sub_element.tag == "BeanShellAssertion":
            if not check_message:
                assert_text = sub_element.element.find(
                    ".//stringProp[@name='BeanShellAssertion.query']").text
                results = re.findall(r'"(.*?)".equals\("(.*?)"\)', assert_text)
                logger.debug(results)
                for result in results:
                    if not results.index(result) == 0:
                        check_message += ";"
                    if "respcode" in result[1].lower():
                        if "UNKNOWN" in result[0].upper():
                            continue
                        check_message += check_msg_head + 'respCode=' + result[
                            0]
                    elif "respmsg" in result[1].lower():
                        check_message += check_msg_head + 'respMsg=' + result[0]
                    elif "servicestatus" in result[1].lower():
                        check_message += check_msg_head + 'serviceStatus=' + result[
                            0]

            check_string = check_message
    logger.debug(request_body)
    data_content["dataChoseRow"], data_content["dataArrContent"] = Josn2Blade(
        eval(request_body), [], 0, check_string)
    data_content["id"] = ""
    data_content["content"] = ""

    logger.debug(step)
    return step
Ejemplo n.º 6
0
def deal_threadgroup(root, node_path):
    # HTTP 组件
    http_companents = []

    # 线程组名称, 作为用例节点的父级目录名称
    thread_group_name = root.get("testname")
    logger.info(node_path)
    sub_elements = root.get_sub_elements()

    # 如果是csv格式的,包含了控制器,特殊处理
    if sub_elements[0].tag == "TransactionController":
        sub_elements = sub_elements[0].get_sub_elements()

    # 初始化导入用例请求
    ioc = importOfflineCase(node_path + thread_group_name)

    messages = []
    # 获取到所有关键组件
    for sub_element in sub_elements:
        # 组件为禁用状态, 不读取
        if not sub_element.isEnabled():
            continue

        # 从 Beanshell 中将读取的csv文件key取出
        if sub_element.tag in ("BeanShellSampler",
                               "BeanShellPreProcessor") and not messages:
            if sub_element.tag == "BeanShellSampler":
                java_code = sub_element.element.find(
                    ".//stringProp[@name='BeanShellSampler.query']").text
            else:
                java_code = sub_element.element.find(
                    ".//stringProp[@name='script']").text
            # 获取csv 路径 key
            csv_re = re.compile(r'FileInputStream[(]vars.get[(]"(.*?)"[)]',
                                re.S)
            csv_key = re.findall(csv_re, java_code)[0]
            file_path = arguments_local[csv_key]
            filename = file_path.split("/")[-1]
            logger.info(thread_group_name + "的 csv 文件名称" + filename)
            messages = deal_csv_file(filename)
            logger.info("读取csv文件内容结束")
            logger.info(messages)
        elif sub_element.tag == "Arguments":
            # copp 自定义变量里直接放的文件名, 直接获取报文内容, 无需将变量上送到blade
            csv_file_path = sub_element.element.find(
                ".//stringProp[@name='Argument.value']").text
            csv_file_name = csv_file_path.split("/")[-1]
            logger.info(thread_group_name + "的 csv 文件名称" + csv_file_name)
            messages = deal_csv_file(csv_file_name)
            logger.info("读取csv文件内容结束")
            logger.info(messages)
        elif sub_element.tag == "HTTPSamplerProxy":
            # 在这里改成将 HTTP 组件保存下来, 在后面循环遍历 Message, 重复发送
            http_companents.append(sub_element)
        elif sub_element.tag == "JDBCSampler":
            # JDBC 组件处理
            step = deal_JDBCSample(sub_element)
            ioc.add_case(sub_element.get("testname"), [step])

    # 改到这里发HTTP请求
    if messages:
        # 不为空
        for message in messages:
            step_num = 0
            steps = []
            for http_companent in http_companents:
                step_num += 1
                path = http_companent.element.find(
                    ".//stringProp[@name='HTTPSampler.path']").text
                logger.info(path)
                # 先添加脚本
                ds = dealScriptData(node_path)
                ds.set_data_with_default(http_companent.get("testname"),
                                         root_url, path, thread_group_name)
                resp, script_id = post_blade.dealScriptData(ds)
                # 再添加数据
                request_body_half = http_companent.element.find(
                    ".//stringProp[@name='Argument.value']").text
                requst_body = request_body_half.replace(
                    "${req_body}", message["body"])
                logger.debug(requst_body)
                steps.append(
                    deal_HTTPSampler(http_companent, "步骤-" + str(step_num),
                                     script_id, requst_body,
                                     message["check_message"]))
            ioc.add_case(message["casename"], steps)
    elif http_companents:
        step_num = 0
        steps = []
        for http_companent in http_companents:
            step_num += 1
            path = http_companent.element.find(
                ".//stringProp[@name='HTTPSampler.path']").text
            logger.info(path)
            # 先添加脚本
            ds = dealScriptData(node_path)
            ds.set_data_with_default(http_companent.get("testname"), root_url,
                                     path, thread_group_name)
            resp, script_id = post_blade.dealScriptData(ds)
            # 再添加数据
            steps.append(
                deal_HTTPSampler(http_companent, "步骤-" + str(step_num),
                                 script_id))
        ioc.add_case(thread_group_name, steps)
    else:
        pass

    resp = post_blade.importOfflineCase(ioc)
    # logger.info(resp)
    if resp is not None:
        logger.error(thread_group_name + resp)