头图

Introduction to JMeter

JMeter :

  • Functional test and performance test for multiple protocols

    • Web - HTTP, HTTPS (Java, NodeJS, PHP, ASP.NET, …)
    • SOAP / REST Webservices
    • FTP
    • Database via JDBC
    • LDAP
    • Message-oriented middleware (MOM) via JMS
    • Mail - SMTP(S), POP3(S) and IMAP(S)
    • Native commands or shell scripts
    • TCP
    • Java Objects
  • Test recording provided
  • Provide CLI mode
  • Provide HTML report
  • Complete portability and 100% purity Java
  • Provide multi-thread support, simulate multi-user
  • High scalability> This section translated JMeter Home: https://jmeter.apache.org/index.html

    The author's experimental environment

JMeter is an implementation of the Java language, that is, a pure Java application, so JMeter can theoretically run on any environment available in the corresponding Java environment. |Type|Value| |:—-|:—-| |Java version|java version "1.8.0_181" (Java8 and above required)| |JMeter version|5.4.1| |Operating system|Ubuntu 20.04 (GNOME 3.36. 5)| |Kernel version|Linux version 5.8.0-43-generic|

download

This article mainly introduces JMeter , so other environments are prepared by the readers themselves

  1. Enter the official website page ( https://jmeter.apache.org/download_jmeter.cgi ), select the appropriate mirror source, and download the binary distribution file;
  2. After the archive into local, JMeter directory path extract obtained after referred JMETER_HOME ;

A brief introduction to JMeter files

File path (relative to the JMETER_HOME directory)File Description
binFolder in which executable files are stored
docsHelp document directory
extrasExtension plug-in directory, the files in the directory provide support for ant
libJar package used by JMeter
bin/jmeterLaunch the executable file of the JMeter client in linux and unix systems (itself is a shell script)
bin/jmeter-serverThe executable file to start the JMeter service process in linux and unix systems (itself is a shell script)
bin/jmeter.propertiesJMeter configuration file
bin/jmeter.batStart the executable file of the JMeter client under Windows
bin/jmeter-server.batExecutable file to start JMeter service process under Windows

Start the user interface of JMeter

Enter JMETER_HOME directory bin directory, execute the following command to start JMeter of GUI mode:

./jmeter


After a few seconds, the interface opens as follows:

Introduction to the main concepts of JMeter

conceptIntroduction
Test PlanThe test plan describes a series of steps that JMeter needs to perform
Thread groupThe thread group defines the user pool for execution (simulating multiple users in a concurrent manner)
jmx fileA file ending with (.jmx) corresponding to a test plan. The file is a JMeter program-specific data structure organized in xml format
SampleThe sampler can sample the execution target (HTTP, JDBC, etc.)
Pre-processorPre-process the sampler (provide user parameters, wait for a specified time, etc.)
Post-processorPost-processing the sampler (result extractor, etc.)
AssertionsAssert the results obtained by the sampler (response time assertion, response data assertion, response structure assertion, etc.)
Logic controllerControl the execution steps of the test plan in a logical form (If, While, etc.)
ListenerAfter the sampler is executed, the listener will be notified. Generally, the listener is used to process the result data (display result data, aggregate charts, etc.)
Config elementAble to perform some configuration for the test plan (request header configuration, general request configuration, authentication configuration, variable configuration, etc.)

Introduction to the main functional elements of JMeter (Http test related)

JMeter interface operations are to click the right mouse button and a drop-down menu will pop up to add elements

Thread group

Right-click test plan to add

Component screenshot:

Component parameter description:

parameter nameValue and meaning
Action after errorContinue (continue to execute the next steps), start the next cycle, stop the thread (only this thread), stop the test (stop the test after the execution of the sampler being executed), stop the test immediately
ThreadsNumber of users to be simulated
Ramp-Up time (seconds)Warm-up time. Used to start all configured threads within the execution time. For example, 10s, the number of threads is 10, then a thread is started every 1s (the first thread is always started immediately, if the total number of threads is 1, then no matter how much the warm-up time is, it is equivalent to 0)
CyclesForever (the loop does not stop), the specified number (after the specified number of loops, the execution will stop)
Is it the same user every time?whether

HTTP request default value

Right-click the thread group element and add it from the config element drop-down

This component is used to provide default values HTTP

Component parameter description:

parameter nameValue and meaning
protocolIs it the http protocol or the https protocol
Server name or IPDomain name or IP address
The port numberThe port number of the server
pathThe path part of the URL
Content encodingThe character set encoding used by the HTTP request
parameterHTTP request parameters
Message body dataDefault request body data

User-defined variables

Right-click the thread group element and select Add from the configuration element

This component is used to define variables in the thread and can be referenced in other places using the syntax of ${variableName}

Add button in the following interface to add a line of variable name and value to define a variable.

HTTP sampler

Right-click the thread group element and select from the sampler entry

The HTTP sampler can sample the system under test in the form of HTTP Many data in this component are the HTTP request default value component mentioned above. If this sampler is within the HTTP request default value component, the empty attributes in the sampler will be filled with the default Value, a non-empty attribute will override the same attribute in the default value

Component parameter description:

parameter nameValue and meaning
protocolIs it the http protocol or the https protocol
Server name or IPDomain name or IP address
The port numberThe port number of the server
pathThe path part of the URL
Content encodingThe character set encoding used by the HTTP request
parameterHTTP request parameters (query parameters in the URL)
Message body dataRequest body data
Request methodHTTP methods such as GET, POST, PUT, DELETE, etc.
File UploadUsed to upload files
Automatic redirectionChecking means automatic redirection. Indicates that the downstream HTTP protocol processor will automatically redirect, so the process of redirection is invisible to JMeter. And can only be used for GET and HEAD methods. POST and PUT methods will be rejected.
Follow redirectChecked means follow redirection (only valid when automatic redirection is not checked). If set, JMeter's sampler will process the response, and will track each redirection in the process, and use the last non-redirected request and response as the outermost sampled data, and other requested data as this Additional information about the sampled data. (The maximum number of redirects is 20)
Use KeepAliveAfter checking, JMeter will set the request header Connection: keep-alive. But whether this option takes effect is still related to JMeter's HTTP implementation.

Response assertion

Right-click the sampler, click [Add-Assertion-Response Assertion] option to add

Response assertion can be used to assert the results obtained by the sampler, and use logic (equal, contain, regular matching, etc.) to assert content including response headers, response codes, response bodies, etc., to verify whether the output of the sampler conforms to The tester’s expectations.

Component parameter description:

parameter nameValue and meaning
NameThe name of the assertion
Apply toThe scope of the selected assertion is generally the Main sample only option. Main sample refers to the sampler to which this assertion belongs, and sub samples refers to the sub-sampler generated by this sampler, such as the advanced HTTP sampler Option-Get the built-in resources, and the sub-sampler will be generated.
Field to TestRefers to the target that needs to be asserted. Text Response refers to the entire response obtained from the server as text (response body). Response Code is the response code (for example, 200). Response Message is the response message (for example, OK). Response Headers are response headers. Request Headers refers to request headers. Request Data refers to all requested data as text (request body). URL sampled is the sampled URL. Document refers to the document extracted with specific rules like the Document part of the View Results Tree component.
Ignore statusIgnore the response status code. Generally 4xx and 5xx are regarded as failures by default. If not set, the result of the total sample is a combination of the success or failure of the status code and the result of the assertion. If it is set, the status will be set to success, and then the assertion (note: if this parameter is set, this assertion must be placed first, otherwise the failure result of the previous assertion will be cleared)
Pattern Matching RulesFor a given pattern string, what rules are used. Contains contains pattern strings (pattern strings are treated as regular expressions). Matches represents a regular match (the pattern string is regarded as a regular expression). Equals means equality (case sensitive, the pattern string is treated as plain text). Substring means that the text under test contains the given pattern string (the pattern string is regarded as plain text). Two logical symbols: Not and Or. Not means to negate the result. Or indicates that the matching rule holds for a given series of pattern strings, and the assertion is OK.
Patterns to TestA list of pattern strings to be tested. You can click the Add button to add multiple pattern strings. If it is a regular expression, it is a Perl5-style regular expression and does not have the form of closed parentheses.

JSON variable extraction

Right click on the request, Add – Post Processors – Json Extractor to add a JSON extractor element

JSON extractor can be used to extract the attribute of the specified position as a variable JSON

Component parameter description:

parameter nameValue and meaning
NameDescriptive name for display
Names of created variablesOne or more names of the created variables (multiple separated by commas), the quantity should correspond to the JSON Path expression
JSON Path ExpressionsOne or more JSON path expressions (multiple separated by commas), the number and the number of variables must match. (Refer to the following for the writing of the expression)
Default ValuesOne and multiple default values (multiple are separated by commas). If a JSON path expression does not return a value, the default value of the corresponding position is used. The number is the same as the number of variables
Match No. (0 for Random)If the JSON path expression can take multiple values, which one should be used. 0 means random; -1 means to extract all the results (multiple variables will be generated, named _N, N starts from 1); X means to extract the result of the specified position, starting from 1, if X is greater than the number of results, then return Empty (will try to use the default value)
Compute concatenation varIf checked, it means that if multiple results are obtained, they will be separated by commas and put into a variable named _ALL

JSON path writing: $ symbol represents the root element, . represents the attribute, [0] represents the first element of the array object ( [1] is the second).

E.g:

{
    "user": {
        "names": ["Jack", "Jacky"],
        "age": 10
    }
}


For the above JSON , use the expression $.user.names[0] to extract the value Jack For more detailed information, please refer to: https://jsonpath.com/

View result tree elements

This element is used JMeter interface to execute the request. It can view the requested request message, response message, and assertion information. See below for details.

JMeter usage example

Next, we use the knowledge learned above to implement such a scenario: query Gitee warehouse on 0617f898350613, and then extract the name of a designated contributor, and use the second request to obtain the contributor's information.

The two interfaces of Gitee

  • GET https://gitee.com/open-hand/choerodon/contributors_count?ref=0.23.0

JSON path of the contributor name we need to obtain $.contributors[0].username ):

