Gatling代码解释

Gatling的代码是基于Scala写的:

package computerdatabase

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

class BasicSimulation extends Simulation {

  val httpConf = http               //表示测试的数据格式以及被测目标等,设置压力的时候会用到
    .baseURL("http://192.168.0.11") // 因为这个,我觉得和python的httplib用法有点类似
    .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") // 数据包头,都是常见的,这里不赘述
    .doNotTrackHeader("1")
    .acceptLanguageHeader("en-US,en;q=0.5")
    .acceptEncodingHeader("gzip, deflate")//我的用例不需要gzip
    .userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0")
 
  val headers_1 = Map("Content-Type" -> "application/x-www-form-urlencoded") // 表示数据内容格式,可以定义多个,方便不同的用例请求使用,不过建议还是一个接口用例用独立一个文件来写吧
  val headers_2 = Map("Content-Type" -> "multipart/form-data; boundary=----------------------------2bb6caed7d98")
   
  val scn = scenario("Scenario Name") // 场景,有点像python的测试集或者jmeter的线程组,一个用例可以有多个场景的,相应的要对每个场景设置不同的压力
    .exec(
      http("get's example") // GET请求例子,http只是起到一个声明(命名)的作用
      .get("/api/heartbeat.json?mid=2096d4f158cb4d41a56592c816365786&ver=1.0")
      )
      //.pause(7) // Note that Gatling has recorded real time pauses,暂时没有试用
    
    .exec(
      http("post's example") // POST请求例子
      .post("/api/getconf.json?mid=ebcd32d5f68e404db1ccc8ff2dacb360&ver=1.0")
      .headers(headers_1)
      .body(StringBody("""{
   "audit_control_list" : [],
   "ui" : [],
   "ws" : [
      "base_setting"
   ],
   "xp_fix" : []
}""")).asJSON
      //body 我当前项目中最常用的参数,用"""...."""这样body内的字符串可以换行,其中换行符实际是“\n”
      //-------------
      //.queryParam("name", "Beautiful Computer")//queryParam的效果等同于增加了URL的参数而已,即“POST /api/getconf.json?mid=ebcd32d5f68e404db1ccc8ff2dacb360&ver=1.0&name=Beautiful%20Computer”
      //-------------    
      //.formParam("name", "Beautiful Computer") //formParam的例子,官方的,没什么特别
      //.formParam("introduced", "2012-05-30") //如果这样连续写两行formParam,实际效果等于post了这个数据“name=Beautiful+Computer&introduced=2012-05-30”,空格居然是个+号,无语
      )
 
  setUp(scn.inject(atOnceUsers(1)).protocols(httpConf))
}

 另外,

如果需要同时压多台机器,可以使用方法:

.baseURLs("http://10.0.0.1",“http://10.0.0.2")

重复次数设置:

val scn = scenario("BaiduSimulation").repeat(100){
exec(http("baidu_home").get("/"))
}

持续时间:

val scn = scenario("BaiduSimulation").during(100){
exec(http("baidu_home").get("/"))
}

 如果两个请求有关联:

    val chains = exec(
                    http("search")
                        .post("/test") // 第一次交互,例如打开baidu
                        .headers(headers)
                        .check(status.is(200))
                )
                .exec(
                    http("choose_brand")
                        .post("/test") // 第二次交互,例如搜索Gatling
                        .headers(headers)
                        .check(status.is(200))
                )

 

posted @ 2017-04-19 15:18  wbinbin  阅读(550)  评论(0)    收藏  举报