Ngrinder腳本開發各細節錦集(groovy)


1、生成隨機字符串(import org.apache.commons.lang.RandomStringUtils)
		數字:RandomStringUtils.randomNumeric(length);
		字母:RandomStringUtils.randomAlphabetic(length);
		字母加數字:RandomStringUtils.randomAlphanumeric(length);
		所有ASCCII字符:RandomStringUtils.randomAscii(length);
		自定義混合字符:RandomStringUtils.randomAscii(length, string);
	
2、生成隨機數字:(import java.util.concurrent.ThreadLocalRandom;)
		數字:int random_number = ThreadLocalRandom.current().nextInt(min_num, max_num);
	
3、獲取項目數據文件路徑
		common項目:"/resources/account.txt"
		maven項目:Thread.currentThread().getContextClassLoader().getResource("/account.txt").getPath();
		maven項目獲取文件內容:ReflectionUtils.getCallingClass(0).getResourceAsStream("/account.txt").getText("UTF-8")
4、讀取文件:
		txt每行單數據:	String[] file_arrary = new File("/resources/account.txt") as String[]; 
						String file_data = file_arrary[arrary_index];
									
		txt每行雙數據:	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每行多數據可參考雙數據方法。也可以參考json方式存儲:
									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文件的數據處理(import org.ngrinder.recorder.RecorderUtils)
		json文件讀取:	String json_str = new File(file_path).getText("UTF-8")
									def json_object = RecorderUtils.parseRequestToJson(json_str)
									
									長度:json_object.length()
									關鍵字:json_object.keys()
									添加元素:json_object.put(name, value)
									修改元素:json_object.put(name, value)
									刪除元素:json_object.remove(name, value)
									獲取對應value:json_object.getString(name)
									
7、字符串的處理
		字符串截取:String new_str = old_str[0..3]
		字符串替換:String string = str.replace("old","new")
		字符串統計:int count = string.count("char")
		字符串轉化:int int_num = Integer.parseInt(string)
	
1、設置多個請求事務(即多個test方法)
		1)設置多個靜態Gtest對象:
			public static GTest test1
			public static GTest test2
		2)實例化多個Gtest對象:
			test1 = new GTest(1, "test1");
			test2 = new GTest(2, "test2");
		3)監聽多個test請求:
			test1.record(this, "test1")
			test2.record(this, "test2")
		4)定義多個test方法:
			public void test1(){
				grinder.logger.info("---ones: {}---", grinder.threadNumber+1)
			}
			public void test2(){
				grinder.logger.info("---twos: {}---", grinder.threadNumber+1)
			}
		
2、Ngrinder定義請求參數集:
		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處理日志:
		日志級別(三種常見):	grinder.logger.info("----before process.----");
												grinder.logger.warn("----before process.----");
												grinder.logger.error("----before process.----");
												
		日志限定(僅打印error級別) :
									1)導入依賴包
									import ch.qos.logback.classic.Level;
									import org.slf4j.LoggerFactory;
									2)設定級別
									@BeforeThread
										LoggerFactory.getLogger("worker").setLevel(Level.ERROR);
									3)設置打印語句
									@test
										grinder.logger.error("----error.----");
		日志輸出(輸出所有進程日志):將每個agent的.ngrinder_agent/agent.conf中一項修改為agent.all_logs=true
		
		日志打印:打印變量:grinder.logger.error("{},{}",variable1,variable2); // 換行或縮進可在""中加\n或\t
		
4、Ngrinder的cookie處理
		1) 登錄產生cookie
			@BeforeThread 
				login_get_cookie(); // 調用登錄方法
				cookies = CookieModule.listAllCookies(HTTPPluginControl.getThreadHTTPClientContext()); // 配置cookie管理器
		2) 讀取控制器中cookie
			@Before
				cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }
	
5、Ngrinder請求方式:
		1)通過url加參數直接訪問:
			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)
			參數是json:設置請求頭參數{"Content-Type": "application/json"}
		2)通過參數化所有請求數據為json對象(導入import org.ngrinder.recorder.RecorderUtils)
							HTTPResponse result = RecorderUtils.sendBy(request, req_data_json)
							HTTPResponse result = RecorderUtils.sendBy(request, req_data_json)
							
