Jmeter Groovy读取和利用头值的脚本

guicsvcw  于 2023-08-02  发布在  其他
关注(0)|答案(2)|浏览(197)

我正在使用jmeter来加载测试服务,我需要使用一个响应头参数值作为下一个请求的输入。为此,我使用JSR223采样器并编写Grrovy脚本来读取参数。我用过

**def headerList = prev.getResponseHeaders()
headerList.each(){
headersList.each{
   log.info it;
   if(it.equals("transactionRef"){
        log.info"Required Header: "it
        requiredHeader=it;
}**

字符串
上面的代码是不工作的,它是遍历字符的字符。谁能帮帮忙。
}

oiopk7p5

oiopk7p51#

getResponseHeaders()函数将响应头作为一个String返回,所以如果你想得到单独的头,你需要先用行分隔符分割,然后用冒号分割以得到名称/值对。
示例代码:

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())
    }
}

字符串
有关JMeter中Groovy脚本的更多信息:Apache Groovy - Why and How You Should Use It
P.S.使用正则表达式提取器不是更容易吗?相关配置将类似于:
x1c 0d1x的数据

qpgpyjmq

qpgpyjmq2#

以下是添加基于JSR223的响应头Assert的步骤:
1.在采样器上添加JSR223 Assertion
1.确保语言是groovy的,因为我们将使用groovy
1.将以下脚本添加到JSR223脚本中:

import 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 =============");

字符串
1.在Add your own header assertion here行,添加您自己的Assert。为此,只需为每个Assert调用assertHeader(headers, "your_own_header", "your_own_header_value");方法。

相关问题