jmeter(四十一)命令行传参

2022-04-09  本文已影响0人  Sandra_liu

1、直接通过命令行传参
格式:${__P(key,default)}


image.png
promote:~ sandra$ jmeter -Jurl=www.baidu.com  -Jport=80 -n -t 
Creating summariser <summary>
Created the tree successfully using /Users/sandra/PycharmProjects/http-runner_xbe/jmeter/jmx/loadtest/template/baidu.jmx
Starting standalone test @ Mon Mar 21 17:15:34 CST 2022 (1647854134633)
Waiting for possible Shutdown/StopTestNow/HeapDump/ThreadDump message on port 4445
summary +      1 in 00:00:00 =    3.1/s Avg:   154 Min:   154 Max:   154 Err:     0 (0.00%) Active: 1 Started: 1 Finished: 0
summary =      1 in 00:00:00 =    3.1/s Avg:   154 Min:   154 Max:   154 Err:     0 (0.00%)
Tidying up ...    @ Mon Mar 21 17:15:35 CST 2022 (1647854135487)
... end of run

2、脚本-间接通过命令行传参

# -*- coding: utf-8 -*-


import os, sys
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def setupJmx(jmx_prefix, host, threads_num, rampup_time, loop_count, remark,  setHost=False):
    current_dir = os.getcwd()
    logger.info(current_dir)
    template_jmx = os.path.join(current_dir, '', jmx_prefix + '.jmx')
    logger.info(template_jmx)
    if not os.path.exists(template_jmx):
        logger.error(template_jmx + ' path not Exist')
        return None

    new_jmx_dir = "{}_tn{}_rt{}_l{}_r{}".format(jmx_prefix, threads_num, rampup_time, loop_count, remark)
    new_jmx_path = new_jmx_dir + '.jmx'
    logger.info("jmx name: " + new_jmx_path)

    result_dir = os.path.join(current_dir, new_jmx_dir, 'result')
    if not os.path.exists(result_dir):
        os.makedirs(result_dir)

    with open(template_jmx) as temp_stream:
        lines = temp_stream.readlines()
        with open(os.path.join(current_dir, new_jmx_path), 'w') as new_stream:
            for line in lines:
                new_line = line.replace('$threads_num$', threads_num).\
                    replace('${__P(url,)}', host).replace(
                    '${__P(num,)}', threads_num).replace('${__P(rampup,)}', rampup_time).replace('${__P(loopcount,)}',
                                                                                                loop_count)
                # if setHost:
                #     new_line = new_line.replace('${__P(url,)}', host)
                new_stream.write(new_line)

    return new_jmx_dir


def runJmeterByCmd(new_jmx_dir, hostname='', ip=''):
    def isJmeterInstalled():
        result = True
        lines = os.popen('which jmeter')
        for l in lines:
            if 'not found' in l:
                logger.error('Jmeter Not Installed')
                result = False
                break
        return result

    execute_cmd = 'jmeter -n -t {0}.jmx -l {0}.jtl -j {0}.log -f -e -o {0}/result/'.format(new_jmx_dir)
    logger.info(execute_cmd)
    if isJmeterInstalled():
        os.system(execute_cmd)


if __name__ == '__main__':
    """在命令行传参"""
    '''python run.py baidu 49.235.32.XX  5 1 1 marker|grep 'param list'''

    if len(sys.argv[1:]) == 6:
        logger.info('param list: %s', str(sys.argv[1:]))
        param = sys.argv[1:]
        new_jmx_dir = setupJmx(param[0], param[1], param[2], param[3], param[4], param[5], True)
        if new_jmx_dir is not None:
            logging.info("new_jmx_dir is : %s", new_jmx_dir)
            runJmeterByCmd(new_jmx_dir=new_jmx_dir)
    else:
        logger.info('param list: %s', len(sys.argv[1:]))



if __name__ == '__main__':
    # '''不在命令行传参'''
    # '''python run.py'''
    params = [
        ["baidu", '49.235.32.XX', '5', '1', '-1', "marker", True],
        ["baidu", '49.235.32.XX', '15', '1', '1', "marker", True],
        ["baidu", '49.235.32.XX', '25', '1', '1', "marker", True],
        ["baidu", '49.235.32.XX', '35', '1', '1', "marker", True]
    ]
    for param in params:
        logger.info(param)
        new_jmx_dir = setupJmx(jmx_prefix=param[0],
                               host=param[1],
                               threads_num=param[2],
                               rampup_time=param[3],
                               loop_count=param[4],
                               remark=param[5],
                               setHost=param[6])
        if new_jmx_dir is not None:
            logging.info("new_jmx_dir is : %s", new_jmx_dir)
            runJmeterByCmd(new_jmx_dir=new_jmx_dir)

上一篇下一篇

猜你喜欢

热点阅读