Want to fetch first three character from the String - jmeter

I have use case in JMeter JSR223 where I want to fetch First three characters from a String
Example given Below
def randomPrefix = org.apache.commons.lang3.RandomStringUtils.randomAlphabetic(6)
vars.put("Trailer_ID", TrailerId)
Output: Trailer_ID : QlWBvp
I want to fetch only QlW

How about String.take() function
def foo = vars.get('Trailer_ID').take(3)
Demo:
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?

Related

how to write in csv ${__threadNum}${__time(ddMMyyyy,)}${__BeanShell(vars.getIteration();,)} in jmeter?

I am generating some unique number by combination of ${__threadNum}${__time(ddMMyyyy,)}${__BeanShell(vars.getIteration();,)}
now i want to write same number in csv or txt in jmeter.
I am using bean shell post processor for this.
Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language
You should not be inlining JMeter Functions or Variables into Groovy scripts
Assuming above points here is the relevant Groovy piece of code
def first = ctx.getThreadNum()
def second = new java.text.SimpleDateFormat('ddMMyyyy').format(new Date())
def third = vars.getIteration()
new File('myFile.txt') << first << second << third
More information: Apache Groovy - Why and How You Should Use It
Use the below code:-
int random_var = ${__threadNum}${__time(ddMMyyyy,)}${__BeanShell(vars.getIteration();,)};
f = new FileOutputStream("D:/Output1.csv", true);
p = new PrintStream(f);
this.interpreter.setOut(p);
print(random_var);
f.flush();
f.close();
There are various ways but above is one example.For performance improvement it is recommended to use groovy.
Other help articles:-https://www.blazemeter.com/blog/saving-data-to-csv-files-with-java-through-jmeter
For groovy check:-https://stackoverflow.com/questions/51597623/jmeter-jsr223-sampler-unable-to-write-data-to-csv-file

How to remove the characters �� from the JSON response using Jmeter?

Below is the JSON Response from the Server, How to remove the characters �� from the below Response using Jmeter
Response :
{"_id":"5d56cc5c31acfd001298e863","test_id":"5d56cc593801370012bdb2bb","display_order":"1","question_type":"MULTIPLE CHOICE","isbn":"9780393630749","status":"added","question":{"_id":"5d56cc5c31acfd001298e864","questionId":"5d4262bb56c1d800122fcb48","QuestionTitle":{"key":"","value":"","valueRTF":"","valueHtml":"��������\n
I have written the groovy Script. but it is not removing the char.
def response = prev.getResponseDataAsString();
def var1= response.replaceAll("\�", "");
and I need to use this Var1 in another request.
Most probably you're seeing these question marks due to encoding problems, try setting file.encoding property to UTF-8 in system.properties file and restart JMeter, most probably you will see normal text instead of the question marks.
If for some reason the above hint is not applicable I would recommend replacing the whole valueHtml attribute value using JsonBuilder, the relevant code would be something like:
def builder = new groovy.json.JsonBuilder(new groovy.json.JsonSlurper().parse(prev.getResponseData()))
builder.content.question.QuestionTitle.valueHtml = ''
vars.put('Var1', builder.toPrettyString())
As the result you will have the same JSON structure with empty valueHtml attribute.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
As it is a JSON Response, add JSON Extractor Post Processor to the Parent Sampler from where the Response is expected. Extract whole JSON with following settings:
Now, use a JSR223 Sampler, with following code in script area:
String var1 = vars.get("jsonOutput");
log.info("Output: " + var1);
String replaceString=var1.replace('?','-'); // replace with whatever you want to, I am replacing it with '-'
log.info("Output: " + replaceString);
vars.put("NewString", replaceString);
Afterwards, you can use ${NewString} wherever you want.

Jmeter values mapping

How to achieve a kind of mapping between string and numeric values that can be used for comparison in assertion? Example:
MAP "DELIVERED"=0
"PENDING"=1
"WAITING"=2
sampler1 - extracted numeric_value=0
sampler2 - assert string value="DELIVERED" is equal to its numeric value
Please check the below test plan:-
I have used variable name from regular expression of 1st sampler in the switch controller like ${regVar}..Then used the second request 3 times i.e. 0,1,2 and used response assertion with the desired value like "DELIVERED"=0 for first sampler under switch i.e "0" then in second "PENDING"=1 i.e "1"..so on.
With this, based on the regEx value from 1st http sample, only one http request will be send for 2nd sampler and that request have it own assertion. I have tried with both positive and negative cases. Please change the assertion value based on your requirements.
Please check if it helps.
Be aware of JSR223 Assertion which allows you to use arbitrary Groovy code to define pass/fail criteria.
You can access the numeric_value using vars shorthand for JMeterVariables class like:
def numericValue = vars.get('numeric_value')
Example code:
def myMap = ['0':'DELIVERED', '1':'PENDING', '2':'WAITING']
def numericValue = vars.get('numeric_value')
log.info('Numeric value is: ' + numericValue)
log.info('Status is: ' + myMap.get(numericValue))
Demo:
More information: Scripting JMeter Assertions in Groovy - A Tutorial
Thanks Dmitri, implemented solution based on your suggestion and it suites fine.

Taurus / performance tests: verify data inside a JsonArray

I extract a JsonArray containing a list of string, and I want to validate by a regex each string inside this object.
Problem, I don't seem to find any answers on the Taurus' website.
Do you know how I can do it ?
Example below:
# Verification of value inside the JsonArray
extract-jsonpath:
names: $.names
- foreach: name in names
do:
- jsonpath: ${name} # if this JSONPATH is not found, assert will fail
validate: true # validate against an expected value
expected-value: "\\w" # value we're expecting to validate. [default: false]
regexp: true # if the value is regular expression, default: true
expect-null: false # expected value is null
invert: false # invert condition
I don't think it is possible with Taurus YAML syntax as:
foreach keyword generates a normal JMeter ForEach Controller
These jsonpath, validate, etc. are applied to a Sampler by default, they will not work if you add them just as children of the ForEach Controller
Assuming above points I would suggest adding a JSR223 PostProcesssor to perform all the checks. In Taurus it is being done via JSR223 Blocks like:
- url: https://api.example.com/v1/media/search
extract-jsonpath:
names: $.names
jsr223:'1.upto(vars.get("names_matchNr") as int,{if (vars.get("names_$it").matches("\\w+")) {prev.setSuccessful(false)}})'
See The Groovy Templates Cheat Sheet for JMeter article to get more ideas with regards to what can be done using Groovy scripts.

Looping through JSON response + in JMETER

I am using Jmeter for performance testing and stuck at following point:
I am getting a JSON response from Webapi as follows:
PersonInfoList:
Person
[0]
{
id: 1
name: Steve
}
[1]
Person
{
id: 2
name: Mark
}
I need to get the ids based on the count of this JSON array and create a comma separated string as ("Expected value" = 1,2)
I know how to read a particular element using JSON Post processor or Regex processor but am unable to loop through the array and create a string as explained so that I can use this value in my next sampler request.
Please help me out with this: I am using Jmeter 3.0 and if this could be achieved without using external third party libs that would be great. Sorry for the JSON syntax above
Actually similar functionality comes with JSON Path PostProcessor which appeared in JMeter 3.0. In order to get all the values in a single variable configure JSON Path PostProcessor as follows:
Variable Names: anything meaningful, i.e. id
JSON Path Expressions: $..id or whatever you use to extract the ids
Match Numbers: -1
Compute concatenation var (suffix _ALL): check
As a result you'll get id_ALL variable which will contain all JSON Path expression matches (comma-separated)
More "universal" answer which will be applicable for any other extractor types and in fact will allow to concatenate any arbitrary JMeter Variables is using scripting (besides if you need this "expected value and parentheses)
In order to concatenate all variables which names start with "id" into a single string add Beanshell PostProcessor somewhere after JSON Path PostProcessor and put the following code into "Script" area
StringBuilder result = new StringBuilder();
result.append("(\"Expected value\" = ");
Iterator iterator = vars.getIterator();
while (iterator.hasNext()) {
Map.Entry e = (Map.Entry) iterator.next();
if (e.getKey().matches("id_(\\d+)")) {
result.append(e.getValue());
result.append(",");
}
}
result.append(")");
vars.put("expected_value", result.toString());
Above code will store the resulting string into ${expected value} JMeter Variable. See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information regarding bypassing JMeter limitations using scripting and using JMeter and Java API from Beanshell test elements.
Demo:

Resources