Reputation: 89
I was using jmeter to load test services I need to use one of the response headers parameter value as input of next request. For this I am using JSR223 Sampler and write Grrovy Script to read parameters. I have used
**def headerList = prev.getResponseHeaders()
headerList.each(){
headersList.each{
log.info it;
if(it.equals("transactionRef"){
log.info"Required Header: "it
requiredHeader=it;
}**
The above code is not working also it is traversing character by character. Could someone help on this.
}
Upvotes: 1
Views: 2490
Reputation: 682
Below are steps to add JSR223-based response header assertion:
JSR223 Assertion
on your samplerimport java.util.HashMap;
def sanitizeResponseHaders() {
def headers = new HashMap<String, String>();
if(SampleResult.getHeadersSize() > 0) {
def headersData = SampleResult.getResponseHeaders().split("\n");
for(headerData: headersData) {
if(headerData.contains(":")) {
def header = headerData.split(":");
headers.put(header[0].toLowerCase().trim(), header[1].toLowerCase().trim());
}
}
}
return headers;
}
def assertHeader(headers, header, value) {
if(!headers.get(header).equals(value)) {
def msg = "Header assertion failed: " + header + " is not as expected " + value + " and actual value is " + headers.get(header);
SampleResult.setSuccessful(false);
SampleResult.setResponseMessage(msg);
AssertionResult.setFailure(true);
AssertionResult.setFailureMessage(msg);
addLog(msg);
}
}
def addLog(msg) {
log.info(msg);
}
def logHeaders(headers) {
for(entry: headers.entrySet()) {
addLog("header name: " + entry.getKey() + ", value: " + entry.getValue());
}
}
addLog("=========== Header assertion started ===============");
def headers = sanitizeResponseHaders();
//Add your own header assertion here
assertHeader(headers, "x-frame-options", "sameorigin");
logHeaders(headers);
addLog("============ Header assertion completed =============");
Add your own header assertion here
line, add your own assertion. To do that, just call assertHeader(headers, "your_own_header", "your_own_header_value");
method for each assertion.Upvotes: 0
Reputation: 168002
As per the JavaDoc SampleResult.getResponseHeaders() function returns response headers as a single String so if you want to get individual headers you need to split it by line separators first and then by colon to get name/value pairs.
Example code:
def headers = prev.getResponseHeaders().split('\n').inject([:]) { out, header ->
if (header.contains(':')) {
header.split(':').with {
out[it[0].trim()] = it[1].trim()
}
}
out
}
headers.each { header ->
if (header.getKey() == 'transactionRef') {
log.info('Required header value: ' + header.getValue())
}
}
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
P.S. Woudln't it be easier to go for Regular Expression Extractor? The relevant configuration would be something like:
Upvotes: 2