qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

jmeter sample 取样器

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
ServerDomain name or IP address of the web server.Yes
PortPort the web server is listening to.No (defaults to 80)
Log parser classThe log parser class is responsible for parsing the logs.Yes (default provided)
FilterThe filter class is used to filter out certain lines.No
Location of log fileThe location of the access log file.Yes

The TCLogParser processes the access log independently for each thread. The SharedTCLogParser and OrderPreservingLogParser share access to the file, i.e. each thread gets the next entry in the log.

The SessionFilter is intended to handle Cookies across threads. It does not filter out any entries, but modifies the cookie manager so that the cookies for a given IP are processed by a single thread at a time. If two threads try to process samples from the same client IP address, then one will be forced to wait until the other has completed.

The LogFilter is intended to allow access log entries to be filtered by filename and regex, as well as allowing for the replacement of file extensions. However, it is not currently possible to configure this via the GUI, so it cannot really be used.。

pasting

18.1.10 BeanShell Sampler

This sampler allows you to write a sampler using the BeanShell scripting language.

For full details on using BeanShell, please see the BeanShell website.

The test element supports the ThreadListener and TestListener interface methods. These must be defined in the initialisation file. See the file BeanShellListeners.bshrc for example definitions.

From JMeter version 2.5.1, the BeanShell sampler also supports the Interruptible interface. The interrupt() method can be defined in the script or the init file.

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree. The name is stored in the script variable LabelNo
Reset bsh.Interpreter before each callIf this option is selected, then the interpreter will be recreated for each sample. This may be necessary for some long running scripts. For further information, see Best Practices - BeanShell scripting .Yes
ParametersParameters to pass to the BeanShell script. This is intended for use with script files; for scripts defined in the GUI, you can use whatever variable and function references you need within the script itself. The parameters are stored in the following variables:
  • Parameters - string containing the parameters as a single variable
  • bsh.args - String array containing parameters, split on white-space
No
Script fileA file containing the BeanShell script to run. The file name is stored in the script variable FileNameNo
ScriptThe BeanShell script to run. The return value (if not null) is stored as the sampler result.Yes (unless script file is provided)

 

N.B. Each Sampler instance has its own BeanShell interpeter, and Samplers are only called from a single thread

If the property "beanshell.sampler.init" is defined, it is passed to the Interpreter as the name of a sourced file. This can be used to define common methods and variables. There is a sample init file in the bin directory: BeanShellSampler.bshrc.

If a script file is supplied, that will be used, otherwise the script will be used.

 

JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props methods, e.g. props.get("START.HMS"); props.put("PROP1","1234"); 
BeanShell does not currently support Java 5 syntax such as generics and the enhanced for loop.

 

Before invoking the script, some variables are set up in the BeanShell interpreter:

The contents of the Parameters field is put into the variable "Parameters". The string is also split into separate tokens using a single space as the separator, and the resulting list is stored in the String array bsh.args.

The full list of BeanShell variables that is set up is as follows:

  • log - the Logger
  • Label - the Sampler label
  • FileName - the file name, if any
  • Parameters - text from the Parameters field
  • bsh.args - the parameters, split as described above
  • SampleResult - pointer to the current SampleResult
  • ResponseCode = 200
  • ResponseMessage = "OK"
  • IsSuccess = true
  • ctx - JMeterContext
  • vars - JMeterVariables - e.g. vars.get("VAR1"); vars.put("VAR2","value"); vars.remove("VAR3"); vars.putObject("OBJ1",new Object());
  • props - JMeterProperties (class java.util.Properties)- e.g. props.get("START.HMS"); props.put("PROP1","1234");

When the script completes, control is returned to the Sampler, and it copies the contents of the following script variables into the corresponding variables in the SampleResult :

  • ResponseCode - for example 200
  • ResponseMessage - for example "OK"
  • IsSuccess - true/false

The SampleResult ResponseData is set from the return value of the script. Since version 2.1.2, if the script returns null, it can set the response directly, by using the method SampleResult.setResponseData(data), where data is either a String or a byte array. The data type defaults to "text", but can be set to binary by using the method SampleResult.setDataType(SampleResult.BINARY).

The SampleResult variable gives the script full access to all the fields and methods in the SampleResult. For example, the script has access to the methods setStopThread(boolean) and setStopTest(boolean). Here is a simple (not very useful!) example script:

if (bsh.args[0].equalsIgnoreCase("StopThread")) {
    log.info("Stop Thread detected!");
    SampleResult.setStopThread(true);
}
return "Data from sample with Label "+Label;
//or, since version 2.1.2
SampleResult.setResponseData("My data");
return null;

Another example: 
ensure that the property beanshell.sampler.init=BeanShellSampler.bshrc is defined in jmeter.properties. The following script will show the values of all the variables in the ResponseData field:

return getVariables();

For details on the methods available for the various classes ( JMeterVariables SampleResult etc) please check the Javadoc or the source code. Beware however that misuse of any methods can cause subtle faults that may be difficult to find ...



18.1.11 BSF Sampler

This sampler allows you to write a sampler using a BSF scripting language. 
See the Apache Bean Scripting Framework website for details of the languages supported. You may need to download the appropriate jars for the language; they should be put in the JMeter lib directory.

 

The BSF API has been largely superseded by JSR-223, which is included in Java 1.6 onwards. Most scripting languages now include support for JSR-223; please use the JSR223 Sampler instead. The BSF Sampler should only be needed for supporting legacy languages/test scripts.

 

By default, JMeter supports the following languages:

  • javascript
  • jexl (JMeter version 2.3.2 and later)
  • xslt

 

Unlike the BeanShell sampler, the interpreter is not saved between invocations.

 

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
Scripting LanguageName of the BSF scripting language to be used. N.B. Not all the languages in the drop-down list are supported by default. The following are supported: jexl, javascript, xslt. Others may be available if the appropriate jar is installed in the JMeter lib directory.Yes
Script FileName of a file to be used as a BSF script, if a relative file path is used, then it will be relative to directory referenced by "user.dir" System propertyNo
ParametersList of parameters to be passed to the script file or the script.No
ScriptScript to be passed to BSF languageYes (unless script file is provided)

 

If a script file is supplied, that will be used, otherwise the script will be used.

 

JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props methods, e.g. props.get("START.HMS"); props.put("PROP1","1234");

 

Before invoking the script, some variables are set up. Note that these are BSF variables - i.e. they can be used directly in the script.

  • log - the Logger
  • Label - the Sampler label
  • FileName - the file name, if any
  • Parameters - text from the Parameters field
  • args - the parameters, split as described above
  • SampleResult - pointer to the current SampleResult
  • sampler - pointer to current Sampler
  • ctx - JMeterContext
  • vars - JMeterVariables - e.g. vars.get("VAR1"); vars.put("VAR2","value"); vars.remove("VAR3"); vars.putObject("OBJ1",new Object());
  • props - JMeterProperties (class java.util.Properties) - e.g. props.get("START.HMS"); props.put("PROP1","1234");
  • OUT - System.out - e.g. OUT.println("message")

The SampleResult ResponseData is set from the return value of the script. If the script returns null, it can set the response directly, by using the method SampleResult.setResponseData(data), where data is either a String or a byte array. The data type defaults to "text", but can be set to binary by using the method SampleResult.setDataType(SampleResult.BINARY).

The SampleResult variable gives the script full access to all the fields and methods in the SampleResult. For example, the script has access to the methods setStopThread(boolean) and setStopTest(boolean).

Unlike the BeanShell Sampler, the BSF Sampler does not set the ResponseCode, ResponseMessage and sample status via script variables. Currently the only way to changes these is via the SampleResult methods:

  • SampleResult.setSuccessful(true/false)
  • SampleResult.setResponseCode("code")
  • SampleResult.setResponseMessage("message")

18.9.8 Debug Sampler

The Debug Sampler generates a sample containing the values of all JMeter variables and/or properties.

The values can be seen in the View Results Tree Listener Response Data pane.

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
JMeter PropertiesInclude JMeter properties ?Yes
JMeter VariablesInclude JMeter variables ?Yes
System PropertiesInclude System properties ?Yes

18.1.1 FTP Request

This controller lets you send an FTP "retrieve file" or "upload file" request to an FTP server. If you are going to send multiple requests to the same FTP server, consider using a FTP Request Defaults Configuration Element so you do not have to enter the same information for each FTP Request Generative Controller. When downloading a file, it can be stored on disk (Local File) or in the Response Data, or both.

Latency is set to the time it takes to login (versions of JMeter after 2.3.1).

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
Server Name or IPDomain name or IP address of the FTP server.Yes
PortPort to use. If this is >0, then this specific port is used, otherwise JMeter uses the default FTP port.No
Remote File:File to retrieve or name of destination file to upload.Yes
Local File:File to upload, or destination for downloads (defaults to remote file name).Yes, if uploading (*)
Local File Contents:Provides the contents for the upload, overrides the Local File property.Yes, if uploading (*)
get(RETR) / put(STOR)Whether to retrieve or upload a file.Yes
Use Binary mode ?Check this to use Binary mode (default Ascii)Yes
Save File in Response ?Whether to store contents of retrieved file in response data. If the mode is Ascii, then the contents will be visible in the Tree View Listener.Yes, if downloading
UsernameFTP account username.Usually
PasswordFTP account password. N.B. This will be visible in the test plan.Usually

 

See Also:

 

18.1.2 HTTP Request

This sampler lets you send an HTTP/HTTPS request to a web server. It also lets you control whether or not JMeter parses HTML files for images and other embedded resources and sends HTTP requests to retrieve them. The following types of embedded resource are retrieved:

  • images
  • applets
  • stylesheets
  • external scripts
  • frames, iframes
  • background images (body, table, TD, TR)
  • background sound

The default parser is htmlparser. This can be changed by using the property "htmlparser.classname" - see jmeter.properties for details.

If you are going to send multiple requests to the same web server, consider using an HTTP Request Defaults Configuration Element so you do not have to enter the same information for each HTTP Request.

Or, instead of manually adding HTTP Requests, you may want to use JMeter's HTTP(S) Test Script Recorder to create them. This can save you time if you have a lot of HTTP requests or requests with many parameters.

There are two different screens for defining the samplers:

  • AJP/1.3 Sampler - uses the Tomcat mod_jk protocol (allows testing of Tomcat in AJP mode without needing Apache httpd) The AJP Sampler does not support multiple file upload; only the first file will be used.
  • HTTP Request - this has an implementation drop-down box, which selects the HTTP protocol implementation to be used:
    • Java - uses the HTTP implementation provided by the JVM. This has some limitations in comparison with the HttpClient implementations - see below.
    • HTTPClient3.1 - uses Apache Commons HttpClient 3.1. This is no longer being developed, and support for this may be dropped in a future JMeter release.
    • HTTPClient4 - uses Apache HttpComponents HttpClient 4.x.
    • Blank Value - does not set implementationon HTTP Samplers, so relies on HTTP Request Defaults if present or on jmeter.httpsampler property defined in jmeter.properties

 

The Java HTTP implementation has some limitations:

  • There is no control over how connections are re-used. When a connection is released by JMeter, it may or may not be re-used by the same thread.
  • The API is best suited to single-threaded usage - various settings are defined via system properties, and therefore apply to all connections.
  • There is a bug in the handling of HTTPS via a Proxy (the CONNECT is not handled correctly). See Java bugs 6226610 and 6208335.
  • It does not support virtual hosts.

Note: the FILE protocol is intended for testing puposes only. It is handled by the same code regardless of which HTTP Sampler is used.

If the request requires server or proxy login authorization (i.e. where a browser would create a pop-up dialog box), you will also have to add an HTTP Authorization Manager Configuration Element. For normal logins (i.e. where the user enters login information in a form), you will need to work out what the form submit button does, and create an HTTP request with the appropriate method (usually POST) and the appropriate parameters from the form definition. If the page uses HTTP, you can use the JMeter Proxy to capture the login sequence.

In versions of JMeter up to 2.2, only a single SSL context was used for all threads and samplers. This did not generate the proper load for multiple users. A separate SSL context is now used for each thread. To revert to the original behaviour, set the JMeter property:

https.sessioncontext.shared=true  
By default, the SSL context is retained for the duration of the test. In versions of JMeter from 2.5.1, the SSL session can be optionally reset for each test iteration. To enable this, set the JMeter property:
https.use.cached.ssl.context=false  
Note: this does not apply to the Java HTTP implementation.

 

JMeter defaults to the SSL protocol level TLS. If the server needs a different level, e.g. SSLv3, change the JMeter property, for example:

https.default.protocol=SSLv3  

 

JMeter also allows one to enable additional protocols, by changing the property https.socket.protocols .

If the request uses cookies, then you will also need an HTTP Cookie Manager . You can add either of these elements to the Thread Group or the HTTP Request. If you have more than one HTTP Request that needs authorizations or cookies, then add the elements to the Thread Group. That way, all HTTP Request controllers will share the same Authorization Manager and Cookie Manager elements.