6、Ngringer的test運行次數設定(將總運行測試次數按百分比例分配到相應test):
		1)引用依賴包:
			import net.grinder.scriptengine.groovy.junit.annotation.RunRate
		2)設置運行次數百分比(所有test設定的比例值不夠100,那不滿的部分不運行,比如設定總比80,只運行這80部分):
			@RunRate(50)  // 數字代表百分比
			@Test
			public void test1(){}
			@RunRate(50)  // 數字代表百分比
			@Test
			public void test2(){}
			
7、Ngringer獲取設置的加壓機總數、進程總數、線程總數等信息:
		int tota_agents = Integer.parseInt(grinder.getProperties().get("grinder.agents").toString()) // 設置的總加壓機數
		int total_processes = Integer.parseInt(grinder.properties().get("grinder.processes").toString()) // 設置的總進程數
		int total_threads = Integer.parseInt(grinder.properties().get("grinder.threads").toString()) // 設置的總線程數
		int total_runs = Integer.parseInt(grinder.properties().get("grinder.runs").toString()) // 設置的總運行次數(若設置的是運行時長,則得到0)
											
8、Ngringer獲取當前運行的加壓機編號、進程編號、線程編號等信息(都從0遞增):
		int agent_number = grinder.agentNumber // 當前運行的加壓機編號
		int process_number = grinder.processNumber // 當前運行的進程編號
		int thread_number = grinder.threadNumber // 當前運行的線程編號
		int run_number = grinder.runNumber // 當前運行的運行次數編號
		
9、Ngringer獲取唯一遞增值方法(從1遞增,不重復):
		// 傳遞接口參數runNumber(即def runNumber = grinder.runNumber)
		private int getIncrementId(int runNumber){
			// 獲取壓力機總數、進程總數、線程總數
			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())
			
			// 獲取當前壓力機數、進程數、線程數
			int agentNum = grinder.agentNumber
			int processNum = grinder.processNumber
			int threadNum = grinder.threadNumber
			
			// 獲取唯一遞增數id
			int incrementId = agentNum * totalProcess * totalThreads + processNum * totalThreads + threadNum + totalAgents * totalProcess * totalThreads * runNumber
			return incrementId
		}

10、Ngringer根據唯一遞增值獲取參數化文件中的唯一行號:
		1)需要設置靜態變量:private enum WhenOutOfValues { AbortVuser, ContinueInCycleManner, ContinueWithLastValue }
		2)傳遞接口參數fileDataList(即def fileDataList = new File(dataFilePath).readLines())
		private int getLineNum(def fileDataList) {
			// 獲取當前運行數、數據讀取行數、數據最大行數
			int counter = getIncrementId(grinder.runNumber)
			int lineNum = counter + 1
			int maxLineNum = fileDataList.size() - 1
			
			// 讀取最大值的判斷處理
			WhenOutOfValues outHandler = WhenOutOfValues.AbortVuser
			if (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日志輸出配置的測試信息:(import java.text.SimpleDateFormat)
		public static String getTestInfo(){
			String time_string = ""
			// 獲取壓測時設置的進程總數、線程總數、運行次數並在log中打印
	        int all_process = grinder.getProperties().getInt("grinder.processes", 1) // 設置的總進程數
	        int all_threads = grinder.getProperties().getInt("grinder.threads", 1)  // 設置的總線程數
	        int all_runs = grinder.getProperties().getInt("grinder.runs", 1)  // 設置的總運行次數(若設置的是運行時長,則得到0)
	        int all_duration = grinder.getProperties().getLong("grinder.duration", 1) // 設置的總運行時長(若設置的是運行次數,則得到0)
	        // 格式化時間毫秒輸出(輸出格式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+"."
			else
				time_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獲取請求返回值:
			HTTPResponse result = request.POST("http://192.168.2.135:8080/blogs", params, headers)
			返回的文本:grinder.logger.info("----{}----", result.getText()) // 或者result.text
			返回的狀態碼:grinder.logger.info("----{}----", result.getStatusCode()) // 或者result.statusCode
			返回的url:grinder.logger.info("----{}----", result.getEffectiveURI())
			返回的請求頭所有參數:grinder.logger.info("---\n{}---", result)
			返回的請求頭某參數:grinder.logger.info("----{}---- ", result.getHeader("Content-type"))
			
14、Ngrinder返回值的匹配:
	匹配狀態碼:assertThat(result.getStatusCode(), is(200))
	匹配包含文本:assertThat(result.getText(), containsString("success"))
			
15、Ngrinder獲取所有虛擬用戶數:
	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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM