利用jmeter提供的API开发(二)

SummaryReport.java

import org.apache.jmeter.gui.util.FileDialoger;
import org.apache.jmeter.gui.util.HeaderAsPropertyRendererWrapper;
import org.apache.jmeter.samplers.Clearable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.save.CSVSaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.Calculator;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.visualizers.StatGraphVisualizer;
import org.apache.jmeter.visualizers.gui.AbstractVisualizer;
import org.apache.jorphan.gui.*;
import org.apache.jorphan.reflect.Functor;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.Arrays;
import java.util.Deque;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;


public class SummaryReport extends AbstractVisualizer implements Clearable, ActionListener {

    private static final long serialVersionUID = 241L;

    private static final String USE_GROUP_NAME = "useGroupName"; //$NON-NLS-1$

    private static final String SAVE_HEADERS   = "saveHeaders"; //$NON-NLS-1$

    private static final String[] COLUMNS = {
            "sampler_label",               //$NON-NLS-1$
            "aggregate_report_count",      //$NON-NLS-1$
            "average",                     //$NON-NLS-1$
            "aggregate_report_min",        //$NON-NLS-1$
            "aggregate_report_max",        //$NON-NLS-1$
            "aggregate_report_stddev",     //$NON-NLS-1$
            "aggregate_report_error%",     //$NON-NLS-1$
            "aggregate_report_rate",       //$NON-NLS-1$
            "aggregate_report_bandwidth",  //$NON-NLS-1$
            "aggregate_report_sent_bytes_per_sec",  //$NON-NLS-1$
            "average_bytes",               //$NON-NLS-1$
    };

    private final String TOTAL_ROW_LABEL
            = JMeterUtils.getResString("aggregate_report_total_label");  //$NON-NLS-1$

    private static final int REFRESH_PERIOD = JMeterUtils.getPropDefault("jmeter.gui.refresh_period", 500); // $NON-NLS-1$

    private JTable myJTable;

    private JScrollPane myScrollPane;

    private final JButton saveTable =
            new JButton(JMeterUtils.getResString("aggregate_graph_save_table"));            //$NON-NLS-1$

    private final JCheckBox saveHeaders = // should header be saved with the data?
            new JCheckBox(JMeterUtils.getResString("aggregate_graph_save_table_header"),true);    //$NON-NLS-1$

    private final JCheckBox useGroupName =
            new JCheckBox(JMeterUtils.getResString("aggregate_graph_use_group_name"));            //$NON-NLS-1$

    private transient ObjectTableModel model;

    /**
     * Lock used to protect tableRows update + model update
     */
    private final transient Object lock = new Object();

    private volatile boolean dataChanged;

    private final Map<String, Calculator> tableRows = new ConcurrentHashMap<>();

    private final Deque<Calculator> newRows = new ConcurrentLinkedDeque<>();

    // Column renderers
    private static final TableCellRenderer[] RENDERERS =
            new TableCellRenderer[]{
                    null, // Label
                    null, // count
                    null, // Mean
                    new MinMaxLongRenderer("#0"), // Min //$NON-NLS-1$
                    new MinMaxLongRenderer("#0"), // Max //$NON-NLS-1$
                    new NumberRenderer("#0.00"), // Std Dev. //$NON-NLS-1$
                    new NumberRenderer("#0.00%"), // Error %age //$NON-NLS-1$
                    new RateRenderer("#.0"),      // Throughput //$NON-NLS-1$
                    new NumberRenderer("#0.00"),  // kB/sec //$NON-NLS-1$
                    new NumberRenderer("#0.00"),  // sent kB/sec //$NON-NLS-1$
                    new NumberRenderer("#.0"),    // avg. pageSize //$NON-NLS-1$
            };

    // Column formats
    private static final Format[] FORMATS =
            new Format[]{
                    null, // Label
                    null, // count
                    null, // Mean
                    new DecimalFormat("#0"), // Min //$NON-NLS-1$
                    new DecimalFormat("#0"), // Max //$NON-NLS-1$
                    new DecimalFormat("#0.00"), // Std Dev. //$NON-NLS-1$
                    new DecimalFormat("#0.000%"), // Error %age //$NON-NLS-1$
                    new DecimalFormat("#.00000"),      // Throughput //$NON-NLS-1$
                    new DecimalFormat("#0.00"),  // kB/sec //$NON-NLS-1$
                    new DecimalFormat("#0.00"),  // sent kB/sec //$NON-NLS-1$
                    new DecimalFormat("#.0"),    // avg. pageSize //$NON-NLS-1$
            };

    public SummaryReport() {
        super();
        model = new ObjectTableModel(COLUMNS, Calculator.class,// All rows have this class
                new Functor[] {
                        new Functor("getLabel"),              //$NON-NLS-1$
                        new Functor("getCount"),              //$NON-NLS-1$
                        new Functor("getMeanAsNumber"),       //$NON-NLS-1$
                        new Functor("getMin"),                //$NON-NLS-1$
                        new Functor("getMax"),                //$NON-NLS-1$
                        new Functor("getStandardDeviation"),  //$NON-NLS-1$
                        new Functor("getErrorPercentage"),    //$NON-NLS-1$
                        new Functor("getRate"),               //$NON-NLS-1$
                        new Functor("getKBPerSecond"),        //$NON-NLS-1$
                        new Functor("getSentKBPerSecond"),        //$NON-NLS-1$
                        new Functor("getAvgPageBytes"),       //$NON-NLS-1$
                },
                new Functor[] { null, null, null, null, null, null, null, null , null, null, null },
                new Class[] { String.class, Integer.class, Long.class, Long.class, Long.class, Double.class, Double.class, Double.class, Double.class, Double.class, Double.class });
        clearData();init();
        new Timer(REFRESH_PERIOD, e -> {
            if (!dataChanged) { return; }
            dataChanged = false;
            synchronized (lock) {
                while (!newRows.isEmpty()) {
                    model.insertRow(newRows.pop(), model.getRowCount() - 1); }
                model.fireTableDataChanged(); }
            int rowCount=model.getRowCount();
            int columnCount=model.getColumnCount();
            System.out.println("===============================聚合性能指标==========================================");
            for(int i=0;i<rowCount;i++){
                for(int j=0;j<columnCount;j++){
                    System.out.print(model.getValueAt(i,j)+"\t");
                }
                if(model.getValueAt(i,0).equals("总体")){
                    System.out.println("\n===============================聚合性能指标==========================================");
                }else{
                    System.out.println();
                }
            }
        }).start();
    }

    /**
     * @return <code>true</code> if all functors can be found
     * @deprecated - only for use in testing
     * */
    @Deprecated
    public static boolean testFunctors(){
        SummaryReport instance = new SummaryReport();
        return instance.model.checkFunctors(null,instance.getClass());
    }

    @Override
    public String getLabelResource() {
        return "summary_report";  //$NON-NLS-1$
    }

    @Override
    public void add(final SampleResult res) {
        Calculator row = tableRows.computeIfAbsent(res.getSampleLabel(useGroupName.isSelected()), label -> {
            Calculator newRow = new Calculator(label);
            newRows.add(newRow);
            return newRow;
        });
        /*
         * Synch is needed because multiple threads can update the counts.
         */
        synchronized (row) {
            row.addSample(res);
        }
        Calculator tot = tableRows.get(TOTAL_ROW_LABEL);
        synchronized (lock) {
            tot.addSample(res);
        }
        dataChanged = true;
    }

    /**
     * Clears this visualizer and its model, and forces a repaint of the table.
     */
    @Override
    public void clearData() {
        //Synch is needed because a clear can occur while add occurs
        synchronized (lock) {
            model.clearData();
            newRows.clear();
            tableRows.clear();
            tableRows.put(TOTAL_ROW_LABEL, new Calculator(TOTAL_ROW_LABEL));
            model.addRow(tableRows.get(TOTAL_ROW_LABEL));
        }
        dataChanged = true;
    }

    /**
     * Main visualizer setup.
     */
    private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
        this.setLayout(new BorderLayout());

        // MAIN PANEL
        JPanel mainPanel = new JPanel();
        Border margin = new EmptyBorder(10, 10, 5, 10);

        mainPanel.setBorder(margin);
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        mainPanel.add(makeTitlePanel());

        myJTable = new JTable(model);
        myJTable.setRowSorter(new ObjectTableSorter(model).fixLastRow());
        JMeterUtils.applyHiDPI(myJTable);
        HeaderAsPropertyRendererWrapper.setupDefaultRenderer(myJTable);
        myJTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
        RendererUtils.applyRenderers(myJTable, RENDERERS);
        myScrollPane = new JScrollPane(myJTable);
        this.add(mainPanel, BorderLayout.NORTH);
        this.add(myScrollPane, BorderLayout.CENTER);
        saveTable.addActionListener(this);
        JPanel opts = new JPanel();
        opts.add(useGroupName, BorderLayout.WEST);
        opts.add(saveTable, BorderLayout.CENTER);
        opts.add(saveHeaders, BorderLayout.EAST);
        this.add(opts,BorderLayout.SOUTH);
    }

    @Override
    public void modifyTestElement(TestElement c) {
        super.modifyTestElement(c);
        c.setProperty(USE_GROUP_NAME, useGroupName.isSelected(), false);
        c.setProperty(SAVE_HEADERS, saveHeaders.isSelected(), true);
    }

    @Override
    public void configure(TestElement el) {
        super.configure(el);
        useGroupName.setSelected(el.getPropertyAsBoolean(USE_GROUP_NAME, false));
        saveHeaders.setSelected(el.getPropertyAsBoolean(SAVE_HEADERS, true));
    }

    @Override
    public void actionPerformed(ActionEvent ev) {
        if (ev.getSource() == saveTable) {
            JFileChooser chooser = FileDialoger.promptToSaveFile("summary.csv");//$NON-NLS-1$
            if (chooser == null) {
                return;
            }
            try (FileOutputStream fo = new FileOutputStream(chooser.getSelectedFile());
                 OutputStreamWriter writer = new OutputStreamWriter(fo, Charset.forName("UTF-8"))) {
                CSVSaveService.saveCSVStats(StatGraphVisualizer.getAllTableData(model, FORMATS),writer,
//                        saveHeaders.isSelected() ? StatGraphVisualizer.getLabels(COLUMNS) : null);
                        saveHeaders.isSelected() ? StatGraphVisualizer.getColumns() : null);
            } catch (IOException e) {
                JMeterUtils.reportErrorToUser(e.getMessage(), "Error saving data");
            }
        }

    }
}

 

SummariserDemo.java
import org.apache.jmeter.JMeter;

import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.util.JMeterUtils;


import java.io.File;
import java.io.IOException;

public class SummariserDemo {
    static {
        System.setProperty(JMeter.JMETER_NON_GUI, "true");
        JMeterUtils.loadJMeterProperties("D:\\apache-jmeter-5.1\\bin\\jmeter.properties");
        JMeterUtils.loadJMeterProperties("D:\\apache-jmeter-5.1\\bin\\system.properties");
        JMeterUtils.loadJMeterProperties("D:\\apache-jmeter-5.1\\bin\\user.properties");
        JMeterUtils.loadJMeterProperties("D:\\apache-jmeter-5.1\\bin\\saveservice.properties");
        JMeterUtils.setJMeterHome("D:\\apache-jmeter-5.1");
        JMeterUtils.initLocale();
        JMeterUtils.initLogging();
        try {
            SaveService.loadProperties();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        File file = new File("D:\\idea.jtl");
        ResultCollector resultCollector = new ResultCollector();
        resultCollector.setFilename(file.getAbsolutePath());
        SummaryReport summaryReport = new SummaryReport();
        resultCollector.setVisual(summaryReport);
        resultCollector.loadExistingFile();
    }
}

 

JmeterTest.java
import org.apache.jmeter.assertions.ResponseAssertion;
import org.apache.jmeter.assertions.gui.AssertionGui;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.gui.TestPlanGui;
import org.apache.jmeter.engine.JMeterEngineException;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui;
import org.apache.jmeter.protocol.http.gui.HeaderPanel;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.gui.ThreadGroupGui;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.visualizers.StatVisualizer;
import org.apache.jorphan.collections.HashTree;

import java.io.FileOutputStream;
import java.io.IOException;
//import java.lang.ThreadGroup;

public class JmeterTest {

    public static void main(String args[]) throws IOException, JMeterEngineException {

        StandardJMeterEngine standardJMeterEngine = new StandardJMeterEngine();
// StandardJMeterEngine standardJMeterEngine=new StandardJMeterEngine("127.0.0.1"); //使用远程的jmeter server来进行性能测试,也就是分布式方式,IP地址可以带端口或不带端口
        JMeterUtils.loadJMeterProperties("D:\\apache-jmeter-5.1\\bin\\jmeter.properties");//本机jmeter路径
        JMeterUtils.loadJMeterProperties("D:\\apache-jmeter-5.1\\bin\\system.properties");//本机jmeter路径
        JMeterUtils.loadJMeterProperties("D:\\apache-jmeter-5.1\\bin\\user.properties");//本机jmeter路径
        JMeterUtils.setJMeterHome("D:\\apache-jmeter-5.1");
        JMeterUtils.initLocale();//时区
        JMeterUtils.initLogging();//日志
        SaveService.loadProperties();
        TestPlan testPlan = new TestPlan();
        testPlan.setName("测试计划");
        testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.

                getName());
        testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.

                getName());
/***********************如下几行testPlan的可以省略*************************************/
        testPlan.setComment("");
        testPlan.setFunctionalMode(false);
        testPlan.setTearDownOnShutdown(true);
        testPlan.setSerialized(false);
        testPlan.setTestPlanClasspathArray(new String[]

                {
                });
        testPlan.addParameter(null, null);//测试计划中的用户定义参数
        LoopController loopController = new LoopController();
        loopController.setContinueForever(true);
        loopController.setLoops(-1);
        loopController.initialize();
        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setName("ThreadGroup");
        threadGroup.setNumThreads(100);
        threadGroup.setRampUp(10);
        threadGroup.setScheduler(true);
        threadGroup.setDuration(120);
        threadGroup.setSamplerController(loopController);
        threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
        threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.

                getName());
        HTTPSamplerProxy httpSamplerProxy = new HTTPSamplerProxy();
        httpSamplerProxy.setName("baidu");
        httpSamplerProxy.setDomain("www.baidu.com");
        httpSamplerProxy.setPath("/");
        httpSamplerProxy.setProtocol("https");
        httpSamplerProxy.setMethod("GET");
        httpSamplerProxy.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
        httpSamplerProxy.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.

                getName());
        HeaderManager headerManager = new HeaderManager();
        headerManager.setName("消息头管理器");
        headerManager.add(new

                Header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36"));
        headerManager.setProperty(TestElement.TEST_CLASS, HeaderManager.class.

                getName());
        headerManager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.

                getName());
        ResponseAssertion responseAssertion = new ResponseAssertion();
        responseAssertion.setName("响应断言");
        responseAssertion.addTestString("百度一下");
        responseAssertion.setTestFieldResponseData();
        responseAssertion.setToContainsType();
        responseAssertion.setProperty(TestElement.TEST_CLASS, ResponseAssertion.class.

                getName());
        responseAssertion.setProperty(TestElement.GUI_CLASS, AssertionGui.class.

                getName());
        Summariser summer = new Summariser(JMeterUtils.getPropDefault("summariser.name", "summary"));
        ResultCollector logger = new ResultCollector(summer);
        logger.setFilename("d:/test.jtl");
        logger.setName("聚合报告");
        HashTree jmeterTest = new HashTree();
        HashTree testPlanTree = jmeterTest.add(testPlan);
        logger.setProperty(TestElement.TEST_CLASS, ResultCollector.class.

                getName());
        logger.setProperty(TestElement.GUI_CLASS, StatVisualizer.class.

                getName());
        HashTree httpSamplerTree = jmeterTest.add(threadGroup, httpSamplerProxy);
        httpSamplerTree.add(responseAssertion);
        httpSamplerTree.add(headerManager);
        jmeterTest.add(jmeterTest.getArray()[0], logger);
        SaveService.saveTree(jmeterTest, new

                FileOutputStream("d:/test.jmx"));
        standardJMeterEngine.configure(jmeterTest);
        standardJMeterEngine.runTest();

    }
}

 

posted @ 2020-06-09 16:28  等那片花海  阅读(883)  评论(0编辑  收藏  举报