Variable Path Param for REST service testing in Jmeter - java

I'm testing RESt service which has path parameter.
/my-service/v1/Customer/order/{ordernumber}
I want to increment the number by 1 for each request. How to achieve this in Jmeter? Till now i had been passing a fixed path param, therefor our test result were on only one input parameter.
/my-service/v1/Customer/order/5247710017785924

The good point to start with is putting your initial order value into User Defined Variable
Given start order as "5247710017785924" you need to create an "ordernumber" variable and set it's value to 5247710017785924.
After each request you can increment variable value by adding BeanShell postprocessor to your HTTP Sampler with following code:
long ordernumber = Long.parseLong(vars.get("ordernumber"));
ordernumber++;
vars.put("ordernumber",String.valueOf(ordernumber));
And set ordernumber in your HTTP Sampler path as
/my-service/v1/Customer/order/${ordernumber}

None of the solutions worked for me. Here is what I did
Define HTTP request as shown below and add path /api/v2/state/find/${id} to the request
Right click on HTTP request --> Preprocessor -> User Parameters ->Add variable -> input id and it's value
Start HTTP request, this should work

Use JMeter Counter component to increment variable.

This question is path parameter related, where the value of the order number is incremented by 1 in each successive request. But I faced a scenario where I got a list of order numbers and I had to make request for those order numbers. So, I am gonna answer this question with respect to that, this solution can be applied in both the scenarios.
What I did is put all the parameter paths in a CSV file, like this -
/my-service/v1/Customer/order/5247710017785924
/my-service/v1/Customer/order/5247710017785976
/my-service/v1/Customer/order/5247710017785984
/my-service/v1/Customer/order/5247710017785991
Then I iterated through the list of paths in the CSHTTPle and made http request to the server. To know how to iterate through the CSV file and make http request in Jmeter, you can check this link:
https://stackoverflow.com/a/47159022/5892553

You can use a JMeter Counter:
right click on your Thread Group (under the Test Plan)
select Add–>Config Element–>Counter
set the Starting value (0), Increment (1), Maximum value, Exported Variable Name ("ordernumber")
Then you can use the exported variable name as path param:
/my-service/v1/Customer/order/${ordernumber}

I used a BeanShell PreProcessor to generate an id
vars.put("id", UUID.randomUUID().toString());
Then used the path Http Request
/api/v1/event/${id}/
BINGO!!!

Related

Failed to build request: attribute named is defined

I am trying to pass my token to the required request but it does not save the variable "token".
The result is always "{token}" as you could collect the value you get in the .check (jsonPath ("$. User_id"). SaveAs ("userId"))
I have tried using ${token} but still not reused
Here you can see my code in case it helps you;
enter image description here
It either means that "getTokenRequest" failed, or that the users who perform "getNotificationClientId" don't first perform "getTokenRequest".

Spark-Java: Different Path Strings Map to Same Get Method

I am running into a problem where two distinct paths are mapping to the same resource. Please let me know why the following 2 paths are mapping to the same path:
get("/test/:idtest/:idsimple", (request, response) -> "");
get("/test/all/:idtest", (request, response) -> "");
Following two call map to the same:
curl -X GET -i http://localhost:4567/test/2/3
curl -X GET -i http://localhost:4567/test/all/5
Thanks
The reason for these two requests to be mapped to the first route is the order you defined them. Spark Java documentation mentions here that:
Routes are matched in the order they are defined. The first route that matches the request is invoked.
When you call http://localhost:4567/test/2/3 Java Spark would try to match it first with the first route you defined "/test/:idtest/:idsimple":
The variable idtest would be matched to 2
The variable idsimple would be matched to 3
When you call http://localhost:4567/test/all/5 Java Spark would try to match it first with the first route you defined again:
The variable idtest would be matched to all
The variable idsimple would be matched to 5
So both of them match and therefore mapped to this route.
If you change the order of the routes definitions, then "/test/all/:idtest" will be the first path to match against and then calling http://localhost:4567/test/all/5 would be mapped to the right route, while calling http://localhost:4567/test/2/3 would fail the first one and would be mapped to the second.

JMeter - Variable set in preprocessor is not available to sampler