If the request uses a technique called "URL Rewriting" to maintain sessions, then see section 6.1 Handling User Sessions With URL Rewriting for additional configuration steps.

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
ServerDomain name or IP address of the web server. e.g. www.example.com. [Do not include the http:// prefix.] Note: in JMeter 2.5 (and later) if the "Host" header is defined in a Header Manager, then this will be used as the virtual host name.Yes, unless provided by HTTP Request Defaults
PortPort the web server is listening to. Default: 80No
Connect TimeoutConnection Timeout. Number of milliseconds to wait for a connection to open.No
Response TimeoutResponse Timeout. Number of milliseconds to wait for a response. Note that this appplies to each wait for a response. If the server response is sent in several chunks, the overall elapsed time may be longer than the timeout. A Duration Assertion can be used to detect overlong responses.No
Server (proxy)Hostname or IP address of a proxy server to perform request. [Do not include the http:// prefix.]No
PortPort the proxy server is listening to.No, unless proxy hostname is specified
Username(Optional) username for proxy server.No
Password(Optional) password for proxy server. (N.B. this is stored unencrypted in the test plan)No
ImplementationJava, HttpClient3.1, HttpClient4. If not specified (and not defined by HTTP Request Defaults), the default depends on the value of the JMeter property jmeter.httpsampler , failing that, the HttpClient4 implementation is used.No
ProtocolHTTP, HTTPS or FILE. Default: HTTPNo
MethodGET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE, PATCH (not supported for JAVA implementation)Yes
Content EncodingContent encoding to be used (for POST, PUT, PATCH and FILE). This the the character encoding to be used, and is not related to the Content-Encoding HTTP header.No
Redirect AutomaticallySets the underlying http protocol handler to automatically follow redirects, so they are not seen by JMeter, and thus will not appear as samples. Should only be used for GET and HEAD requests. The HttpClient sampler will reject attempts to use it for POST or PUT. Warning: see below for information on cookie and header handling.No
Follow RedirectsThis only has any effect if "Redirect Automatically" is not enabled. If set, the JMeter sampler will check if the response is a redirect and follow it if so. The initial redirect and further responses will appear as additional samples. The URL and data fields of the parent sample will be taken from the final (non-redirected) sample, but the parent byte count and elapsed time include all samples. The latency is taken from the initial response (versions of JMeter after 2.3.4 - previously it was zero). Note that the HttpClient sampler may log the following message: 
"Redirect requested but followRedirects is disabled" 
This can be ignored. 
In versions after 2.3.4, JMeter will collapse paths of the form '/../segment' in both absolute and relative redirect URLs. For example http://host/one/../two => http://host/two. If necessary, this behaviour can be suppressed by setting the JMeter property httpsampler.redirect.removeslashdotdot=false
No
Use KeepAliveJMeter sets the Connection: keep-alive header. This does not work properly with the default HTTP implementation, as connection re-use is not under user-control. It does work with the Apache HttpComponents HttpClient implementations.No
Use multipart/form-data for HTTP POSTUse a multipart/form-data or application/x-www-form-urlencoded post requestNo
Browser-compatible headersWhen using multipart/form-data, this suppresses the Content-Type and Content-Transfer-Encoding headers; only the Content-Disposition header is sent.No
PathThe path to resource (for example, /servlets/myServlet). If the resource requires query string parameters, add them below in the "Send Parameters With the Request" section. As a special case, if the path starts with "http://" or "https://" then this is used as the full URL. In this case, the server, port and protocol fields are ignored; parameters are also ignored for GET and DELETE methods. Also please note that the path is not encoded - apart from replacing spaces with %20 - so unsafe characters may need to be encoded to avoid errors such as URISyntaxException.Yes
Send Parameters With the RequestThe query string will be generated from the list of parameters you provide. Each parameter has a name and value , the options to encode the parameter, and an option to include or exclude an equals sign (some applications don't expect an equals when the value is the empty string). The query string will be generated in the correct fashion, depending on the choice of "Method" you made (ie if you chose GET or DELETE, the query string will be appended to the URL, if POST or PUT, then it will be sent separately). Also, if you are sending a file using a multipart form, the query string will be created using the multipart form specifications. See below for some further information on parameter handling.

Additionally, you can specify whether each parameter should be URL encoded. If you are not sure what this means, it is probably best to select it. If your values contain characters such as the following then encoding is usually required.:

  • ASCII Control Chars
  • Non-ASCII characters
  • Reserved characters:URLs use some characters for special use in defining their syntax. When these characters are not used in their special role inside a URL, they need to be encoded, example : '$', '&', '+', ',' , '/', ':', ';', '=', '?', '@'
  • Unsafe characters: Some characters present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded, example : ' ', '<', '>', '#', '%', ...

 

No
File Path:Name of the file to send. If left blank, JMeter does not send a file, if filled in, JMeter automatically sends the request as a multipart form request.

If it is a POST or PUT or PATCH request and there is a single file whose 'Parameter name' attribute (below) is omitted, then the file is sent as the entire body of the request, i.e. no wrappers are added. This allows arbitrary bodies to be sent. This functionality is present for POST requests after version 2.2, and also for PUT requests after version 2.3. See below for some further information on parameter handling.

No
Parameter name:Value of the "name" web request parameter.No
MIME TypeMIME type (for example, text/plain). If it is a POST or PUT or PATCH request and either the 'name' atribute (below) are omitted or the request body is constructed from parameter values only, then the value of this field is used as the value of the content-type request header.No
Retrieve All Embedded Resources from HTML FilesTell JMeter to parse the HTML file and send HTTP/HTTPS requests for all images, Java applets, JavaScript files, CSSs, etc. referenced in the file. See below for more details.No
Use as monitorFor use with the Monitor Results listener.No
Save response as MD5 hash?If this is selected, then the response is not stored in the sample result. Instead, the 32 character MD5 hash of the data is calculated and stored instead. This is intended for testing large amounts of data.No
Embedded URLs must match:If present, this must be a regular expression that is used to match against any embedded URLs found. So if you only want to download embedded resources from http://example.com/, use the expression: http://example\.com/.*No
Use concurrent poolUse a pool of concurrent connections to get embedded resources.No
SizePool size for concurrent connections used to get embedded resources.No
Source address type[Only for HTTP Request with HTTPClient implementation] 
To distinguish the source address value, select the type of these:
  • Select IP/Hostname to use a specific IP address or a (local) hostname
  • Select Device to pick the first available address for that interface which this may be either IPv4 or IPv6
  • Select Device IPv4 To select the IPv4 address of the device name (like eth0, lo, em0, etc.)
  • Select Device IPv6 To select the IPv6 address of the device name (like eth0, lo, em0, etc.)
No
Source address field[Only for HTTP Request with HTTPClient implementation] 
Override the default local IP address for this sample. The JMeter host must have multiple IP addresses (i.e. IP aliases, network interfaces, devices). The value can be a host name, IP address, or a network interface device such as "eth0" or "lo" or "wlan0". 
If the property httpclient.localaddress is defined, that is used for all HttpClient requests.
No



 

N.B. when using Automatic Redirection, cookies are only sent for the initial URL. This can cause unexpected behaviour for web-sites that redirect to a local server. E.g. if www.example.com redirects to www.example.co.uk. In this case the server will probably return cookies for both URLs, but JMeter will only see the cookies for the last host, i.e. www.example.co.uk. If the next request in the test plan uses www.example.com, rather than www.example.co.uk, it will not get the correct cookies. Likewise, Headers are sent for the initial request, and won't be sent for the redirect. This is generally only a problem for manually created test plans, as a test plan created using a recorder would continue from the redirected URL.

Parameter Handling: 
For the POST and PUT method, if there is no file to send, and the name(s) of the parameter(s) are omitted, then the body is created by concatenating all the value(s) of the parameters. Note that the values are concatenated without adding any end-of-line characters. These can be added by using the __char() function in the value fields. This allows arbitrary bodies to be sent. The values are encoded if the encoding flag is set (versions of JMeter after 2.3). See also the MIME Type above how you can control the content-type request header that is sent. 
For other methods, if the name of the parameter is missing, then the parameter is ignored. This allows the use of optional parameters defined by variables. (versions of JMeter after 2.3)


Since JMeter 2.6, you have the option to switch to Post Body when a request has only unnamed parameters (or no parameters at all). This option is useful in the following cases (amongst others):

  • GWT RPC HTTP Request
  • JSON REST HTTP Request
  • XML REST HTTP Request
  • SOAP HTTP Request
Note that once you leave the Tree node, you cannot switch back to the parameter tab unless you clear the Post Body tab of data.

 

In Post Body mode, each line will be sent with CRLF appended, apart from the last line. To send a CRLF after the last line of data, just ensure that there is an empty line following it. (This cannot be seen, except by noting whether the cursor can be placed on the subsequent line.)

 


Figure 1 - HTTP Request with one unnamed parameter

 

 


Figure 2 - Confirm dialog to switch

 

 


Figure 3 - HTTP Request using Body Data

 

Method Handling: 
The POST, PUT and PATCH request methods work similarly, except that the PUT and PATCH methods do not support multipart requests or file upload. The PUT and PATCH method body must be provided as one of the following:

  • define the body as a file with empty Parameter name field; in which case the MIME Type is used as the Content-Type
  • define the body as parameter value(s) with no name
  • use the Post Body tab
If you define any parameters with a name in either the sampler or Http defaults then nothing is sent. PUT and PATCH require a Content-Type. If not using a file, attach a Header Manager to the sampler and define the Content-Type there. The GET and DELETE request methods work similarly to each other.

 

Upto and including JMeter 2.1.1, only responses with the content-type "text/html" were scanned for embedded resources. Other content-types were assumed to be something other than HTML. JMeter 2.1.2 introduces the a new property HTTPResponse.parsers , which is a list of parser ids, e.g. htmlParser andwmlParser . For each id found, JMeter checks two further properties:

  • id.types - a list of content types
  • id.className - the parser to be used to extract the embedded resources

See jmeter.properties file for the details of the settings. If the HTTPResponse.parser property is not set, JMeter reverts to the previous behaviour, i.e. only text/html responses will be scanned

Emulating slow connections: 
# Define characters per second > 0 to emulate slow connections #httpclient.socket.http.cps=0 #httpclient.socket.https.cps=0  

Response size calculation 
Optional properties to allow change the method to get response size: 

  • Gets the real network size in bytes for the body response
    sampleresult.getbytes.body_real_size=true 
  • Add HTTP headers to full response size
    sampleresult.getbytes.headers_size=true 

 

The Java and HttpClient3 inplementations do not include transport overhead such as chunk headers in the response body size. 
The HttpClient4 implementation does include the overhead in the response body size, so the value may be greater than the number of bytes in the response content.

 

 

Versions of JMeter before 2.5 returns only data response size (uncompressed if request uses gzip/defate mode). 
To return to settings before version 2.5, set the two properties to false.

 

 

Retry handling 
In version 2.5 of JMeter, the HttpClient4 and Commons HttpClient 3.1 samplers used the default retry count, which was 3. In later versions, the retry count has been set to 1, which is what the Java implementation appears to do. The retry count can be overridden by setting the relevant JMeter property, for example:

httpclient4.retrycount=3 httpclient3.retrycount=3  

 

See Also:

 



18.1.4 Java Request

This sampler lets you control a java class that implements the org.apache.jmeter.protocol.java.sampler.JavaSamplerClient interface. By writing your own implementation of this interface, you can use JMeter to harness multiple threads, input parameter control, and data collection.

The pull-down menu provides the list of all such implementations found by JMeter in its classpath. The parameters can then be specified in the table below - as defined by your implementation. Two simple examples (JavaTest and SleepTest) are provided.

The JavaTest example sampler can be useful for checking test plans, because it allows one to set values in almost all the fields. These can then be used by Assertions, etc. The fields allow variables to be used, so the values of these can readily be seen.

Control Panel

 

Since JMeter 2.8, if the method teardownTest is not overriden by a subclass of AbstractJavaSamplerClient, its teardownTest method will not be called. This reduces JMeter memory requirements. This will not have any impact on existing Test plans.

 

 

The Add/Delete buttons don't serve any purpose at present.

 

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
ClassnameThe specific implementation of the JavaSamplerClient interface to be sampled.Yes
Send Parameters with RequestA list of arguments that will be passed to the sampled class. All arguments are sent as Strings. See below for specific settings.No

 

The following parameters apply to the SleepTest and JavaTest implementations:

Parameters

AttributeDescriptionRequired
Sleep_timeHow long to sleep for (ms)Yes
Sleep_maskHow much "randomness" to add: 
The sleep time is calculated as follows: 
totalSleepTime = SleepTime + (System.currentTimeMillis() % SleepMask)
Yes

 

The following parameters apply additionaly to the JavaTest implementation:

Parameters

AttributeDescriptionRequired
LabelThe label to use. If provided, overrides NameNo
ResponseCodeIf provided, sets the SampleResult ResponseCode.No
ResponseMessageIf provided, sets the SampleResult ResponseMessage.No
StatusIf provided, sets the SampleResult Status. If this equals "OK" (ignoring case) then the status is set to success, otherwise the sample is marked as failed.No
SamplerDataIf provided, sets the SampleResult SamplerData.No
ResultDataIf provided, sets the SampleResult ResultData.No

 


18.1.3 JDBC Request

This sampler lets you send an JDBC Request (an SQL query) to a database.

Before using this you need to set up a JDBC Connection Configuration Configuration element

If the Variable Names list is provided, then for each row returned by a Select statement, the variables are set up with the value of the corresponding column (if a variable name is provided), and the count of rows is also set up. For example, if the Select statement returns 2 rows of 3 columns, and the variable list is A,,C , then the following variables will be set up:

A_#=2 (number of rows) A_1=column 1, row 1 A_2=column 1, row 2 C_#=2 (number of rows) C_1=column 3, row 1 C_2=column 3, row 2  
If the Select statement returns zero rows, then the A_# and C_# variables would be set to 0, and no other variables would be set.

 

Old variables are cleared if necessary - e.g. if the first select retrieves 6 rows and a second select returns only 3 rows, the additional variables for rows 4, 5 and 6 will be removed.

Note: The latency time is set from the time it took to acquire a connection.

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
Variable NameName of the JMeter variable that the connection pool is bound to. This must agree with the 'Variable Name' field of a JDBC Connection Configuration.Yes
Query TypeSet this according to the statement type:
  • Select Statement
  • Update Statement - use this for Inserts as well
  • Callable Statement
  • Prepared Select Statement
  • Prepared Update Statement - use this for Inserts as well
  • Commit
  • Rollback
  • Autocommit(false)
  • Autocommit(true)
  • Edit - this should be a variable reference that evaluates to one of the above

 

When "Prepared Select Statement", "Prepared Update Statement" or "Callable Statement" types are selected, a Statement Cache per connection is used by JDBC Request. It stores by default up to 100 PreparedStatements per connection, this can impact your database (Open Cursors). This can be changed by defining the property "jdbcsampler.nullmarker".

 

Yes
SQL QuerySQL query. Do not enter a trailing semi-colon. There is generally no need to use { and } to enclose Callable statements; however they mey be used if the database uses a non-standard syntax. [The JDBC driver automatically converts the statement if necessary when it is enclosed in {}]. For example:
  • select * from t_customers where id=23
  • CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE (null,?, ?, null, null, null)
    • Parameter values: tablename,filename
    • Parameter types: VARCHAR,VARCHAR
  • The second example assumes you are using Apache Derby.
Yes
Parameter valuesComma-separated list of parameter values. Use ]NULL[ to indicate a NULL parameter. (If required, the null string can be changed by defining the property "jdbcsampler.nullmarker".) 
The list must be enclosed in double-quotes if any of the values contain a comma or double-quote, and any embedded double-quotes must be doubled-up, for example:
"Dbl-Quote: "" and Comma: ," 

 

There must be as many values as there are placeholders in the statement even if your parameters are OUT ones, be sure to set a value even if the value will not be used (for example in a CallableStatement).

 

Yes, if a prepared or callable statement has parameters
Parameter typesComma-separated list of SQL parameter types (e.g. INTEGER, DATE, VARCHAR, DOUBLE) or integer values of Constants when for example you use custom database types proposed by driver (-10 for OracleTypes.CURSOR for example). 
These are defined as fields in the class java.sql.Types, see for example: 
Javadoc for java.sql.Types 
[Note: JMeter will use whatever types are defined by the runtime JVM, so if you are running on a different JVM, be sure to check the appropriate document] 
If the callable statement has INOUT or OUT parameters, then these must be indicated by prefixing the appropriate parameter types, e.g. instead of "INTEGER", use "INOUT INTEGER". 
If not specified, "IN" is assumed, i.e. "DATE" is the same as "IN DATE". 
If the type is not one of the fields found in java.sql.Types, versions of JMeter after 2.3.2 also accept the corresponding integer number, e.g. since OracleTypes.CURSOR == -10, you can use "INOUT -10". 
There must be as many types as there are placeholders in the statement.
Yes, if a prepared or callable statement has parameters
Variable NamesComma-separated list of variable names to hold values returned by Select statements, Prepared Select Statements or CallableStatement. Note that when used with CallableStatement, list of variables must be in the same sequence as the OUT parameters returned by the call. If there are less variable names than OUT parameters only as many results shall be stored in the thread-context variables as variable names were supplied. If more variable names than OUT parameters exist, the additional variables will be ignoredNo
Result Variable NameIf specified, this will create an Object variable containing a list of row maps. Each map contains the column name as the key and the column data as the value. Usage: 
columnValue = vars.getObject("resultObject").get(0).get("Column Name");
No

 

See Also:

 

 

Versions of JMeter after 2.3.2 use UTF-8 as the character encoding. Previously the platform default was used.

 

 

Ensure Variable Name is unique accross Test Plan.

18.1.15 JMS Point-to-Point

 

BETA CODE - the code is still subject to change

 

This sampler sends and optionally receives JMS Messages through point-to-point connections (queues). It is different from pub/sub messages and is generally used for handling transactions.

Request Only will typically used to put load on a JMS System. 
Request Response will be used when you want to test response time of a JMS service that processes messages sent to the Request Queue as this mode will wait for the response on the Reply queue sent by this service. 

Versions of JMeter after 2.3.2 use the properties java.naming.security.[principal|credentials] - if present - when creating the Queue Connection. If this behaviour is not desired, set the JMeter property JMSSampler.useSecurity.properties=false


 

JMeter does not include any JMS implementation jar; this must be downloaded from the JMS provider and put in the lib directory

 

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
QueueConnection FactoryThe JNDI name of the queue connection factory to use for connecting to the messaging system.Yes
JNDI Name Request queueThis is the JNDI name of the queue to which the messages are sent.Yes
JNDI Name Reply queueThe JNDI name of the receiving queue. If a value is provided here and the communication style is Request Response this queue will be monitored for responses to the requests sent.No
JMS SelectorMessage Selector as defined by JMS specification to extract only messages that respect the Selector condition. Syntax uses subpart of SQL 92.No
Communication styleThe Communication style can be Request Only (also known as Fire and Forget) or Request Response :
  • Request Only will only send messages and will not monitor replies. As such it can be used to put load on a system.
  • Request Response will send messages and monitor the replies it receives. Behaviour depends on the value of the JNDI Name Reply Queue. If JNDI Name Reply Queue has a value, this queue is used to monitor the results. Matching of request and reply is done with the message id of the request and the correlation id of the reply. If the JNDI Name Reply Queue is empty, then temporary queues will be used for the communication between the requestor and the server. This is very different from the fixed reply queue. With temporary queues the sending thread will block until the reply message has been received. With Request Response mode, you need to have a Server that listens to messages sent to Request Queue and sends replies to queue referenced by message.getJMSReplyTo() .
Yes
Use alternate fields for message correlationThese check-boxes select the fields which will be used for matching the response message with the original request.
  • Use Request Message Id - if selected, the request JMSMessageID will be used, otherwise the request JMSCorrelationID will be used. In the latter case the correlation id must be specified in the request.
  • Use Response Message Id - if selected, the response JMSMessageID will be used, otherwise the response JMSCorrelationID will be used.
There are two frequently used JMS Correlation patterns:
  • JMS Correlation ID Pattern - i.e. match request and response on their correlation Ids => deselect both checkboxes, and provide a correlation id.
  • JMS Message ID Pattern - i.e. match request message id with response correlation id => select "Use Request Message Id" only.
In both cases the JMS application is responsible for populating the correlation ID as necessary.

 

if the same queue is used to send and receive messages, then the response message will be the same as the request message. In which case, either provide a correlation id and clear both checkboxes; or select both checkboxes to use the message Id for correlation. This can be useful for checking raw JMS throughput.

 

Yes
TimeoutThe timeout in milliseconds for the reply-messages. If a reply has not been received within the specified time, the specific testcase failes and the specific reply message received after the timeout is discarded.Yes
Use non-persistent delivery mode?Whether to set DeliveryMode.NON_PERSISTENT.Yes
ContentThe content of the message.No
JMS PropertiesThe JMS Properties are properties specific for the underlying messaging system. You can setup the name, the value and the class (type) of value. Default type is String. For example: for WebSphere 5.1 web services you will need to set the JMS Property targetService to test webservices through JMS.No
Initial Context FactoryThe Initial Context Factory is the factory to be used to look up the JMS Resources.No
JNDI propertiesThe JNDI Properties are the specific properties for the underlying JNDI implementation.No
Provider URLThe URL for the jms provider.No

 


18.1.13 JMS Publisher

 

BETA CODE - the code is still subject to change

 

JMS Publisher will publish messages to a given destination (topic/queue). For those not familiar with JMS, it is the J2EE specification for messaging. There are numerous JMS servers on the market and several open source options.


 

JMeter does not include any JMS implementation jar; this must be downloaded from the JMS provider and put in the lib directory

 

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
use JNDI properties fileuse jndi.properties. Note that the file must be on the classpath - e.g. by updating the user.classpath JMeter property. If this option is not selected, JMeter uses the "JNDI Initial Context Factory" and "Provider URL" fields to create the connection.Yes
JNDI Initial Context FactoryName of the context factoryNo
Provider URLThe URL for the jms providerYes, unless using jndi.properties
DestinationThe message destination (topic or queue name)Yes
SetupThe destination setup type. With At startup, the destination name is static (i.e. always same name during the test), with Each sample, the destination name is dynamic and is evaluate at each sample (i.e. the destination name may be a variable)Yes
AuthenticationAuthentication requirement for the JMS providerYes
UserUser NameNo
PasswordPassword (N.B. this is stored unencrypted in the test plan)No
Number of samples to aggregateNumber of samples to aggregateYes
Message sourceWhere to obtain the message:
  • From File : means the referenced file will be read and reused by all samples
  • Random File from folder specified below : means a random file will be selected from folder specified below, this folder must contain either files with extension .dat for Bytes Messages, or files with extension .txt or .obj for Object or Text messages
  • Text area : The Message to use either for Text or Object message
Yes
Message typeText, Map, Object message or Bytes MessageYes
Use non-persistent delivery mode?Whether to set DeliveryMode.NON_PERSISTENT (defaults to false)No
JMS PropertiesThe JMS Properties are properties specific for the underlying messaging system. You can setup the name, the value and the class (type) of value. Default type is String. For example: for WebSphere 5.1 web services you will need to set the JMS Property targetService to test webservices through JMS.No

 

For the MapMessage type, JMeter reads the source as lines of text. Each line must have 3 fields, delimited by commas. The fields are:

  • Name of entry
  • Object class name, e.g. "String" (assumes java.lang package if not specified)
  • Object string value
For each entry, JMeter adds an Object with the given name. The value is derived by creating an instance of the class, and using the valueOf(String) method to convert the value if necessary. For example:
name,String,Example size,Integer,1234  
This is a very simple implementation; it is not intended to support all possible object types.

 

 

 

The Object message is implemented since 2.7 and works as follow:
  • Put the JAR that contains your object and its dependencies in jmeter_home/lib/ folder
  • Serialize your object as XML using XStream
  • Either put result in a file suffixed with .txt or .obj or put XML content direclty in Text Area
Note that if message is in a file, replacement of properties will not occur while it will if you use Text Area.

 

 

The following table shows some values which may be useful when configuring JMS:

Apache ActiveMQValue(s)Comment
Context Factoryorg.apache.activemq.jndi.ActiveMQInitialContextFactory.
Provider URLvm://localhost 
Provider URLvm:(broker:(vm://localhost)?persistent=false)Disable persistence
Queue ReferencedynamicQueues/QUEUENAMEDynamically define the QUEUENAME to JNDI
Topic ReferencedynamicTopics/TOPICNAMEDynamically define the TOPICNAME to JNDI

 




18.1.14 JMS Subscriber

 

BETA CODE - the code is still subject to change

 

JMS Publisher will subscribe to messages in a given destination (topic or queue). For those not familiar with JMS, it is the J2EE specification for messaging. There are numerous JMS servers on the market and several open source options.


 

JMeter does not include any JMS implementation jar; this must be downloaded from the JMS provider and put in the lib directory

 

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
use JNDI properties fileuse jndi.properties. Note that the file must be on the classpath - e.g. by updating the user.classpath JMeter property. If this option is not selected, JMeter uses the "JNDI Initial Context Factory" and "Provider URL" fields to create the connection.Yes
JNDI Initial Context FactoryName of the context factoryNo
Provider URLThe URL for the jms providerNo
Destinationthe message destination (topic or queue name)Yes
Durable Subscription IDThe ID to use for a durable subscription. On first use the respective queue will automatically be generated by the JMS provider if it does not exist yet.No
Client IDThe Client ID to use when you you use a durable subscription. Be sure to add a variable like ${__threadNum} when you have more than one Thread.No
JMS SelectorMessage Selector as defined by JMS specification to extract only messages that respect the Selector condition. Syntax uses subpart of SQL 92.No
SetupThe destination setup type. With At startup, the destination name is static (i.e. always same name during the test), with Each sample, the destination name is dynamic and is evaluate at each sample (i.e. the destination name may be a variable)Yes
AuthenticationAuthentication requirement for the JMS providerYes
UserUser NameNo
PasswordPassword (N.B. this is stored unencrypted in the test plan)No
Number of samples to aggregatenumber of samples to aggregateYes
Read responseshould the sampler read the response. If not, only the response length is returned.Yes
TimeoutSpecify the timeout to be applied, in milliseconds. 0=none. This is the overall aggregate timeout, not per sample.Yes
ClientWhich client implementation to use. Both of them create connections which can read messages. However they use a different strategy, as described below:
  • MessageConsumer.receive() - calls receive() for every requested message. Retains the connection between samples, but does not fetch messages unless the sampler is active. This is best suited to Queue subscriptions.
  • MessageListener.onMessage() - establishes a Listener that stores all incoming messages on a queue. The listener remains active after the sampler completes. This is best suited to Topic subscriptions.
Yes
Stop between samples?If selected, then JMeter calls Connection.stop() at the end of each sample (and calls start() before each sample). This may be useful in some cases where multiple samples/threads have connections to the same queue. If not selected, JMeter calls Connection.start() at the start of the thread, and does not call stop() until the end of the thread.Yes
SeparatorSeparator used to separate messages when there is more than one (related to setting Number of samples to aggregate). Note that \n, \r, \t are accepted.No

 

NOTE: JMeter 2.3.4 and earlier used a different strategy for the MessageConsumer.receive() client. Previously this started a background thread which polled for messages. This thread continued when the sampler completed, so the net effect was similar to the MessageListener.onMessage() strategy.




18.1.11.1 JSR223 Sampler

The JSR223 Sampler allows JSR223 script code to be used to perform a sample.

The JSR223 test elements have a feature (compilation) that can significantly increase performance. To benefit from this feature:

  • Use Script files instead of inlining them. This will make JMeter compile them if this feature is available on ScriptEngine and cache them.
  • Or Use Script Text and fill in script cache key property, ensure it is unique across Test Plan as JMeter will use it to cache result of compilation.

     

    When using this feature, ensure you script code does not use JMeter variables directly in script code as caching would only cache first replacement. Instead use script parameters.

     

     

    To benefit fomr Caching and compilation, language engine used for scripting must implement JSR223 Compilable interface (Groovy is one of these, java, beanshell and javascript are not)

     

Cache size is controlled by the following jmeter property (jmeter.properties):
  • jsr223.compiled_scripts_cache_size=100
For details, see BSF Sampler .

 

 

Unlike the BeanShell sampler, the interpreter is not saved between invocations.

 

 

Since JMeter 2.8, JSR223 Test Elements using Script file or Script text + cache key are now Compiled if ScriptEngine supports this feature, this enables great performance enhancements.

 

Control Panel

 

JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props methods, e.g. props.get("START.HMS"); props.put("PROP1","1234");

 

18.1.16 JUnit Request

The current implementation supports standard Junit convention and extensions. It also includes extensions like oneTimeSetUp and oneTimeTearDown. The sampler works like the JavaSampler with some differences. 
1. rather than use Jmeter's test interface, it scans the jar files for classes extending junit's TestCase class. That includes any class or subclass. 
2. Junit test jar files should be placed in jmeter/lib/junit instead of /lib directory. In versions of JMeter after 2.3.1, you can also use the "user.classpath" property to specify where to look for TestCase classes. 
3. Junit sampler does not use name/value pairs for configuration like the JavaSampler. The sampler assumes setUp and tearDown will configure the test correctly. 
4. The sampler measures the elapsed time only for the test method and does not include setUp and tearDown. 
5. Each time the test method is called, Jmeter will pass the result to the listeners. 
6. Support for oneTimeSetUp and oneTimeTearDown is done as a method. Since Jmeter is multi-threaded, we cannot call oneTimeSetUp/oneTimeTearDown the same way Maven does it. 
7. The sampler reports unexpected exceptions as errors. There are some important differences between standard JUnit test runners and JMeter's implementation. Rather than make a new instance of the class for each test, JMeter creates 1 instance per sampler and reuses it. This can be changed with checkbox "Create a new instance per sample". 
The current implementation of the sampler will try to create an instance using the string constructor first. If the test class does not declare a string constructor, the sampler will look for an empty constructor. Example below:

Empty Constructor:
public class myTestCase {
public myTestCase() {}
}

String Constructor:
public class myTestCase {
public myTestCase(String text) {
super(text);
}
}
By default, Jmeter will provide some default values for the success/failure code and message. Users should define a set of unique success and failure codes and use them uniformly across all tests.
General Guidelines 
If you use setUp and tearDown, make sure the methods are declared public. If you do not, the test may not run properly. 
Here are some general guidelines for writing Junit tests so they work well with Jmeter. Since Jmeter runs multi-threaded, it is important to keep certain things in mind.

1. Write the setUp and tearDown methods so they are thread safe. This generally means avoid using static memebers.
2. Make the test methods discrete units of work and not long sequences of actions. By keeping the test method to a descrete operation, it makes it easier to combine test methods to create new test plans.
3. Avoid making test methods depend on each other. Since Jmeter allows arbitrary sequencing of test methods, the runtime behavior is different than the default Junit behavior.
4. If a test method is configurable, be careful about where the properties are stored. Reading the properties from the Jar file is recommended.
5. Each sampler creates an instance of the test class, so write your test so the setup happens in oneTimeSetUp and oneTimeTearDown.

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
Search for JUnit4 annotationsSelect this to search for JUnit 4 tests (@Test annotations)Yes
Package filterComma separated list of packages to show. Example, org.apache.jmeter,junit.framework.No
Class nameFully qualified name of the JUnit test class.Yes
Constructor stringString pass to the string constructor. If a string is set, the sampler will use the string constructor instead of the empty constructor.No
Test methodThe method to test.Yes
Success messageA descriptive message indicating what success means.No
Success codeAn unique code indicating the test was successful.No
Failure messageA descriptive message indicating what failure means.No
Failure codeAn unique code indicating the test failed.No
Error messageA description for errors.No
Error codeSome code for errors. Does not need to be unique.No
Do not call setUp and tearDownSet the sampler not to call setUp and tearDown. By default, setUp and tearDown should be called. Not calling those methods could affect the test and make it inaccurate. This option should only be used with calling oneTimeSetUp and oneTimeTearDown. If the selected method is oneTimeSetUp or oneTimeTearDown, this option should be checked.Yes
Append assertion errorsWhether or not to append assertion errors to the response message.Yes
Append runtime exceptionsWhether or not to append runtime exceptions to the response message. Only applies if "Append assertion errors" is not selected.Yes
Create a new Instance per sampleWhether or not to create a new JUnit instance for each sample. Defaults to false, meaning JUnit TestCase is created one and reused.Yes

 

The following JUnit4 annotations are recognised:

  • @Test - used to find test methods and classes. The "expected" and "timeout" attributes are supported.
  • @Before - treated the same as setUp() in JUnit3
  • @After - treated the same as tearDown() in JUnit3
  • @BeforeClass, @AfterClass - treated as test methods so they can be run independently as required

 

Note that JMeter currently runs the test methods directly, rather than leaving it to JUnit. This is to allow the setUp/tearDown methods to be excluded from the sample time.

18.4.11 LDAP Request Defaults

The LDAP Request Defaults component lets you set default values for LDAP testing. See the LDAP Request .

Control Panel

18.1.7 LDAP Request

This Sampler lets you send a different Ldap request(Add, Modify, Delete and Search) to an LDAP server.

If you are going to send multiple requests to the same LDAP server, consider using an LDAP Request Defaults Configuration Element so you do not have to enter the same information for each LDAP Request.

The same way the Login Config Element also using for Login and password.

Control Panel

There are two ways to create test cases for testing an LDAP Server.

  1. Inbuilt Test cases.
  2. User defined Test cases.

There are four test scenarios of testing LDAP. The tests are given below:

  1. Add Test
    1. Inbuilt test :

      This will add a pre-defined entry in the LDAP Server and calculate the execution time. After execution of the test, the created entry will be deleted from the LDAP Server.

    2. User defined test :

      This will add the entry in the LDAP Server. User has to enter all the attributes in the table.The entries are collected from the table to add. The execution time is calculated. The created entry will not be deleted after the test.

  2. Modify Test
    1. Inbuilt test :

      This will create a pre-defined entry first, then will modify the created entry in the LDAP Server.And calculate the execution time. After execution of the test, the created entry will be deleted from the LDAP Server.

    2. User defined test

      This will modify the entry in the LDAP Server. User has to enter all the attributes in the table. The entries are collected from the table to modify. The execution time is calculated. The entry will not be deleted from the LDAP Server.

  3. Search Test
    1. Inbuilt test :

      This will create the entry first, then will search if the attributes are available. It calculates the execution time of the search query. At the end of the execution,created entry will be deleted from the LDAP Server.

    2. User defined test

      This will search the user defined entry(Search filter) in the Search base (again, defined by the user). The entries should be available in the LDAP Server. The execution time is calculated.

  4. Delete Test
    1. Inbuilt test :

      This will create a pre-defined entry first, then it will be deleted from the LDAP Server. The execution time is calculated.

    2. User defined test

      This will delete the user-defined entry in the LDAP Server. The entries should be available in the LDAP Server. The execution time is calculated.

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
Server Name or IPDomain name or IP address of the LDAP server. JMeter assumes the LDAP server is listening on the default port(389).Yes
Portdefault port(389).Yes
root DNDN for the server to communicateYes
UsernameLDAP server username.Usually
PasswordLDAP server password. (N.B. this is stored unencrypted in the test plan)Usually
Entry DNthe name of the context to create or Modify; may not be empty Example: do you want to add cn=apache,ou=test you have to add in table name=cn, value=apacheYes
Deletethe name of the context to Delete; may not be emptyYes
Search basethe name of the context or object to searchYes
Search filterthe filter expression to use for the search; may not be nullYes
add testthis name, value pair to added in the given context objectYes
modify testthis name, value pair to add or modify in the given context objectYes

 

See Also:

 


18.1.17 Mail Reader Sampler

The Mail Reader Sampler can read (and optionally delete) mail messages using POP3(S) or IMAP(S) protocols.

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
Server TypeThe protocol used by the provider: e.g. pop3, pop3s, imap, imaps. or another string representing the server protocol. For examplefile for use with the read-only mail file provider. The actual provider names for POP3 and IMAP are pop3 and imapYes
ServerHostname or IP address of the server. See below for use with file protocol.Yes
PortPort to be used to connect to the server (optional)No
UsernameUser login nameNo
PasswordUser login password (N.B. this is stored unencrypted in the test plan)No
FolderThe IMAP(S) folder to use. See below for use with file protocol.Yes, if using IMAP(S)
Number of messages to retrieveSet this to retrieve all or some messagesYes
Delete messages from the serverIf set, messages will be deleted after retrievalYes
Store the message using MIMEWhether to store the message as MIME. If so, then the entire raw message is stored in the Response Data; the headers are not stored as they are available in the data. If not, the message headers are stored as Response Headers. A few headers are stored (Date, To, From, Subject) in the body.Yes
Use no security featuresIndicates that the connection to the server does not use any security protocol.No
Use SSLIndicates that the connection to the server must use the SSL protocol.No
Use StartTLSIndicates that the connection to the server should attempt to start the TLS protocol.No
Enforce StartTLSIf the server does not start the TLS protocol the connection will be terminated.No
Trust All CertificatesWhen selected it will accept all certificates independent of the CA.No
Use local truststoreWhen selected it will only accept certificates that are locally trusted.No
Local truststorePath to file containing the trusted certificates. Relative paths are resolved against the current directory. 
Failing that, against the directory containing the test script (JMX file).
No

 

Messages are stored as subsamples of the main sampler. In versions of JMeter after 2.3.4, multipart message parts are stored as subsamples of the message.

Special handling for "file" protocol: 
The file JavaMail provider can be used to read raw messages from files. The server field is used to specify the path to the parent of the folder . Individual message files should be stored with the name n.msg , where is the message number. Alternatively, the server field can be the name of a file which contains a single message. The current implementation is quite basic, and is mainly intended for debugging purposes.




18.1.20 OS Process Sampler

The OS Process Sampler is a sampler that can be used to execute commands on the local machine. 
It should allow execution of any command that can be run from the command line. 
Validation of the return code can be enabled, and the expected return code can be specified. 

Note that OS shells generally provide command-line parsing. This varies between OSes, but generally the shell will split parameters on white-space. Some shells expand wild-card file names; some don't. The quoting mechanism also varies between OSes. The sampler deliberately does not do any parsing or quote handling. The command and its parameters must be provided in the form expected by the executable. This means that the sampler settings will not be portable between OSes.

Many OSes have some built-in commands which are not provided as separate executables. For example the Windows DIR command is part of the command interpreter (CMD.EXE). These built-ins cannot be run as independent programs, but have to be provided as arguments to the appropriate command interpreter.

For example, the Windows command-line: DIR C:\TEMP needs to be specified as follows:

command:   CMD Param 1:   /C Param 2:   DIR Param 3:   C:\TEMP  

 

Control Panel

Parameters

AttributeDescriptionRequired
CommandThe program name to execute.Yes
Working directoryDirectory from which command will be executed, defaults to folder referenced by "user.dir" System propertyNo
Command ParametersParameters passed to the program name.No
Environment ParametersKey/Value pairs added to environment when running command.No
Standard input (stdin)Name of file from which input is to be taken (STDIN).No
Standard output (stdoutName of output file for standard output (STDOUT). If omitted, output is captured and returned as the response data.No
Standard error (stderr)Name of output file for standard error (STDERR). If omitted, output is captured and returned as the response data.No
Check Return CodeIf checked, sampler will compare return code with Expected Return Code.No
Expected Return CodeExpected return code for System Call, required if "Check Return Code" is checked.No
TimeoutTimeout for command in milliseconds, defaults to 0, which means NO timeout.No

 



18.1.19 SMTP Sampler

The SMTP Sampler can send mail messages using SMTP/SMTPS protocol. It is possible to set security propocols for the connection (SSL and TLS), as well as user authentication. If a security protocol is used a verification on the server certificate will occur. 
Two alternatives to handle this verification are available: 

  • Trust all certificates. This will ignore certificate chain verification
  • Use a local truststore. With this option the certificate chain will be validated against the local truststore file.

 

Control Panel

Parameters

AttributeDescriptionRequired
ServerHostname or IP address of the server. See below for use with file protocol.Yes
PortPort to be used to connect to the server. Defaults are: SMTP=25, SSL=465, StartTLS=587No
Address FromThe from address that will appear in the e-mailYes
Address ToThe destination e-mail address (multiple values separated by ";")Yes, unless CC or BCC is specified
Address To CCCarbon copy destinations e-mail address (multiple values separated by ";")No
Address To BCCBlind carbon copy destinations e-mail address (multiple values separated by ";")No
Address Reply-ToAlternate Reply-To address (multiple values separated by ";")No
Use AuthIndicates if the SMTP server requires user authenticationNo
UsernameUser login nameNo
PasswordUser login password (N.B. this is stored unencrypted in the test plan)No
Use no security featuresIndicates that the connection to the SMTP server does not use any security protocol.No
Use SSLIndicates that the connection to the SMTP server must use the SSL protocol.No
Use StartTLSIndicates that the connection to the SMTP server should attempt to start the TLS protocol.No
Enforce StartTLSIf the server does not start the TLS protocol the connection will be terminated.No
Trust All CertificatesWhen selected it will accept all certificates independent of the CA.No
Use local truststoreWhen selected it will only accept certificates that are locally trusted.No
Local truststorePath to file containing the trusted certificates. Relative paths are resolved against the current directory. 
Failing that, against the directory containing the test script (JMX file).
No
SubjectThe e-mail message subject.No
Suppress Subject HeaderIf selected, the "Subject:" header is omitted from the mail that is sent. This is different from sending an empty "Subject:" header, though some e-mail clients may display it identically.No
Include timestamp in subjectIncludes the System.currentTimemilis() in the subject line.No
Add HeaderAdditional headers can be defined using this button.No
MessageThe message body.No
Send plain body (i.e. not multipart/mixed)If selected, then send the body as a plain message, i.e. not multipart/mixed, if possible. If the message body is empty and there is a single file, then send the file contents as the message body. Note: If the message body is not empty, and there is at least one attached file, then the body is sent as multipart/mixed.No
Attach filesFiles to be attached to the message.No
Send .emlIf set, the .eml file will be sent instead of the entries in the Subject, Message, and Attached filesNo
Calculate message sizeCalculates the message size and stores it in the sample result.No
Enable debug logging?If set, then the "mail.debug" property is set to "true"No

 


18.1.5 SOAP/XML-RPC Request

This sampler lets you send a SOAP request to a webservice. It can also be used to send XML-RPC over HTTP. It creates an HTTP POST request, with the specified XML as the POST content. To change the "Content-type" from the default of "text/xml", use a HeaderManager. Note that the sampler will use all the headers from the HeaderManager. If a SOAP action is specified, that will override any SOAPaction in the HeaderManager. The primary difference between the soap sampler and webservice sampler, is the soap sampler uses raw post and does not require conformance to SOAP 1.1.

 

For versions of JMeter later than 2.2, the sampler no longer uses chunked encoding by default. 
For screen input, it now always uses the size of the data. 
File input uses the file length as determined by Java. 
On some OSes this may not work for all files, in which case add a child Header Manager with Content-Length set to the actual length of the file. 
Or set Content-Length to -1 to force chunked encoding.

 

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
URLThe URL to direct the SOAP request to.Yes
Send SOAP actionSend a SOAP action header? (overrides the Header Manager)No
Use KeepAliveIf set, sends Connection: keep-alive, else sends Connection: closeNo
Soap/XML-RPC DataThe Soap XML message, or XML-RPC instructions. Not used if the filename is provided.No
FilenameIf specified, then the contents of the file are sent, and the Data field is ignoredNo

 




18.1.12 TCP Sampler

The TCP Sampler opens a TCP/IP connection to the specified server. It then sends the text, and waits for a response. 
If "Re-use connection" is selected, connections are shared between Samplers in the same thread, provided that the exact same host name string and port are used. Different hosts/port combinations will use different connections, as will different threads. If both of "Re-use connection" and "Close connection" are selected, the socket will be closed after running the sampler. On the next sampler, another socket will be created. You may want to close a socket at the end of each thread loop. 
If an error is detected - or "Re-use connection" is not selected - the socket is closed. Another socket will be reopened on the next sample. 
The following properties can be used to control its operation:

  • tcp.status.prefix - text that precedes a status number
  • tcp.status.suffix - text that follows a status number
  • tcp.status.properties - name of property file to convert status codes to messages
  • tcp.handler - Name of TCP Handler class (default TCPClientImpl) - only used if not specified on the GUI
The class that handles the connection is defined by the GUI, failing that the property tcp.handler. If not found, the class is then searched for in the package org.apache.jmeter.protocol.tcp.sampler.

Users can provide their own implementation. The class must extend org.apache.jmeter.protocol.tcp.sampler.TCPClient.

The following implementations are currently provided.

  • TCPClientImpl
  • BinaryTCPClientImpl
  • LengthPrefixedBinaryTCPClientImpl
The implementations behave as follows:

 

TCPClientImpl 
This implementation is fairly basic. When reading the response, it reads until the end of line byte, if this is defined by setting the propertytcp.eolByte , otherwise until the end of the input stream. You can control charset encoding by setting tcp.charset , which will default to Platform default encoding.

BinaryTCPClientImpl 
This implementation converts the GUI input, which must be a hex-encoded string, into binary, and performs the reverse when reading the response. When reading the response, it reads until the end of message byte, if this is defined by setting the property tcp.BinaryTCPClient.eomByte , otherwise until the end of the input stream.

LengthPrefixedBinaryTCPClientImpl 
This implementation extends BinaryTCPClientImpl by prefixing the binary message data with a binary length byte. The length prefix defaults to 2 bytes. This can be changed by setting the property tcp.binarylength.prefix.length .

Timeout handling If the timeout is set, the read will be terminated when this expires. So if you are using an eolByte/eomByte, make sure the timeout is sufficiently long, otherwise the read will be terminated early.

Response handling 
If tcp.status.prefix is defined, then the response message is searched for the text following that up to the suffix. If any such text is found, it is used to set the response code. The response message is then fetched from the properties file (if provided). 
For example, if the prefix = "[" and the suffix = "]", then the following repsonse: 
[J28] XI123,23,GBP,CR 
would have the response code J28. 
Response codes in the range "400"-"499" and "500"-"599" are currently regarded as failures; all others are successful. [This needs to be made configurable!]

 

The login name/password are not used by the supplied TCP implementations.

 


Sockets are disconnected at the end of a test run.

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
TCPClient classnameName of the TCPClient class. Defaults to the property tcp.handler, failing that TCPClientImpl.No
ServerName or IPName or IP of TCP serverYes
Port NumberPort to be usedYes
Re-use connectionIf selected, the connection is kept open. Otherwise it is closed when the data has been read.Yes
Close connectionIf selected, the connection will be closed after running the sampler.Yes
SO_LINGEREnable/disable SO_LINGER with the specified linger time in seconds when a socket is created. If you set "SO_LINGER" value as 0, you may prevent large numbers of sockets sitting around with a TIME_WAIT status.No
End of line(EOL) byte valueByte value for end of line, set this to a value outside the range -128 to +127 to skip eol checking. You may set this in jmeter.properties file as well with eolByte property. If you set this in TCP Sampler Config and in jmeter.properties file at the same time, the setting value in the TCP Sampler Config will be used.No
Connect TimeoutConnect Timeout (milliseconds, 0 disables).No
Response TimeoutResponse Timeout (milliseconds, 0 disables).No
Set NodelaySee java.net.Socket.setTcpNoDelay(). If selected, this will disable Nagle's algorithm, otherwise Nagle's algorithm will be used.Yes
Text to SendText to be sentYes
Login UserUser Name - not used by default implementationNo
PasswordPassword - not used by default implementation (N.B. this is stored unencrypted in the test plan)No

 

8.1.18 Test Action

The Test Action sampler is a sampler that is intended for use in a conditional controller. Rather than generate a sample, the test element eithers pauses or stops the selected target.

This sampler can also be useful in conjunction with the Transaction Controller, as it allows pauses to be included without needing to generate a sample. For variable delays, set the pause time to zero, and add a Timer as a child.

The "Stop" action stops the thread or test after completing any samples that are in progress. The "Stop Now" action stops the test without waiting for samples to complete; it will interrupt any active samples. If some threads fail to stop within the 5 second time-limit, a message will be displayed in GUI mode. You can try using the Stop command to see if this will stop the threads, but if not, you should exit JMeter. In non-GUI mode, JMeter will exit if some threads fail to stop within the 5 second time limit. [This can be changed using the JMeter property jmeterengine.threadstop.wait ]

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this element that is shown in the tree.No
TargetCurrent Thread / All Threads (ignored for Pause)Yes
ActionPause / Stop / Stop Now / Go to next loop iterationYes
DurationHow long to pause for (milliseconds)Yes, if Pause is selected

 




18.1.6 WebService(SOAP) Request (DEPRECATED)

*** This element is deprecated. Use HTTP_Request instead ***

This sampler has been tested with IIS Webservice running .NET 1.0 and .NET 1.1. It has been tested with SUN JWSDP, IBM webservices, Axis and gSoap toolkit for C/C++. The sampler uses Apache SOAP driver to serialize the message and set the header with the correct SOAPAction. Right now the sampler doesn't support automatic WSDL handling, since Apache SOAP currently does not provide support for it. Both IBM and SUN provide WSDL drivers. There are 3 options for the post data: text area, external file, or directory. If you want the sampler to randomly select a message, use the directory. Otherwise, use the text area or a file. The if either the file or path are set, it will not use the message in the text area. If you need to test a soap service that uses different encoding, use the file or path. If you paste the message in to text area, it will not retain the encoding and will result in errors. Save your message to a file with the proper encoding, and the sampler will read it as java.io.FileInputStream.

An important note on the sampler is it will automatically use the proxy host and port passed to JMeter from command line, if those fields in the sampler are left blank. If a sampler has values in the proxy host and port text field, it will use the ones provided by the user. This behavior may not be what users expect.

By default, the webservice sampler sets SOAPHTTPConnection.setMaintainSession (true). If you need to maintain the session, add a blank Header Manager. The sampler uses the Header Manager to store the SOAPHTTPConnection object, since the version of apache soap does not provide a easy way to get and set the cookies.

Note: If you are using CSVDataSet, do not check "Memory Cache". If memory cache is checked, it will not iterate to the next value. That means all the requests will use the first value.

Make sure you use <soap:Envelope rather than <Envelope. For example:

<?xml version="1.0" encoding="utf-8"?> <soap:Envelope  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <foo xmlns="http://clients-xlmns"/> </soap:Body> </soap:Envelope>  

 

The SOAP library that is used does not support SOAP 1.2, only SOAP 1.1. Also the library does not provide access to the HTTP response code (e.g. 200) or message (e.g. OK). To get round this, versions of JMeter after 2.3.2 check the returned message length. If this is zero, then the request is marked as failed.

 

Control Panel

Parameters

AttributeDescriptionRequired
NameDescriptive name for this sampler that is shown in the tree.No
WSDL URLThe WSDL URL with the service description. Versions of JMeter after 2.3.1 support the file: protocol for local WSDL files.No
Web MethodsWill be populated from the WSDL when the Load WSDL button is pressed. Select one of the methods and press the Configure button to populate the Protocol, Server, Port, Path and SOAPAction fields.No
ProtocolHTTP or HTTPS are acceptable protocol.Yes
Server Name or IPThe hostname or IP address.Yes
Port NumberPort Number.Yes
TimeoutConnection timeout.No
PathPath for the webservice.Yes
SOAPActionThe SOAPAction defined in the webservice description or WSDL.Yes
Soap/XML-RPC DataThe Soap XML messageYes
Soap fileFile containing soap messageNo
Message(s) FolderFolder containing soap files. Files are choose randomly during test.No
Memory cacheWhen using external files, setting this causes the file to be processed once and caches the result. This may use a lot of memory if there are many different large files.Yes
Read SOAP ResponseRead the SOAP reponse (consumes performance). Permit to have assertions or post-processorsNo
Use HTTP ProxyCheck box if http proxy should be usedNo
Server Name or IPProxy hostnameNo
Port NumberProxy host portNo

 

 

Webservice Soap Sampler assumes that empty response means failure.

 

posted on 2014-03-05 11:25 顺其自然EVO 阅读(14378) 评论(0)  编辑  收藏 所属分类: jmeter


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