Writing web service response to excel - jmeter

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

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

Using custom amount in Jmeter WebDriver Sampler in graph metrics

I'm using Jmeter to get daily results of website performance, specifically, the render time (which I calculate using the sum domComplete - domLoading).
I end up with the result as a new var, but I don't know how to take that amount and transfer it to a Jmeter graph to display the results. My code is below:
WDS.sampleResult.sampleStart();
WDS.browser.get('http://www.vivastreet.co.uk/');
var completeTime = WDS.browser.executeScript('return window.performance.timing.domComplete;');
var loadingTime = WDS.browser.executeScript('return window.performance.timing.domLoading;');
var renderTime = completeTime - loadingTime;
WDS.log.info("Render time = " + renderTime);
WDS.sampleResult.sampleEnd();
The functionality is available only in JMeter 5.0, if you're on a previous version - you will have to upgrade, moreover it is highly recommended as per JMeter Best Practices
Store the result variable into JMeter Variables using WDS.vars shorthand. Add the following line before WDS.sampleResult.sampleEnd()
WDS.vars.put('renderTime', renderTime.toString())
Store the values into .jtl results file using Sample Variables property and configure JMeter HTML Reporting Dashboard to plot the custom value Add the following lines to user.properties file:
sample_variables=renderTime
jmeter.reportgenerator.graph.custom_testGraph.classname=org.apache.jmeter.report.processor.graph.impl.CustomGraphConsumer
jmeter.reportgenerator.graph.custom_testGraph.title=Rendering Time
jmeter.reportgenerator.graph.custom_testGraph.property.set_Y_Axis=Page Rendering time
jmeter.reportgenerator.graph.custom_testGraph.set_X_Axis=Over Time
jmeter.reportgenerator.graph.custom_testGraph.property.set_granularity=60000
jmeter.reportgenerator.graph.custom_testGraph.property.set_Sample_Variable_Name=renderTime
jmeter.reportgenerator.graph.custom_testGraph.property.set_Content_Message=Rendering Time :
Restart JMeter to pick the properties up

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

How can I navigate the JMeter test element tree from within a sampler script

From a JSR223 Sampler, I can get access to the current test element using the sampler variable.
From there, how can I navigate the tree of TestElement objects? For example, how can I get access to the parent test element (and then it’s parent, etc) or how can I get access to the TestPlan test element?
Background:
I want to dynamically create a JDBC Connection Configuration element from a JSR223 Sampler using Groovy.
From other questions (e.g., here) and web searches (e.g., here), I know how to create test plan elements from the top down (e.g., how to create a test plan and build the tree down from there). So I know how to do the new DataSourceElement() which is a TestElement but I don’t know how to add that new element to the test plan. In the sampler script I have access to the sampler (Sampler) and the ctx (JMeterContext) variables but I don’t know how to navigate the test element tree.
I tried just using sampler.addTestElement but a config element isn’t really valid under a sampler element. Still, I did try but the config element was not found when I tried to use it in a JDBC Request (error: "No pool found named: 'myDatabaseThreadPool', ensure Variable Name matches Variable Name of JDBC Connection Configuration").
I’m hoping that if I can get the TestPlan element and add the config element to that, then it would work.
FWIW, my test plan looks like this:
Test Plan
Thread Group 1 (could be a setup thread group)
JSR223 Sampler (this is where I want to create the dynamic config)
Thread Group 2 (multiple threads)
JDBC Request (uses the pool variable name specified in the dynamic config)
View Results Tree
I can go into further detail about why I want to dynamically create the JDBC Connection Configuration, but if there’s an easy answer about how to navigate the test element tree from inside my sampler script I’d like to know that anyway.
As you have mentioned you have access to JMeterContext via ctx shorthand. Hence you have access to StandardJMeterEngine class instance via ctx.getEngine(); method.
Looking into StandardJMeterEngine source you can see that test plan is being stored as HashTree structure:
private HashTree test;
So the choices are in:
change access modifier to public and recompile JMeter from sources
use Trail - Java Reflection API in order to access test value
Reference code:
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.SearchByClass;
import java.lang.reflect.Field;
import java.util.Collection;
StandardJMeterEngine engine = ctx.getEngine();
Field test = engine.getClass().getDeclaredField("test");
test.setAccessible(true);
HashTree testPlanTree = (HashTree) test.get(engine);
SearchByClass testPlans = new SearchByClass(TestPlan.class);
testPlanTree.traverse(testPlans);
Collection testPlansRes = testPlans.getSearchResults();
TestPlan testPlan = (TestPlan)testPlansRes.toArray()[0];
//do what you need with "testPlanTree" and/or "testPlan"
Check out How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information using JMeter and Java API from scripting test elements.

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