首页 > 解决方案 > 仅在检查成功时才调用函数?

问题描述

仅当响应返回字符串“成功”时,我才想将会话属性写入文件。

我正在尝试这样做:

.check(substring("success").onSuccess(writeThisToFile(<my variable here>))

我看到这不像 IDE 所说的那样有效。有没有办法根据响应检查的结果调用函数?

标签: gatlingscala-gatling

解决方案


为此,您可以使用方法.transform()on bodyString。它采用类型的函数参数String => T(String, Session) => T并将其应用于响应主体,因此在您的情况下,它看起来像:

.check(
    bodyString.transform(
        (body: String, session: Session) => {
            if(body.contains("success")){
                File("/path/to/file")
                    .createFile()
                    .appendAll(session("attributeName").as[String])
            }
        }
    )
)

-- 已编辑 --

因此,要将请求正文的一部分保存到会话中,您需要做的是单独生成该部分,保存到会话属性中并在创建正文时使用。例如,假设您要发送包含 2 个字段的 JSON:某个常量值 + 当前时间戳,然后如果响应包含“成功”,则将时间戳保存到文件中:

val exampleScenario =  scenario("Example")
    .exec(session => {
        session.set("timestamp", System.currentTimeMillis)
    })
    .exec(http("Send data")
        .post("http://example.com")
        .body(StringBody("""{"constant":123, "timestamp": ${timestamp}}"""))
        .asJSON
        .check(
            bodyString.transform(
                (body: String, session: Session) => {
                    if(body.contains("success")){
                        File("/path/to/file")
                            .createFile()
                            .appendAll(session("timestamp").as[String])
                    }
                }
            )
        )
    )

推荐阅读