2017-02-08 6 views
0
val tName = System.getProperty("tName", "asdflkjh") 

Я планирую сделать "tName" динамичным, но он печатает "$tName" на выходе вместо «asdflkjh». .body(StringBody("""{"objectId":${assetid},"objectType":"m-asset","name1": "$tName","accountId":4,"userId":5}"""))типа показана при прохождении «TName» в stringbody

Если я использую 'session=>s' в stringBody он бросает под ошибкой .body(StringBody(session=>s"""{"objectId":${assetid},"objectType":"m-asset","name1": "$tName","accountId":4,"userId":5}"""))

////////////////////// ОШИБКА: ///// ///////////////////////////

3894 [main] ERROR io.gatling.compiler.ZincCompiler$ - type mismatch; 
found : String("${ThumbIdList}") 
required: ?{def apply: ?} 
Note that implicit conversions are not applicable because they are ambiguous: 
both method augmentString in object Predef of type (x: String)scala.collection.immutable.StringOps 
and method stringToExpression in object Predef of type [T](string: String)(implicit evidence$1: scala.reflect.ClassTag[T])io.gatling.core.session.Expression[T] 
are possible conversion functions from String("${ThumbIdList}") to ?{def apply: ?} 
3894 [main] ERROR io.gatling.compiler.ZincCompiler$ -  .foreach("${ThumbIdList}", "thumbid") { 
3894 [main] ERROR io.gatling.compiler.ZincCompiler$ -    ^
3914 [main] ERROR io.gatling.compiler.ZincCompiler$ - D:\myTags.scala:110: type mismatch; 
found : String("thumbid") 
required: ?{def apply: ?} 
Note that implicit conversions are not applicable because they are ambiguous: 
both method augmentString in object Predef of type (x: String)scala.collection.immutable.StringOps 
and method stringToExpression in object Predef of type [T](string: String)(implicit evidence$1: scala.reflect.ClassTag[T])io.gatling.core.session.Expression[T] 
are possible conversion functions from String("thumbid") to ?{def apply: ?} 
3914 [main] ERROR io.gatling.compiler.ZincCompiler$ -  .foreach("${ThumbIdList}", "thumbid") { 
3924 [main] ERROR io.gatling.compiler.ZincCompiler$ -        ^
4004 [main] ERROR io.gatling.compiler.ZincCompiler$ - D:\myTags.scala:98: not found: value assetid 
4004 [main] ERROR io.gatling.compiler.ZincCompiler$ -   .body(StringBody(session=>s"""{"objectId":${assetid},"objectType":"m-asset","name1": "$tName","accountId":4,"userId":5}""")) 
4004 [main] ERROR io.gatling.compiler.ZincCompiler$ -              ^
4054 [main] ERROR io.gatling.compiler.ZincCompiler$ - three errors found 
4054 [main] DEBUG io.gatling.compiler.ZincCompiler$ - Compilation failed (CompilerInterface) 

///////////// Script Начинается здесь ///////////

import scala.concurrent.duration._ 
import io.gatling.core.Predef._ 
import io.gatling.http.Predef._ 
import io.gatling.jdbc.Predef._ 

class myTags extends Simulation { 

    val testServerUrl = System.getProperty("testServerUrl", "https:someurl") 
    val username = System.getProperty("username", "ma") 
    val password = System.getProperty("password", "ma") 
    val userCount = Integer.getInteger("userCount", 1).toInt 
    val accountname = System.getProperty("accountname", "ma1") 
    val tName = System.getProperty("tName", "asdflkjh") 

    val httpProtocol = http 
     .baseURL(testServerUrl) 

    val headers_6 = Map(
     "Accept" -> "application/json, text/plain, */*", 
     "Cache-Control" -> "no-cache", 
     "If-Modified-Since" -> "Mon, 26 Jul 1997 05:00:00 GMT", 
     "Pragma" -> "no-cache", 
     "X-Requested-With" -> "XMLHttpRequest") 

    val headers_52 = Map(
     "Accept" -> "application/json, text/plain, */*", 
     "Accept-Encoding" -> "gzip, deflate, br", 
     "Cache-Control" -> "no-cache", 
     "Origin" -> testServerUrl, 
     "Pragma" -> "no-cache", 
     "X-Requested-With" -> "XMLHttpRequest", 
     "Content-Type" -> "application/json;charset=UTF-8", 
     "Connection" -> "keep-alive", 
     "User-Agent" -> "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36") 

    val scn = scenario("Add") 
     .exec(http("Fetch") 
      .get("/someurl2") 
      .headers(headers_6) 
      .check(jsonPath("$.resources[*].ids").findAll.saveAs("IdList")) 
      .check(jsonPath("$.resources[*].thumbIds").findAll.saveAs("ThumbIdList"))) 

     .foreach("${IdList}", "assetid") { 
      exec(http("Load_Details") 
      .get("/mmm/images/loader.svg") 
      .resources(
      http("C1_request") 
      .get("/mmm/ast/${assetid}/c1") 
      .headers(headers_6), 
      http("T1_request") 
      .get("/mmm/ast/${assetid}/t1") 
      .headers(headers_6), 
      http("A1_request") 
      .post("/mmm/actions") 
      .headers(headers_52) 
      .body(StringBody("""{"objects":[{"id":${assetid},"resource":"m-asset"}]}""")), 
      http("R1_request") 
      .get("/mmm/variants%3BresourceType=m-asset") 
      .headers(headers_6), 
      http("S1_request") 
      .get("/mmm/ast/${assetid}/keyframes") 
      .headers(headers_6))) 

     .exec(http("Add Tags") 
      .post("/mmm/objs/${assetid}/tags") 
      .headers(headers_52) 

      // The PROBLEM IS Here. I want to pass "$tName" dynamically 
      .body(StringBody("""{"objectId":${assetid},"objectType":"m-asset","name1": "$tName","accountId":4,"userId":5}""")) 
      ) 
     } 

     .foreach("${ThumbIdList}", "thumbid") { 
      doIf(session => session("thumbid").as[String] != "-1") 
      { 
       exec(http("Set_Keyframes") 
       .get("/mmm/keyframes/${thumbid};width=185;height=103") 
       ) 
      } 
     } 

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

ответ

1

ошибка просто, что у вас уже есть в строке с $, поэтому при переключении строки интерполяции (s"""...""") это неверно. Используйте $$, чтобы избежать этого: s"""{"objectId":$${assetid},"objectType":"m-asset","name1": "$tName","accountId":4,"userId":5}""". Обратите внимание, что часть session => ... полностью ортогональна интерполяции строк.

Замечу, что это небезопасно: что делать, если tName содержит котировки? В этом случае это может быть неважно, предполагая, что вы собираетесь запускать скрипт на компьютерах, где вы управляете переменными среды, но смотрите «SQL-инъекцию» и знайте, что проблема не ограничивается SQL.

+0

Спасибо, Алексей Романов. Это сработало. Благодаря :-) – Peter

0

Вы пытаетесь получить значение переменной среды? Если да, попробуйте это один:

val tName = sys.env("tName").getOrElse(doSomething here...) 
+0

nope Я хочу получить значение tName. Над ответом Алексея Романова работала для меня. Спасибо за ответ и усилие. – Peter

Смежные вопросы