{
    "status": 1,
    "contributors_count": "16",
    "contributors": [
        {
            "username": "example1"
        }
    ]
}


  • GET https://gitee.com/{contributor name}

Create test plan

there will be a default test plan 1617f8983507cf

Create thread group

Right-click the test plan and click Add > Threads (Users) > Thread Group add the thread group element. Fill in the following values:

Create HTTP default value configuration element

Right-click the thread group, Add > Config Element > Http Request Defaults add configuration elements. Fill in the value as follows:

Create HTTP sampler to get the list of contributors

Right-click the thread group, Add > Sampler > HTTP Request add sampler (fill in path and add a parameter):

Add response extractor

Right-click to request the sampler, and Add > Post Processors > JSON extractor as follows, because some users gitee , here we will extract JSON path as the $.contributors[4].username (that is, the fifth contributor) into the variable contributorName :

Add the view result tree element to the request

Right-click the sampler, Add > Listener > View Results Tree add to view the result tree as follows:

Add HTTP sampler to request specific contributor information

Right-click the thread group, Add > Sampler > HTTP Request added sampler (here path fill property ${contributorName} used to refer to variables on a request extracted):

Add the view result tree element to the request

Right-click the sampler, Add > Listener > View Results Tree add to view the result tree as follows:

Click the green triangle to execute

After clicking the execute button, we will be prompted to save the file before executing it. After selecting a suitable directory to save, click the execute button. At this time, the green execute button will turn gray, and the upper right corner will start timing, which indicates that the request is in progress. Execute, when the button turns green again, the execution is over.

View execution results

view result tree element of the first request to view the execution result of this request:

You can see that the information in the response body is:

Looking at the request data of the second request, you can see that the request is successful, and you can see that the ${contributorName} request path has been rendered as the value handchoerodon extracted by the first request:

Summarize

JMeter provides the HTTP sampler, various assertion mechanisms, configuration mechanisms and variable extraction mechanisms, which can help our modular interface test and make the system more robust.

Extended information

  1. JMeter Get Started
  2. JMeter component description

This article was originally created by the Toothfish technical team, please indicate the source for reprinting: official website

about pig tooth fish

The Choerodon full-scenario performance platform provides systematic methodology and collaboration, testing, DevOps and container tools to help companies pull through the requirements, design, development, deployment, testing and operation processes, and improve management efficiency and quality in one stop. From team collaboration to DevOps tool chain, from platform tools to systemic methodology, Pigtooth fully meets the needs of collaborative management and engineering efficiency, runs through the entire end-to-end process, and helps the team to be faster, stronger and more stable. here to try the pig tooth fish


ZKNOW甄知科技
1.5k 声望946 粉丝

上海甄知科技有限公司(简称甄知科技)是一家服务管理数字化领先企业,由业界知名的数字化服务综合提供商上海汉得信息技术股份有限公司(股票代码:300170)孵化而成,承袭汉得信息20年的企业信息化服务经验和对...