性能工具之nGrinder關聯腳本編寫簡單介紹

  • 2019 年 11 月 3 日
  • 筆記

背景:

在做性能測試,腳本之間的關聯是一個比較棘手的問題,nGrinder腳本是怎麼關聯,其實也是比較簡單的,簡單前提條件是自己具備一定的知識,也就是需要程式碼基礎、http協議知識、網路知識等這些基礎知識,這樣才能開展工作。

常見的獲取請求結果方法有:

  1. 通過正則表達方式獲取結果;
  2. 通過xpath方式獲取相關結果;
  3. 通過JSON解析獲取相關結果

關聯介紹

  • 關聯的目的是後面請求需要,如果不需要就不需要關聯。
  • 關聯獲取結果做斷言

想了解更多、更詳細關聯知識請查找相關資料。

在編寫nGrinder腳本之前請學習下groovy語法這樣方便寫腳本,腳本編寫建議在idea中上寫腳本與調試腳本,這樣有語法提示能很快寫出腳本與調試腳本,寫完腳本後直接複製到線上腳本中在微調驗證就能使用。

腳本編寫簡單演示

本次腳本編寫與調試需要解析JSON所以需要上傳fastjson-1.2.62.jar用例解析JSON腳本,下載地址為:

https://mvnrepository.com/artifact/com.alibaba/fastjson

<dependency>      <groupId>com.alibaba</groupId>      <artifactId>fastjson</artifactId>      <version>1.2.62</version>  </dependency>

1、如果是線上直接寫腳本需要上傳jar:

在腳本頁面的腳本文件夾中新建lib文件夾,之後再lib文件中上傳相關的jar包,如下圖:

點擊文件夾:

注意:一定在腳本文件相關的地方新建lib文件夾,並且在lib下中上傳jar如:

2、如果是idea中寫程式碼與調試腳本,需要在腳本文件中新建lib文件夾之後在把jar包加入工程中去如:

相關工程:https://github.com/357712148/nGrinder/blob/master/script-sample/test-with-login/OneAndTwo.groovy

工程下載地址:

https://github.com/357712148/nGrinder.git

該工程下載後需要處理下才可以使用:

點擊

再次點擊:

選擇腳本工程

再次選擇:

上面操作後即可實現程式碼與調試腳本,如果還是有問題,自己微調即可。

idea中調試並且測試

線上調試:

程式碼示例

    import HTTPClient.Cookie      import HTTPClient.CookieModule      import HTTPClient.HTTPResponse      import HTTPClient.NVPair      import com.alibaba.fastjson.JSONArray      import groovy.json.JsonParser      import groovy.json.JsonSlurper      import net.grinder.plugin.http.HTTPPluginControl      import net.grinder.plugin.http.HTTPRequest      import net.grinder.script.GTest      import net.grinder.scriptengine.groovy.junit.GrinderRunner      import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess      import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread      import org.junit.Before      import org.junit.Test      import org.junit.runner.RunWith      import com.alibaba.fastjson.JSONObject      import static net.grinder.script.Grinder.grinder      import static org.hamcrest.Matchers.is      // import static net.grinder.util.GrinderUtils.* // You can use this if you're using nGrinder after 3.2.3      import static org.junit.Assert.assertThat      /**       * @Title: OneAndTwo* @Description: this is       * @author liwen* @date 2019/10/27 / 11:00       */      @RunWith(GrinderRunner)      class OneAndTwo {          public static GTest test          // 定義 HTTPRequest 靜態變數 request,用於發送 HTTP 請求          public static HTTPRequest request          // 定義 NVPair 數組 headers ,用於存放通用的請求頭數據          public static NVPair[] headers = []          // 定義 NVPair 數組 params ,用於存放請求參數數據          public static NVPair[] params = []          // 定義 Cookie 數組 cookies ,用於存放通用的 cookie 數據          public static Cookie[] cookies = []          //存儲第一個請求得參數          def paramName = new ArrayList()          @BeforeProcess          public static void beforeProcess() {              // 設置請求響應超時時間(ms)              HTTPPluginControl.getConnectionDefaults().timeout = 6000              // 創建GTest對象,第一個參數1代表有多個請求/事務時的執行順序ID,              // 第二個參數是請求/事務的名稱,會顯示在summary結果中,有多個請求/事務時,要創建多個GTest對象              test = new GTest(1, "User_find_01")              //創建 HTTPRequest 對象,用於發起 HTTP 請求              request = new HTTPRequest()              // Set header datas              List<NVPair> headerList = new ArrayList<NVPair>()              headerList.add(new NVPair("Content-Type", "application/x-www-form-urlencoded"))              headerList.add(new NVPair("Connection", "keep-alive"))              headers = headerList.toArray()              // Set param datas      //        List<Cookie> cookieList = new ArrayList<Cookie>()      //        cookieList.add(new Cookie("Cookie", "null", "localhost:8888", "", new Date(), true))      //        cookies = cookieList.toArray()              grinder.logger.info("before process.");          }          @BeforeThread          public void beforeThread() {      //        註冊事件,啟動test,第二個參數要與@Test註解的方法名保持一致,有多個請求/事務時,要註冊多個事件              test.record(this, "test")              //配置延遲報告統計結果              grinder.statistics.delayReports = true;              grinder.logger.info("before thread.");          }          @Before          public void before() {              //在這裡可以添加headers屬性和cookies      //        request.setHeaders(headers)              cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }              grinder.logger.info("before thread. init headers and cookies");          }          @Test          public void test() {              getUserFind()              getItem()          }          public void getUserFind() {              // 發送GET請求              HTTPResponse resu = request.GET("http://localhost:8888/userfind")              def text1 = resu.getText()              JSONObject jsonObject = JSONObject.parseObject(text1);              JSONObject object = jsonObject.getJSONObject("extend")              JSONArray array = object.getJSONArray("info")              for (int i = 0; i < array.size(); i++) {                  JSONObject object1 = JSONObject.parseObject(array.get(i).toString())                  Object name = object1.get("userName");                  paramName.add(String.valueOf(name))              }              assertThat(resu.statusCode, is(200))          }          public void getItem() {              List<NVPair> paramList = new ArrayList<NVPair>()              //獲取參數的第一個值              paramList.add(new NVPair("userName", paramName.get(0)))              params = paramList.toArray()              // Set cookie datas              HTTPResponse result = request.GET("http://localhost:8888/findName", params)              def text = result.getText()              grinder.logger.info("這是第二請求" + text)              // 斷言HTTP請求狀態碼              assertThat(result.statusCode, is(200))          }      }

結果顯示:

這是相應的測試工程程式碼下載地址:

https://github.com/357712148/bodygit.git

程式碼截圖: