Jmeter - how to write specific variable to CSV file to specific row/column - jmeter

My csv file looks like:
TC_name, username, password, excpecedCode
ad_test_master_successful_login,username,Test123!,200
What is the easiest way to so i can write to csv to specific row/column, and example to overwrite Test123! with variable fetched from user defined variables?
I know i can read value using JSR223 Pre/post processor with ex:
def line10 = new File('C:/Users/test/Desktop/testData/login.csv').readLines().get(1).split(",")[2]
log.warn("csv as-> " + line10);

There is no such concept as "cell" in CSV files, if you're looking for the code which will replace one string with another, you can do something like:
def file = new File('test.csv')
def text = file.text.replaceAll('Test123!', vars.get('foo'))
file.text = text
If you're looking for a better option you can consider using GroovyCSV library (you will need to download it and place in JMeter Classpath followed by JMeter restart) or consider switching to Excel file where you will have full control via Apache POI library like it's described in How to Implement Data Driven Testing in your JMeter Test article

Related

Save extracted variable value in a pdf file using JSR223 PostProcessor

How to save the extracted variable value(text/content) in a pdf file using JSR223 PostProcessor in JMeter??
let say variable name ${data} .
Please suggest some solutions.
You will need a library like PDFBox for this
Add it and all its dependencies to JMeter Classpath
Restart JMeter to pick the .jars up
The simplest code to write a JMeter Variable into a PDF file would be something like:
def document = new org.apache.pdfbox.pdmodel.PDDocument()
def page = new org.apache.pdfbox.pdmodel.PDPage()
document.addPage(page)
def font = org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA_BOLD
// Start a new content stream which will "hold" the to be created content
def contentStream = new org.apache.pdfbox.pdmodel.PDPageContentStream(document, page)
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.beginText()
contentStream.setFont(font, 12)
contentStream.moveTextPositionByAmount(100, 700)
contentStream.drawString(vars.get('data'))
contentStream.endText()
// Make sure that the content stream is closed:
contentStream.close()
// Save the results and ensure that the document is properly closed:
document.save('path-to-your-file.pdf')
document.close()
More information:
Apache Groovy: What Is Groovy Used For?
Apache PDFBox Cookbook - Document Creation

How to pass variable value in selenium-javascript

In script I used org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('result33.csv'), 'User,Items per page,Pagination / Activity,Time to load(ms)' + newline, 'UTF-8', true) now I want to pass user value and time to load value dynamically (Actually I calculated those value in my script) so how to pass this value in above function?
and can you please provide how to pass variable(which used in script) and its value in Flexible File Writer
You have WDS.vars shorthand which provides read/write access to JMeterVariables class instance so you can do:
var foo = WDS.vars.get('foo')
to read the foo variable value from JMeter Variables
or
WDS.vars.put('foo', 'bar')
to create a JMeter Variable called foo with the value of bar
In order to be able to use the variables in the Flexible File Writer you need to declare them via sample_variables property, i.e. add the next line to user.properties file (lives in "bin" folder of your JMeter Installation)
sample_variables=foo
and next time you start JMeter you will be able to refer the variable as variable#0
if you have 2 variables like:
sample_variables=foo,bar
the first one will be variable#0, the second one will be variable#1, etc.
More information: Using the JMeter Flexible File Writer Plugin

Store extracted value in csv file using jsr223 postprocessor in jmeter

How can i store extracted value of a variable in a csv/text file using JSR223 post processor
If this is something you really need to do in the JSR223 PostProcessor the minimal code would be:
new File('/path/to/your/file.csv') << vars.get('YOUR_VARIABLE_NAME_HERE') << System.getProperty('line.separator')
However if there will be a minimal concurrency you will run into the race condition when 2 or more threads (virtual users) will be writing into the same file resulting in data corruption
The approach which I would recommend is using:
Declare the variable you want to store via Sample Variables JMeter Property by adding the next line to user.properties file (lives in "bin" folder of your JMeter installation):
sample_variables=YOUR_VARIABLE_NAME_HERE
Once done you will be able to write the values using Flexible File Writer configured like:
You basically need to write the code to write into file.
Something like:
import org.apache.commons.io.FilenameUtils;
attr1 = vars.get("attr1");
attr2 = vars.get("attr2");
f = new FileOutputStream(locationOfCSVOutputfile, true);
p = new PrintStream(f);
p.println(attr2+","+attr2);
p.close();
f.close();
Like wise get the values you need and write into the file by comma separated.
Beware that in multiple threads scenario, Many threads will be accessing same file. therefore the file output may not be what you expected. To overcome this I used a critical section controller.
Hope this helps.
1/ Consider for example a node in your test plan with your request :
A regular expression extractor and a JR223 post processor component as child of your request.
2/ If you extract for example a multiple variable named "blabla" positioning the match number to "-1"
3/ Here's the piece of Groovy code that you can use in your post processor component to write your variable in a file :
import org.apache.jmeter.*;
File outputFile = new File("MY_FILE.csv")
int max = Integer.parseInt(vars.get("blabla_matchNr"));
for (i=1;i<max;i++) {
def word = vars.get("blabla_"+i);
outputFile << word << "\r\n"
}

Jmeter Debug Sampler | How to save all variable values to CSV

I am able to extract values for many variables and are showing in Debug Sampler.
Is there any way to save these all variable values to a CSV file?
I found a solution (using BeanShell script) to save multiple Jmeter variable to CSV but I want all variables values to a single CSV, so that I can use the CSV file for next thread run.
Here is the snapshot of one of the Debug Sampler:
enterCompanyname=APITENANT
CreateTenant_Status=Success
CreateTenant_Status_matchNr=1
Current_UTC_Time=2018-03-07T01:53:18.310Z
DB_DataSource=dev4574857
DB_Password=1234
DB_UserName=web
DeviceCount=19
DevicesPerUser=94
EXCELPATH=X:\QualityAssurance\XLSX_3 columns_1000 rows.xlsx
Email=apitenant#apitenant.com
EndDate=2018-12-31
Exist=false
Exist_matchNr=1
FirstName=API
JMeterThread.last_sample_ok=true
JMeterThread.pack=org.apache.jmeter.threads.SamplePackage#69ab73cf
LastName=TENANT
LicensePlan=Pro
LicenseType=Device
MaxUsers=11
Password=Password
Protocol=http
RandomNumber=10
Add JSR223 Sampler to your Test Plan (where you want variables to be saved)
Put the following code into "Script" area:
def csv = new File('vars.csv')
vars.entrySet().each {var ->
csv << var.key + '=' + var.value + System.getProperty('line.separator')
}
That's it, you will have vars.csv file created in JMeter's "bin" folder having all variables listed. You might also want to replace = with , for better CSV Data Set Config compatibility.
vars is a shorthand to JMeterVariables class instance, it provides read/write access to all JMeter Variables.
Also be aware that starting from JMeter 3.1 users are encouraged to switch to JSR223 Test Elements and Groovy language so consider migrating to Groovy as soon as it will be possible. See Apache Groovy - Why and How You Should Use It for more details.

Trying to generate JMeter Test Plan (jmx) With JMeter API : Not able to save CSVDataSet element

I am creating a JMeter jmx file dynamically by using JMeter APIs. I am able to add a ThreadGroup within a TestPlan and a JavaSampler within the ThreadGroup. But when I add a CSVDataSet element within the Java Sampler, it does not get saved properly.
The following code is used to create a new CSVDataSet element
CSVDataSet csvDataSet = new CSVDataSet();
csvDataSet.setName("CSV Data Set");
csvDataSet.setComment("Sample CSV Data Set");
csvDataSet.setDelimiter(",");
csvDataSet.setFileEncoding("");
csvDataSet.setFilename("d:\\jmeter\\data.csv"); // variable
csvDataSet.setQuotedData(true);
csvDataSet.setRecycle(true);
csvDataSet.setShareMode(shareMode.all);
csvDataSet.setStopThread(false);
csvDataSet.setVariableNames("firstname, lastname, email"); // variable
csvDataSet.setEnabled(true);
When this is saved using SaveService.saveTree, the final jmx does not contain all the values which were set.
<org.apache.jorphan.collections.HashTree>
<CSVDataSet testname="CSV Data Set Config" enabled="true">
<stringProp name="TestPlan.comments">Sample CSV Data Set Config</stringProp>
</CSVDataSet>
<org.apache.jorphan.collections.HashTree/>
As seen above, only the test name, enabled, and comments are added. The rest of the variables are completely ignored.
Is there something that needs to be set in order to get all the values as expected?
or is this a bug in JMeter? I am using version 2.11
The basic code is as per section 4.3 from following link
http://blazemeter.com/blog/5-ways-launch-jmeter-test-without-using-jmeter-gui
To that I add the code shown above. The way it is added is,
testPlanTree.add("testPlan", testPlan);
testPlanTree.add("loopController", loopController);
testPlanTree.add("threadGroup", threadGroup);
testPlanTree.add("httpSampler", httpSampler);
testPlanTree.add("csvDataSet", csvDataSet);
SaveService
.saveTree(testPlanTree, new FileOutputStream("d:\\test.jmx"));
output of CSVDataSet block is as shown above.
After looking into the JMeter source code, it seems all the properties are set using the setProperty function rather than the individual setter functions. So putting the following code does the job of creating the CSVDataSet element properly.
csvDataSet.setProperty("delimiter", ",");
csvDataSet.setProperty("fileEncoding", "");
csvDataSet.setProperty("filename", "d:\\data.csv");
csvDataSet.setProperty("quotedData", true);
csvDataSet.setProperty("recycle", true);
csvDataSet.setProperty("shareMode", "shareMode.all");
csvDataSet.setProperty("stopThread", false);
csvDataSet.setProperty("variableNames", "var1, var2, var3");
Not sure why setters are not used in the code, but this seems to be the way to go for now
It is clearly not a bug in JMeter otherwise CSV Data Set could not be saved.
It is probably an issue in the way you build the HashTree, but unless you show the full code, you cannot get help.
By the way, as I said in a previous answer, what you are trying to do to build different tests based on input parameter is not good idea IMHO, the approach will be very fragile towards upcoming versions of JMeter.
JMeter provides ways to do it that you should follow.

Resources