以前寫過一些文章講了Groovy如何在JMeter中協助測試:正則表達式
此次來看看Groovy正則表達式在JMeter中的應用。shell
正則表達式是特殊的文本字符串,用做查找與之匹配的其餘字符串的模板。它們是從字符串中檢索數據(子字符串)的很是強大的機制。在Apache JMeter™中,能夠從內置組件正則表達式提取器中使用正則表達式,也能夠用Groovy編寫它們。編程
將正則表達式與Groovy一塊兒使用可提供更大的靈活性並節省時間。例如,若是您須要提取幾個不一樣的參數,則能夠只編寫一個腳本,而不是爲每一個請求添加一個正則表達式提取器。json
在本文中,我將向您展現當使用JMeter對API響應進行性能測試時,如何在Groovy中使用正則表達式。框架
這裏先看一下接口的響應,以下:異步
{ "success": 1, "gt": "3c73c021ac3bfea7b5df8d461b5573c5", "challenge": "60e86734e0dfb7db48c5661ff9c5c935", "new_captcha": true }
這裏個人需求是獲取challenge
這個字段的值,固然這個須要用解析json的方式更好,具體參考文章:用Groovy處理JMeter斷言和日誌。本期我採用正則提取的方式進行提取,並賦值到某個線程私有變量中,賦值變量部分能夠參考文章:用Groovy處理JMeter變量。性能
腳本以下:測試
def response = prev.getResponseDataAsString() log.info("響應內容:"+ response) def re = response =~ /challenge":.+?"/ log.info("提取結果:"+ re[0]) def a = re[0] - "challenge\":\"" - "\"" vars.put("MY1",a) log.warn("修改後的MY1參數是:${vars.get("MY1")}")
控制檯輸出:spa
2020-03-08 17:45:20,035 INFO o.a.j.e.StandardJMeterEngine: Running the test! 2020-03-08 17:45:20,038 INFO o.a.j.s.SampleEvent: List of sample_variables: [] 2020-03-08 17:45:20,040 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*) 2020-03-08 17:45:20,233 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : 線程組 2020-03-08 17:45:20,233 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group 線程組. 2020-03-08 17:45:20,233 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error 2020-03-08 17:45:20,233 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=1 perThread=1000.0 delayedStart=false 2020-03-08 17:45:20,233 INFO o.a.j.t.ThreadGroup: Started thread group number 1 2020-03-08 17:45:20,233 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started 2020-03-08 17:45:20,234 INFO o.a.j.t.JMeterThread: Thread started: 線程組 1-1 2020-03-08 17:45:20,495 INFO o.a.j.a.J.JSR223 正則提取: 響應內容:{"success":1,"gt":"3c73c021ac3bfea7b5df8d461b5573c5","challenge":"b001a7188421320f77fb4631dbd72116","new_captcha":true} 2020-03-08 17:45:20,495 INFO o.a.j.a.J.JSR223 正則提取: 提取結果:challenge":"b001a7188421320f77fb4631dbd72116" 2020-03-08 17:45:20,496 WARN o.a.j.a.J.JSR223 正則提取: 修改後的MY1參數是:b001a7188421320f77fb4631dbd72116 2020-03-08 17:45:20,496 INFO o.a.j.t.JMeterThread: Thread is done: 線程組 1-1 2020-03-08 17:45:20,496 INFO o.a.j.t.JMeterThread: Thread finished: 線程組 1-1 2020-03-08 17:45:20,496 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test 2020-03-08 17:45:20,497 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)
而後當前線程下一次請求時,變量MY1
的值已經變成了咱們修改過的內容。命令行