I am new to jmeter and i am stuck in a condition . I am running jmeter http sample using a csv file where i am using a pre-processor script in which doing the following-
setting http.method as per request like POST , GET , PUT ,PATCH
setting http.path as "/restpath"
setting request body.json
For Path i am using a "http.path" and passed the same in http sampler like ${http.path}. All above is working fine until i have dependent HTTP request like below use case -
Step 1 - Hit HTTP Request on path "/restpath" . After successful submission , i got a serverId in response and save the same in json extractor variable "serverID".
Step 2- Now i have to hit http request on path "/rest/${serverID}" . when i am trying to pass the same from csv file then the same is not replacing with captured variable in step 1 . Whatever i passed in csv file in http.path got passed and submit.
Expectation -
In Sheet --> http.path == "/restpath/${serverID}"
In HTTP Request submission --> "/restpath/4894rh89r"
Actual -
In Sheet --> http.path == "/restpath/${serverID}"
In HTTP Request submission --> "/restpath/${serverID}"
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
//test input parameters
def httpMethod = vars.get("http.method");
//change the http method as per the data sheet
sampler.setMethod(httpMethod);
//set the HTTP Path
//URL url = new URL(vars.get('http.path'));
//vars.put('http.path',url.getPath());
//set the HTTP request body
if(!vars.get("input.json").equals("")){
def dataToBePosted = new CompoundVariable(new File(vars.get("jmeter.test.home") + vars.get("input.json")).text).execute();
def arg= new HTTPArgument("", dataToBePosted, null, true);
arg.setAlwaysEncoded(false);
sampler.getArguments().addArgument(arg);
//HTTP Body is set to
log.info(dataToBePosted);
}
Tried couple of hit n trial using __V() functions but no luck :(
I think you need to change this line:
def dataToBePosted = new CompoundVariable(new File(vars.get("jmeter.test.home") + vars.get("input.json")).text).execute();
to this one:
def dataToBePosted = ((org.apache.jmeter.engine.util.CompoundVariable)([new File(vars.get("jmeter.test.home") + vars.get("input.json")).text])).execute()
Demo:
More information:
EvalFunction source
CompoundVariable JavaDoc
Apache Groovy - Why and How You Should Use It
Related
I had previously asked and solved the problem of dumping stats using an older version of locust, but the setup and teardown methods were removed in locust 1.0.0, and now I'm unable to get the host (base URL).
I'm looking to print out some information about requests after they've run. Following the docs at https://docs.locust.io/en/stable/extending-locust.html, I have an request_success listener inside my sequential task set - some rough sample code below:
class SearchSequentialTest(SequentialTaskSet):
#task
def search(self):
path = '/search/tomatoes'
headers = {"Content-Type": "application/json",
unique_identifier = uuid.uuid4()
data = {
"name": f"Performance-{unique_identifier}",
}
with self.client.post(
path,
data=json.dumps(data),
headers=headers,
catch_response=True,
) as response:
json_response = json.loads(response.text)
self.items = json_response['result']['payload'][0]['uuid']
print(json_response)
#events.request_success.add_listener
def my_success_handler(request_type, name, response_time, response_length, **kw):
print(f"Successfully made a request to: {self.host}/{name}")
But I cannot access the self.host - and if I remove it I only get a relative url.
How do I access the base_url inside a TaskSet's event hooks?
How do I access the base_url inside a TaskSet's event hooks?
You can do it by accessing the class variable directly in your request handler:
print(f"Successfully made a request to: {YourUser.host}/{name}")
Or you can use absolute URLs in your test (task) like this:
with self.client.post(
self.user.host + path,
...
Then you'll get the full url to your request listener.
I want to provide parameters for a GET request/ API call to the AYLIEN text analytics API. I can set the headers for the key and ID as authorization and the call itself works (my usage statistics of the API increase after running the code), but I don't know how to provide the text to analyze as a parameter.
def customScript(){
def connection = new
URL("https://api.aylien.com/api/v1/sentiment").openConnection() as
HttpURLConnection
connection.requestMethod = 'GET'
// set headers
connection.setRequestProperty('X-AYLIEN-TextAPI-Application-Key','//mykey')
connection.setRequestProperty('X-AYLIEN-TextAPI-Application-ID', '//myid')
// get the response code - automatically sends the request
println connection.responseCode + ": " + connection.inputStream.text
}
In a GET request, the parameters are sent as part of the URL.
For example, if you want to add the parameter id=23, you can change the code to:
def connection = new
URL("https://api.aylien.com/api/v1/sentiment?id=23").openConnection() as
HttpURLConnection
I am writing a groovy script to execute/automate my test suite. In one test case i have a HTTPRequest where i have a request URL, parameters( username and password) and method( GET) to get a token-id and then i would pass that token id to my next step( a SOAP request)to get the data.
I am stuck at a point where i need to pass the params(username and password), request URL and method(GET) using groovy.
I have a test step created manaully under a test case, i just need to pass the params
as i search online i got to know how to pass headers,url to a SOAP request which is like below
def headers = new StringToStringMap()
testRunner = new com.eviware............WsdlTestCaseRunner(myTestCase,null);
testStepContext = new com.eviware.soapui........WsdlTestRunContext(testsetp);
headers.put("apikey", "abcd")
teststep.getTestRequest().setRequestHeaders(headers)
teststep.getHttpRequest().setEndpoint(encpointurl);
testsetp.run(testRunner ,testStepContext )
but i looking to know how to pass params to a http request(test step) and run it.
Add a Properties teststep to your testcase. Just let it keep the default "Properties" name.
Add the properties to the Properties teststep, that you need to transfer
Inside your groovy teststep, you may set the properties using something like:
def properties = testRunner.testCase.getTestStepByName("Properties");
properties.setPropertyValue("name", "value");
Add the parameters directly in your request using variables in the format ${Properties#name} and replace "name" with the actual parameter name. This can be done both in the request body and in the URL if you should wish to do so.
It can be done completely in groovy by using groovy.json.JsonBuilder Class.
def body = new StringToStringMap()
def jsonbildr = new JsonBuilder()
body.put("username","Hackme")
body.put("password","LockUout")
def root = jsonbildr body
jsonbildr = jsonbildr.toPrettyString()
log.info(jsonbildr)
testStep.setPropertyValue("Request", jsonbildr)
Output :
{
"password": "LockUout",
"username": "Hackme"
}
I am writing my first Groovy script, where I am calling a REST API.
I have the following call:
def client = new RESTClient( 'http://myServer:9000/api/resources/?format=json' )
That returns:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
I am trying to get the field level, like this:
def level_value = client.get( path : 'msr/data/level' )
However, when I print the value of the variable obtained:
println level_value.getData()
I get the whole JSON object instead of the field:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
So, what am I doing wrong?
Haven't looked at the docs for RESTClient but like Tim notes you seem to have a bit of a confusion around the rest client instance vs the respons object vs the json data. Something along the lines of:
def client = new RESTClient('http://myServer:9000/api/resources/?format=json')
def response = client.get(path: 'msr/data/level')
def level = response.data[0].msr[0].data.level
might get you your value. The main point here is that client is an instance of RESTClient, response is a response object representing the http response from the server, and response.data contains the parsed json payload in the response.
You would need to experiment with the expression on the last line to pull out the 'level' value.
I have two REST request which I am trying to run in SOAP UI. I want to feed response from one REST request to the other REST request. I am using property transfer for this. I first want to modify a Value in Response from 1st request and then feed it . I am trying this
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// request
def request = '''{"data":{
"supplementaryMessages" : [ ],
"requisitionHeaders" : [ {
"dataOperation" : "UPDATE"
} ]
}}'''
// parse the request
def jsonReq = new JsonSlurper().parseText(request);
// get the response where you've the values you want to get
// using the name of your test step
responseContent = testRunner.testCase.getTestStepByName("Fetch1").getPropertyValue("response")
// parse response
def jsonResp = new JsonSlurper().parseText(responseContent)
// get the values from your first test response
// and set it in the request of the second test
jsonResp.data.requisitionHeaders.dataOperation = jsonReq.data.requisitionHeaders.dataOperation
When I run this I am getting the Type Mismatch error .It could be very simple issue but I am new to Groovy .