Save extracted variable value in a pdf file using JSR223 PostProcessor - jmeter

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

Related

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

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

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"
}

Writing web service response to excel

I am trying to wrote the response of a restful service response to excel.
In the below once, if my test case response is below one, then i need to write to csv or excel for sheet1 (in excel) TC01, sampleResponse
<user-batch-result xmlns="http://www.xxxxxx.com/api//02" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<records-succeeded>1</records-succeeded>
<records-failed>0</records-failed>
<UsersDetails>
<UserInfo>
<EmployeeID>xxxxx</EmployeeID>
<FeedRecordNumber>0</FeedRecordNumber>
<Status>SUCCESS</Status>
</UserInfo>
</UsersDetails>
You can do something like:
Download tika-app.jar and drop it somewhere to JMeter Classpath (i.e. to "lib" folder of your JMeter installation). JMeter restart will be required to pick the .jar up.
Add JSR223 PostProcessor as a child of the request which returns the above response
Put the following code into "Script" area:
def wb = new org.apache.poi.hssf.usermodel.HSSFWorkbook()
def sheet1 = wb.createSheet("sheet1")
def row = sheet1.createRow(0)
def A1 = row.createCell(0, org.apache.poi.ss.usermodel.CellType.STRING)
A1.setCellValue(prev.getResponseDataAsString())
wb.write(new File('myFile.xlsx'))
Run your test.
If everything goes well you should see myFile.xlsx having Sheet1 and the response of your Web Service as the very first cell value. Feel free to amend this code as required according to your use case.
References:
Busy Developers' Guide to HSSF and XSSF Features
How to Implement Data Driven Testing in your JMeter Test

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.

Transferring my dynamic value from response data to excel file in Jmeter

I want to actually transfer my dynamic value from the response data to Excel file in Jmeter... can anyone plz let me know the clear process for it ?
I used beanshell post processor but dint got the expected output...
Take a look at Apache POI - Java API To Access Microsoft Excel Format Files, this way you will be able to create, read and update Excel files from Beanshell code. The easiest way to add binary documents formats support to JMeter is using Apache Tika, given you have tika-app.jar in JMeter Classpath you will be able to view Excel files contents using View Results Tree listener and use Apache POI API to manipulate Excel files.
Minimal working code for creating an Excel file and adding to it JMeter variable value looks like:
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(vars.get("your_variable"));
FileOutputStream fileOut = new FileOutputStream("FileCreatedByJMeter.xlsx");
wb.write(fileOut);
fileOut.close();
References:
Busy Developers' Guide to HSSF and XSSF Features
How to Extract Data From Files With JMeter

Resources