Unable to access UDV variable - jmeter

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

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?

Populate a variable in controller with single row data from a query

I have in a Codeigniter 4 controller this code:
$competicion =$db->table('competiciones')
->select('*')
->where('competiciones.slug', $blog_slug)
->get()->getRowArray();
How can I get and save in a variable id_competicion value, for example? I try this code but it is wrong:
$competicionid = $competicion->[competicion_id];
getRowArray() returns an array, the correct approach to retrieve an array value would be:
$competicionid = $competicion['competicion_id'];
another possibility would be to use getRow(), which returns an object. To retrieve an object value you could use:
$competicionid = $competicion->competicion_id;
read more: Generating Query Results: Result Rows

Using Jmeter how extracted values can be inserted to different columns of a database table

Using JMeter-Bean shell sampler, I have extracted and split(with ',' delimiter) dynamic string. Currently I got stuck how this split values can be inserted to different columns of a database table.
Here is the code snippet which prints all the values after split. After splitting the string, each value will store into an array. You can retrieve by specifying the array position.
You can use the variable name e.g. aftersplit[0], aftersplit[1], and so on in the insert query.
String mystring = "here is my, dynamic, random, and unique string";
String[] aftersplit = mystring.split(",");
System.out.println(aftersplit[0]);
System.out.println(aftersplit[1]);
System.out.println(aftersplit[2]);
//To print all the values after splitting
for (int i=0; i < aftersplit.length; i++){
System.out.println(aftersplit[i]);
}
I would recommend the following approach: store your dynamic values into JMeter Variables having number postfix, example code:
String source = "foo,bar,baz";
int counter = 1;
for (String token : source.split(",")) {
vars.put("token_" + counter, token);
counter++;
}
It produces the following JMeter Variables:
token_1=foo
token_2=bar
token_3=baz
Then add ForEach Controller to iterate the generated variables and JDBC Request sampler as a child of the ForEach Controller to insert them into the database. See The Real Secret to Building a Database Test Plan With JMeter to learn how to establish database connection and execute arbitrary SQL queries using JMeter

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

Updating an Entity Without Saving the Data back to the Database

I have created a new query like the following
var pressData = from press in dataContext.Releases
select new
{
Heading = press.Heading,
Description = press.Desc,
DatePublished = press.PublishDate.ToString(),
Body = press.BodyContent,
ID=press.ReleaseID,
CreatedBy=press.CreatedBy
};
Later in the code I want to update the entity from a session variable, but not save any data back to the database. Here is the code I am trying to accomplish this with....
var edit = pressData.Where(a => a.Heading == sectionPreview.HeadingContent && a.ID == sectionPreview.tionID).FirstOrDefault();
if (edit != null)
{
//WONT LET ME UPDATE THE Body VALUE
edit.Body = sectionPreview.SectionContent;
}
The code aboves purpose is to look at pressData and replace the body content with the new body from a session variable(not shown here), but NOT save it to the db. I want pressData to be filtered and updated only in the entity. So when I bind it to the control in this case it binds the data stored in my session.
this.rptSections.DataSource = pressData;
this.rptSections.DataBind();
I am getting a complier error stating
Property or indexer 'AnonymousType#1.Body' cannot be assigned to -- it is read only.
I checked the entity model and nothing is read only not any fields not anything. I must be missing something?
Anonymous Types encapsulate a read only property collection - for more information, read here. The compiler rewrites anonymous types as a constructor injections, ie:
select new
{
Heading = press.Heading,
Description = press.Desc,
DatePublished = press.PublishDate.ToString(),
Body = press.BodyContent,
ID=press.ReleaseID,
CreatedBy=press.CreatedBy
};
Is really rewritten as:
new Anonymous`1(press.Heading, press.Desc, press.PublishDate.ToString(), press.BodyContent, press.ReleaseID, press.CreatedBy)
And the properties are read only (public get, private / protected set, to use an easy comparison). If you want to solve your issue, instead of taking the data and making an anonymous object, create a real type and set properties on it.

Resources