Ngrinder脚本开发各细节锦集(groovy)
生活随笔
收集整理的這篇文章主要介紹了
Ngrinder脚本开发各细节锦集(groovy)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Ngrinder腳本開(kāi)發(fā)各細(xì)節(jié)錦集(groovy)
1、生成隨機(jī)字符串(import org.apache.commons.lang.RandomStringUtils)
數(shù)字:RandomStringUtils.randomNumeric(length);字母:RandomStringUtils.randomAlphabetic(length);字母加數(shù)字:RandomStringUtils.randomAlphanumeric(length);所有ASCCII字符:RandomStringUtils.randomAscii(length);自定義混合字符:RandomStringUtils.randomAscii(length, string);2、生成隨機(jī)數(shù)字:(import java.util.concurrent.ThreadLocalRandom;)
數(shù)字:int random_number = ThreadLocalRandom.current().nextInt(min_num, max_num);3、獲取項(xiàng)目數(shù)據(jù)文件路徑
common項(xiàng)目:"/resources/account.txt"maven項(xiàng)目:Thread.currentThread().getContextClassLoader().getResource("/account.txt").getPath();maven項(xiàng)目獲取文件內(nèi)容:ReflectionUtils.getCallingClass(0).getResourceAsStream("/account.txt").getText("UTF-8")4、讀取文件:
txt每行單數(shù)據(jù): String[] file_arrary = new File("/resources/account.txt") as String[];String file_data = file_arrary[arrary_index];txt每行雙數(shù)據(jù): String[] file_arrary = new File("/resources/account.txt") as String[];String data_one = file_arrary[arrary_index].split(",")[0];String data_two = file_arrary[arrary_index].split(",")[1];另一種方法: List<String> reqDataArrList = new File(dataFilePath).readLines()String data_one = reqDataArrList.get(arrary_index).split(",")[0];String data_two = reqDataArrList.get(arrary_index).split(",")[1];txt每行多數(shù)據(jù)可參考雙數(shù)據(jù)方法。也可以參考json方式存儲(chǔ):BufferedReader txt_content=new BufferedReader(new FileReader(new File("/resources/account.txt")))data_json = new JSONObject()String text_line = ""while(( text_line=txt_content.readLine())!=null){data_json.put(text_line.split(",")[0],text_line.split(",")[1])}String data_one = data_json.keys[0]String data_two = data_json.getString(data_one)5、寫入文件:
覆蓋寫入: def write = new File(file_path, file_name).newPrintWriter();write.write(write_text);write.flush();write.close()追加寫入: def write = new File(file_path, file_name).newPrintWriter();write.append(write_text);write.flush();write.close()6、json文件的數(shù)據(jù)處理(import org.ngrinder.recorder.RecorderUtils)
json文件讀取: String json_str = new File(file_path).getText("UTF-8")def json_object = RecorderUtils.parseRequestToJson(json_str)長(zhǎng)度:json_object.length()關(guān)鍵字:json_object.keys()添加元素:json_object.put(name, value)修改元素:json_object.put(name, value)刪除元素:json_object.remove(name, value)獲取對(duì)應(yīng)value:json_object.getString(name)7、字符串的處理
字符串截取:String new_str = old_str[0..3]字符串替換:String string = str.replace("old","new")字符串統(tǒng)計(jì):int count = string.count("char")字符串轉(zhuǎn)化:int int_num = Integer.parseInt(string)1、設(shè)置多個(gè)請(qǐng)求事務(wù)(即多個(gè)test方法)
1)設(shè)置多個(gè)靜態(tài)Gtest對(duì)象:public static GTest test1public static GTest test22)實(shí)例化多個(gè)Gtest對(duì)象:test1 = new GTest(1, "test1");test2 = new GTest(2, "test2");3)監(jiān)聽(tīng)多個(gè)test請(qǐng)求:test1.record(this, "test1")test2.record(this, "test2")4)定義多個(gè)test方法:public void test1(){grinder.logger.info("---ones: {}---", grinder.threadNumber+1)}public void test2(){grinder.logger.info("---twos: {}---", grinder.threadNumber+1)}2、Ngrinder定義請(qǐng)求參數(shù)集:
add方法: List<NVPair> paramList = new ArrayList<NVPair>();paramList.add(new NVPair("name", "value"));paramList.add(new NVPair("name", "value"));params = paramList.toArray();new方法: params = [new NVPair("name", "value"), new NVPair("name", "value")];3、Ngrinder處理日志:
日志級(jí)別(三種常見(jiàn)): grinder.logger.info("----before process.----");grinder.logger.warn("----before process.----");grinder.logger.error("----before process.----");日志限定(僅打印error級(jí)別) :1)導(dǎo)入依賴包import ch.qos.logback.classic.Level;import org.slf4j.LoggerFactory;2)設(shè)定級(jí)別@BeforeThreadLoggerFactory.getLogger("worker").setLevel(Level.ERROR);3)設(shè)置打印語(yǔ)句@testgrinder.logger.error("----error.----");日志輸出(輸出所有進(jìn)程日志):將每個(gè)agent的.ngrinder_agent/agent.conf中一項(xiàng)修改為agent.all_logs=true日志打印:打印變量:grinder.logger.error("{},{}",variable1,variable2); // 換行或縮進(jìn)可在""中加\n或\t4、Ngrinder的cookie處理
1) 登錄產(chǎn)生cookie@BeforeThreadlogin_get_cookie(); // 調(diào)用登錄方法cookies = CookieModule.listAllCookies(HTTPPluginControl.getThreadHTTPClientContext()); // 配置cookie管理器2) 讀取控制器中cookie@Beforecookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }5、Ngrinder請(qǐng)求方式:
1)通過(guò)url加參數(shù)直接訪問(wèn):post方法: HTTPResponse result = request.POST("http://192.168.2.135:8080/blogs", params, headers)get方法: HTTPResponse result = request.GET("http://192.168.2.135:8080/blogs", params, headers)參數(shù)是json:設(shè)置請(qǐng)求頭參數(shù){"Content-Type": "application/json"}2)通過(guò)參數(shù)化所有請(qǐng)求數(shù)據(jù)為json對(duì)象(導(dǎo)入import org.ngrinder.recorder.RecorderUtils)HTTPResponse result = RecorderUtils.sendBy(request, req_data_json)HTTPResponse result = RecorderUtils.sendBy(request, req_data_json)6、Ngringer的test運(yùn)行次數(shù)設(shè)定(將總運(yùn)行測(cè)試次數(shù)按百分比例分配到相應(yīng)test):
1)引用依賴包:import net.grinder.scriptengine.groovy.junit.annotation.RunRate2)設(shè)置運(yùn)行次數(shù)百分比(所有test設(shè)定的比例值不夠100,那不滿的部分不運(yùn)行,比如設(shè)定總比80,只運(yùn)行這80部分):@RunRate(50) // 數(shù)字代表百分比@Testpublic void test1(){}@RunRate(50) // 數(shù)字代表百分比@Testpublic void test2(){}7、Ngringer獲取設(shè)置的加壓機(jī)總數(shù)、進(jìn)程總數(shù)、線程總數(shù)等信息:
int tota_agents = Integer.parseInt(grinder.getProperties().get("grinder.agents").toString()) // 設(shè)置的總加壓機(jī)數(shù)int total_processes = Integer.parseInt(grinder.properties().get("grinder.processes").toString()) // 設(shè)置的總進(jìn)程數(shù)int total_threads = Integer.parseInt(grinder.properties().get("grinder.threads").toString()) // 設(shè)置的總線程數(shù)int total_runs = Integer.parseInt(grinder.properties().get("grinder.runs").toString()) // 設(shè)置的總運(yùn)行次數(shù)(若設(shè)置的是運(yùn)行時(shí)長(zhǎng),則得到0)8、Ngringer獲取當(dāng)前運(yùn)行的加壓機(jī)編號(hào)、進(jìn)程編號(hào)、線程編號(hào)等信息(都從0遞增):
int agent_number = grinder.agentNumber // 當(dāng)前運(yùn)行的加壓機(jī)編號(hào)int process_number = grinder.processNumber // 當(dāng)前運(yùn)行的進(jìn)程編號(hào)int thread_number = grinder.threadNumber // 當(dāng)前運(yùn)行的線程編號(hào)int run_number = grinder.runNumber // 當(dāng)前運(yùn)行的運(yùn)行次數(shù)編號(hào)9、Ngringer獲取唯一遞增值方法(從1遞增,不重復(fù)):
// 傳遞接口參數(shù)runNumber(即def runNumber = grinder.runNumber)private int getIncrementId(int runNumber){// 獲取壓力機(jī)總數(shù)、進(jìn)程總數(shù)、線程總數(shù)int totalAgents = Integer.parseInt(grinder.getProperties().get("grinder.agents").toString())int totalProcess = Integer.parseInt(grinder.getProperties().get("grinder.processes").toString())int totalThreads = Integer.parseInt(grinder.getProperties().get("grinder.threads").toString())// 獲取當(dāng)前壓力機(jī)數(shù)、進(jìn)程數(shù)、線程數(shù)int agentNum = grinder.agentNumberint processNum = grinder.processNumberint threadNum = grinder.threadNumber// 獲取唯一遞增數(shù)idint incrementId = agentNum * totalProcess * totalThreads + processNum * totalThreads + threadNum + totalAgents * totalProcess * totalThreads * runNumberreturn incrementId}10、Ngringer根據(jù)唯一遞增值獲取參數(shù)化文件中的唯一行號(hào):
1)需要設(shè)置靜態(tài)變量:private enum WhenOutOfValues { AbortVuser, ContinueInCycleManner, ContinueWithLastValue }2)傳遞接口參數(shù)fileDataList(即def fileDataList = new File(dataFilePath).readLines())private int getLineNum(def fileDataList) {// 獲取當(dāng)前運(yùn)行數(shù)、數(shù)據(jù)讀取行數(shù)、數(shù)據(jù)最大行數(shù)int counter = getIncrementId(grinder.runNumber)int lineNum = counter + 1int maxLineNum = fileDataList.size() - 1// 讀取最大值的判斷處理WhenOutOfValues outHandler = WhenOutOfValues.AbortVuserif (lineNum > maxLineNum) {if(outHandler.equals(WhenOutOfValues.AbortVuser)) {lineNum = maxLineNum //grinder.stopThisWorkerThread()} else if (outHandler.equals(WhenOutOfValues.ContinueInCycleManner)) {lineNum = (lineNum - 1) % maxLineNum + 1} else if (outHandler.equals(WhenOutOfValues.ContinueWithLastValue)) {lineNum = maxLineNum}}return lineNum}11、Ngrinder日志輸出配置的測(cè)試信息:(import java.text.SimpleDateFormat)
public static String getTestInfo(){String time_string = ""// 獲取壓測(cè)時(shí)設(shè)置的進(jìn)程總數(shù)、線程總數(shù)、運(yùn)行次數(shù)并在log中打印int all_process = grinder.getProperties().getInt("grinder.processes", 1) // 設(shè)置的總進(jìn)程數(shù)int all_threads = grinder.getProperties().getInt("grinder.threads", 1) // 設(shè)置的總線程數(shù)int all_runs = grinder.getProperties().getInt("grinder.runs", 1) // 設(shè)置的總運(yùn)行次數(shù)(若設(shè)置的是運(yùn)行時(shí)長(zhǎng),則得到0)int all_duration = grinder.getProperties().getLong("grinder.duration", 1) // 設(shè)置的總運(yùn)行時(shí)長(zhǎng)(若設(shè)置的是運(yùn)行次數(shù),則得到0)// 格式化時(shí)間毫秒輸出(輸出格式00:00:00)SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss")formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"))String all_duration_str = formatter.format(all_duration)if (all_duration_str.equals("00:00:00"))time_string = "Test information: the processes is "+all_process+", the threads is "+all_threads+", the run count is "+all_runs+"."elsetime_string = "Test information: the processes is "+all_process+", the threads is "+all_threads+", the run time is "+all_duration_str+"."return time_string}12、Ngrinder打印所有的配置信息
String property = grinder.getProperties();grinder.logger.info("------- {}", property) ;13、Ngrinder獲取請(qǐng)求返回值:
HTTPResponse result = request.POST("http://192.168.2.135:8080/blogs", params, headers)返回的文本:grinder.logger.info("----{}----", result.getText()) // 或者result.text返回的狀態(tài)碼:grinder.logger.info("----{}----", result.getStatusCode()) // 或者result.statusCode返回的url:grinder.logger.info("----{}----", result.getEffectiveURI())返回的請(qǐng)求頭所有參數(shù):grinder.logger.info("---\n{}---", result)返回的請(qǐng)求頭某參數(shù):grinder.logger.info("----{}---- ", result.getHeader("Content-type"))14、Ngrinder返回值的匹配:
匹配狀態(tài)碼:assertThat(result.getStatusCode(), is(200)) 匹配包含文本:assertThat(result.getText(), containsString("success"))15、Ngrinder獲取所有虛擬用戶數(shù):
public int getVusers() {int totalAgents = Integer.parseInt(grinder.getProperties().get("grinder.agents").toString());int totalProcesses = Integer.parseInt(grinder.getProperties().get("grinder.processes").toString());int totalThreads = Integer.parseInt(grinder.getProperties().get("grinder.threads").toString());int vusers = totalAgents * totalProcesses * totalThreads;return vusers; }16、Ngrinder的斷言和error日志輸出
if (result.statusCode == 301 || result.statusCode == 302) {grinder.logger.error("Possible error: {} expected: <200> but was: <{}>.",result.getEffectiveURI(),result.statusCode);} else {assertEquals((String)result.getEffectiveURI(), result.statusCode, 200)assertThat((String)result.getEffectiveURI(), result.statusCode, is(200))}
參考文檔:
1、https://testerhome.com/topics/17585?locale=zh-CN
2、https://my.oschina.net/aub/blog/858483
3、https://blog.csdn.net/u013512987/article/details/81776845
4、https://www.cnblogs.com/zjsupermanblog/archive/2017/08/18/7390980.html
5、https://www.cnblogs.com/lindows/p/10517839.html
6、https://www.cnblogs.com/zhongyehai/p/10386478.html
總結(jié)
以上是生活随笔為你收集整理的Ngrinder脚本开发各细节锦集(groovy)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mondrian olap 示例_jav
- 下一篇: 点云/网格模型的体积计算