Jmeter- Log values to CSV file - jmeter

I have used below code to log values to CSV. With this code I am not able to get header names, it directly logging values to firstname, lastname without header. I am expecting the output file with header and values. For example: Can some please let me know whats missing
firstname lastname
Test Jmeter
firstNameoutput = vars.get(“firstName”)
lastNameoutput = vars.get(“lastName”)
resultPath = vars.get(“resultsheetFilePath”)
FileOutputStream file= new FileOutputStream(resultPath, true);
PrintStream printOutputData = new PrintStream(file);
this.interpreter.setOut(printOutputData);
Var responseCode=prev.getResponseCode();
If (responseCode.equals(“200”){
print(“PASS”+”+firstName+”,”+lastName);
}

Just write firstname and lastname as the first line of the CSV file somewhere in setUp Thread Group.
As since JMeter 3.1 Groovy is the recommended scripting option add a JSR223 Sampler to the setUp Thread group and put the following code there:
new File(vars.get('resultsheetFilePath')).text = 'firstname,lastname' + System.getProperty('line.separator')
This will create the file with the header at the beginning of the test and you can write the values later.

Related

How to store values from a while loop to a list as a property in JMeter

Is there a way to add each session Id that is retrieved from a Loop Controller to a list and assign it to a property for use in the following thread group? Below I used a couple of Dummy Sampler to explain my requirement.
I had 3 users stored in a list to retrieve 3 session ids in the setUp Thread Group.
JSR223 PreProcessor
List usernames = Arrays.asList('Peter', 'Alex', 'Mary');
props.put('accounts', usernames);
I was able to read a username from this property to get a session id in the response accordingly per iteration in the Loop Controller.
"sessionId": "this_is_my_session_id-${__groovy(props.get('accounts').get(${__jm__LoopController__idx} % 3),)}-${__jm__LoopController__idx} "
I parsed the 3 session ids out by a JSR223 PostProcessor
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper();
def response = jsonSlurper.parseText(prev.getResponseDataAsString());
def json = JsonOutput.toJson(response.sessionId)
def sessionId = new JsonSlurper().parseText(json)
log.info('The session id is:' + sessionId)
ArrayList<String> sessionIds = new ArrayList<String>();
props.put("sessionIds", sessionIds.add(sessionId))
I needed to add these 3 session ids to a list and assign it to a property so that I can use one session id inside the property per VU/thread in the following Thread Group. But it didn't work as expected. It threw error saying No such property: sessionIds
${__groovy(props.get(sessionIds).get(${__jm__UseSession__idx} % 3),)}
We don't know what do you "expect"
Most probably the problem is here:
props.put("sessionIds", sessionIds.add(sessionId))
Collection.add() function returns a boolean value so it puts true to the sessionIds property instead of the real value of the ArrayList.
So I believe you need to change it to something like:
sessionIds.add(sessionId)
props.put("sessionIds", sessionIds)
if you're going to run the JSR223 Test Element in the loop you can also reconsider the way you're initializing the sessionIds and implement the following logic:
If sessionIds property exists - read its value
If it doesn't exist - create a new ArrayList
Something like:
ArrayList<String> sessionIds = props.get("sessionIds") ?: new ArrayList<String>()
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?

Unable to access UDV variable

in below script i am trying to access user defined variable and modify the data and passing the value to post data using the variable "data".But after modifying the data it is not being sent to http request.
String temp = vars.get("${json}"); //access UDV data
temp = temp.replaceAll("__"," ");
vars.put("data",temp); //pass the data to another udv "data"
Please let me know whether there is any mistake in my above script
If you have an User Defined Variable called json which is created like:
then you need to change your code like:
String temp = vars.get("json")
or alternatively use "Parameters" section of the JSR223 Test Element:
you are accessing the variable incorrectly
String temp = vars.get("${json}"); //access UDV data is wrong
String temp = vars.get("json"); //access UDV data
refer here for more details

Random numbers in java generated JMeter testplan

I programmaticaly generate my jmeter test plans in java code.
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(loopController);
HashTree threadGroupHashTree;
String employeeId = "1";
HTTPSamplerProxy hs = HttpSampler.createHttpSampler(data, "http://test.de/employee/" + employeeId, "GET", "");
threadGroupHashTree.add(hs);
Then I start this testplan:
StandardJMeterEngine jmeter = setupJMeter(threadGroupHashTree);
jmeter.configure(threadGroupHashTree);
jmeter.run();
It's works. Now I need to send requests with different employeeId (random). In JMeter GUI we can use random functions for randomize our tests.
Provides JMeter API such functionality? How can we randomize our requests? Or we must replace LoopController with for loops?
You can use JMeter's __Random() function normally like:
String employeeId = "${__Random(1,999,)}"
Just make sure to have ApacheJMeter_functions JAR in your project classpath
You can use RandomUtils class like
String employeeId = String.valueOf(org.apache.commons.lang3.RandomUtils.nextInt(1,1000));
You can use ThreadLocalRandom class like
String employeeId = String.valueOf(java.util.concurrent.ThreadLocalRandom.current().nextInt(1,1000));
Any of the approaches will return a random number each time it will be called.
See Five Ways To Launch a JMeter Test without Using the JMeter GUI article and jmeter-from-code example project to learn more about creating JMeter tests programmatically.

Passing values to parameters in Jmeter

Suppose I have a variable in the RequestParameter as StudentList list where StudentList is a class as follows:
class StudentList
{
List<Students> stud=new ArrayList<Students>();
}
and Students is a class having fields firstName,lastName etc.How to pass values to the list variable in Jmeter as a request parameter?
You can pass values to the list variable in Jmeter via CSV Data Set Config. Where you have to create first .CSV file with values and set the parameters in the HTTP request. Below are shared steps with screenshots of results.
Create an HTTP request under the Thread group and change the name to "Student"
Select CSV Data Set Config from Config Element under the same Thread Group
Create .CSV file with values related firstname and lastname and set the loop count in the Thread Group as 3 as there are 3 records available in CSV file
CSV File
Set Path in CSV Data Set Config under Filename and Set the variable name as
"firstname,lastname"
CSV Dat Set Config
Set the parameter in value with the $ sign as per the attached screenshot.
Request Parameter
Select View Result Tree from Listener under the same Thread Group
Save the Test plan and Run or Start.
Under the view result tree, when clicking on each request you will find firstname and last name under each request parameter.
Student 1
Student 2
Student 3

How can I extract values from a custom flat file header into variables?

I have been stuck for a while with this problem and I have no clue. I am trying to upload multiple CSV files which has dates but I wanted the dates stored as date variables so I use the date variables to form part of the column in a table using script componet and I have no idea how to create the dates as date variables in SSIS.
CSV files look as shown below when opened in Excel.
CSV data 1:
Relative Date: 02/01/2013
Run Date: 15/01/2013
Organisation,AreaCode,ACount
Chadwell,RM6,50
Primrose,RM6,60
CSV data 2:
Relative Date: 14/02/2013
Run Date: 17/02/2013
Organisation,AreaCode,ACount
Second Ave,E12,110
Fourth Avenue, E12,130
I want the Relative Date and Run Date stored as date variables. I hope I made sense.
Your best solution would be to use a Script Task in your control flow. With this you would pre-process your CSV files - you can easily parse the first two rows, retrieving your wanted dates and storing them into two variables created beforehand. (http://msdn.microsoft.com/en-us/library/ms135941.aspx)
Important to make sure when passing the variables into the script task you set them as ReadWriteVariables. Use these variables in any way you desire afterwards.
Updated Quick Walkthrough:
I presume that the CSV files you will want to import will be located in the same directory:
Add a Foreach Loop Container which will loop through the files in your specified directory and inside, a Script Task which will be responsible for parsing the two dates in each of your files and a Data Flow Task which you will use for your file import.
Create the variables you will be using - one for the FileName/Path, two for the two dates you want to retrieve. These you won't fill in as it will be done automatically in your process.
Set-up your Foreach Loop Container:
Select a Foreach File Enumerator
Select a directory folder that will contain your files. (Even better, add a variable that will take in a path you specify. This can then be read into the enumerator using its expression builder)
Wildcard for the files that will be searched in that directory.
You also need to map each filename the enumerator generates to the variable you created earlier.
Open up your Script Task, add the three variables to the ReadWriteVariables section. This is important, otherwise you won't be able to write to your variables.
This is the script I used for the purpose. Not necessarily the best, works for this example.
public void Main()
{
string filePath = this.Dts.Variables["User::FileName"].Value.ToString();
using (StreamReader reader = new System.IO.StreamReader(filePath))
{
string line = "";
bool getNext = true;
while (getNext && (line = reader.ReadLine()) != null)
{
if(line.Contains("Relative Date"))
{
string date = getDate(line);
this.Dts.Variables["User::RelativeDate"].Value = date;
// Test Event Information
bool fireAgain = false;
this.Dts.Events.FireInformation(1, "Rel Date", date,
"", 0, ref fireAgain);
}
else if (line.Contains("Run Date"))
{
string date = getDate(line);
this.Dts.Variables["User::RunDate"].Value = date;
// Test Event Information
bool fireAgain = false;
this.Dts.Events.FireInformation(1, "Run Date", date,
"", 0, ref fireAgain);
break;
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
private string getDate(string line)
{
Regex r = new Regex(#"\d{2}/\d{2}/\d{4}");
MatchCollection matches = r.Matches(line);
return matches[matches.Count - 1].Value;
}
The results from the execution of the Script Task for the two CSV files. The dates can now be used in any way you fancy in your Data Flow Task. Make sure you skip the first rows you don't need to import in your Source configuration.

Resources