Search code examples
jmeterperformance-testing

Use the same regular expression at multiple requests


I have a scenario, where a regular expression is to be applied at multiple requests (not all of them).

For example:

  1. Request-1 generates a token-id.
  2. This needs to be extracted with an expression say connectionToken":"(.+?)".
  3. Use this variable in the next 2 subsequent requests.
  4. Third request generates another token-id.
  5. This also would need the same expression to be used.
  6. Use this in the next two requests.
  7. Similarly, fifth request generates a token-id and so on...

Is there a way to optimize this with a single regular expression extractor?

Note: Placing the extractor at Thread Group level doesn't seem to be an efficient option.

I want to use a single regular expression extractor. This extractor has to apply the regular expression at appropriate requests. Accordingly, variables need to be used in the succeeding requests.


Solution

  • JMeter Post-Processors obey JMeter Scoping Rules to wit each Regular Expression Extractor will be executed after each Sampler it its scope.

    And if 2nd request doesn't return a connectionToken - the variable will have empty or default value and 3rd request will fail.

    The easiest solution would be just copying and pasting the Regular Expression Extractor.

    If you don't want to duplicate the code you can switch to JSR223 PostProcessor and extract the token conditionally, for example basing on Sampler's label or presence of connectionToken in the response.

    Something like:

    def response = prev.getResponseDataAsString()
    
    if (response.contains('connectionToken')) {
        def token = (response =~ 'connectionToken":"(.+?)"')[0][1]
        vars.put('token', token)
    }
    

    See Top 8 JMeter Java Classes You Should Be Using with Groovy article to learn more about what do these prev and vars guys mean and Find Operator Groovy documentation chapter on the approach of the extracting the text.