I have a relatively simple JMeter test plan setup as shown here:
https://imgur.com/c8BIzBB
The relevant part of this is the BeanShell Preprocessor (shown as Setup element data) and its relationship to the HTTP Request sampler (shown as POST /elements). Both of these are inside a Loop Controller (shown as Do a few times).
The Preprocessor gets an array of data stored on the bsh.shared object and randomly selects one item. It then sets a variable called elementTypeId.
When I run this test, elementTypeId gets logged (and I therefore assume is set) correctly. However, the first time around, the variable is not set correctly and still appears as ${elementTypeId}. Further samples appear to be set but use the n-1th value.
The first, failing sample is shown here: https://imgur.com/Gj2YAje
The final sample (and logged values) are shown here: https://imgur.com/OW5HSsS
Setup element data - BeanShell Preprocessor code:
import java.util.Random;
import com.eclipsesource.json.*;
Random rand = new Random();
int idx = rand.nextInt(bsh.shared.elementTypes.size());
JsonValue elementType = bsh.shared.elementTypes.get(idx);
String elementTypeId = String.valueOf(elementType.get("id").asInt());
log.info(elementTypeId);
vars.put("elementTypeId", elementTypeId);
It looks to me as if the sampler is firing before the preprocessor has set the variable - which seems counter to what should be happening.
Update following UBIK's answer
When I disable the SetQueryParams PreProcessor, it appears that the variable is set correctly (although the request fails as it needs a query parameter to be added).
SetQueryParams PreProcessor:
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;
if (sampler instanceof HTTPSamplerBase &&
sampler.getMethod().equalsIgnoreCase("post")) {
// add query parameter to url
var customPath = sampler.getPath() + '?' + sampler.getQueryString();
sampler.setPath(customPath);
// remove query parameter from body
arguments = sampler.getArguments();
while (arguments.getArgumentCount() > 1) {
arguments.removeArgument(arguments.getArgumentCount() - 1);
}
sampler.setArguments(arguments);
}
Is it possible to have both preprocessors applied to the POST request?
I think you issue might be coming from the other PreProcessor :
SetQueryParams PreProcessor
As per scoping rules , this one runs for every HTTP Sampler.
Check in console for the exception thrown.
try resolving that
if nothing is working please copy your script, delete Beanshell preprocessor and add BeanShell again and paste your script.
This may be silly but it worked for me.

Spring Security antMatcher expression not works with path variable

I need to provide certain role for accessing a URL in the following format:
/connector/{programId}/order/{anything here}
Where programId is an integer value so I'd tried the following and it doesn't work at all.
.antMatchers('/connector/{programId:\\d+}/order/**').access("hasRole('CONNECTOR')")
But when I used ** instead of the programId part it's working well. But how can I make it work with pathVariable (which is always an integer).
You should use RegexRequestMatcher instead of AntPathRequestMatcher.
.regexMatchers("/connector/(\\d+)/order/.*").access("hasRole('CONNECTOR')")
I am using:
.regexMatchers("/connector/(\\d+)/order/.*").access("hasRole('CONNECTOR')")
But server response 405 error

Create a Java Request in jMeter for validating multiple variables

Here in My HTTP Request I extracted some variables using JSON Path Extractor. I want to create a Java Request it will validate the above variables. i.e I want to check the value of reqVar1 is equal to resVar1 or not and reqVar2 is equal to resVar2 or not like that.
You are making things over complicated, you could achieve the same using normal Response Assertion.
For example, if you have a JMeter Variable ${var1} and you need to compare it to ${var2}, ${var3} and ${var4} you can just configure the Response Assertion like:
More information on conditionally marking sampler results as successful or failed: How to Use JMeter Assertions in Three Easy Steps
Instead of Java Request sampler, you can add BeanShell Assertion to compare the values. following is the code:
if(vars.get("reqVar1").equals(vars.get("resVar1")))
{
if(vars.get("reqVar2").equals(vars.get("resVar2")))
{
SampleResult.setResponseCode("200");
SampleResult.setResponseMessage("SUCESS");
}
else{
SampleResult.setResponseCode("403"); // keep error code as per your wish
SampleResult.setResponseMessage("reqVar2 and reqVar2 are NOT same" + vars.get("reqVar2") + vars.get("resVar2"));
}
}
else{
SampleResult.setResponseCode("403"); // keep error code as per your wish
SampleResult.setResponseMessage("reqVar1 and reqVar1 are NOT same" + vars.get("reqVar1") + vars.get("resVar1"));
}
Add the BeanShell Assertion as a child element to the HTTP Sampler in which you are getting the values for reqVar1, reqVar2, resVar1, resVar2
Once the decision is taken based on If condition, you can change the response code and message using SampleResult
Check the following reference that shows all methods available to you:
https://jmeter.apache.org/api/org/apache/jmeter/samplers/SampleResult.html
Image reference:

Categories