简体   繁体   中英

Scala - how to use variables in a multi-line string literal

I want to call value of ' myActionID ' variable. How do I do that? If i pass static value like "actionId":1368201 to myActionID then it works, but If I use "actionId" : ${actionIdd} it gives error.

Here's the relevant code:

class LaunchWorkflow_Act extends Simulation {

    val scenarioRepeatCount = 1
    val userCount = 1
    val myActionID = "13682002351"
    
    val scn = scenario("LaunchMyFile")
        .repeat (scenarioRepeatCount) {
            exec(session => session.set("counter", (globalVar.getAndIncrement+" "+timeStamp.toString())))
            .exec(http("LaunchRequest")
            .post("""/api/test""")
            .headers(headers_0)
            .body(StringBody(
                """{    "actionId": ${myActionID} ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
                }""")))

            .pause(pause) 

        }
    }

setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)

Everything works fine If I put value 13682002351 instead of myActionID. While executing this script in Gatling I am Getting this error

ERROR ighttp.action.HttpRequestAction - 'httpRequest-3' failed to execute: No attribute named 'myActionID' is defined

Scala has various mechanisms for String Interpolation (see docs ), which can be used to embed variables in strings. All of them can be used in conjunction with the triple quotes """ used to create multi-line strings.

In this case, you can use:

val counter = 12
val myActionID = "13682002351"
val str = s"""{    
                "actionId": $myActionID ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
              }"""

Notice the s prepended to the string literal, and the dollar sign prepended to the variable names.

Using S interpolated String we can do this easily:

 s"""Hello Word , Welcome Back!
      How are you doing ${userName}"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM