11、生成随机字符串(import org.apache.commons.lang.RandomStringUtils) 2 数字:RandomStringUtils.randomNumeric(length); 3 字母:RandomStringUtils.randomAlphabetic(length); 4 字母加数字:RandomStringUtils.randomAlphanumeric(length); 5 所有ASCCII字符:RandomStringUtils.randomAscii(length); 6 自定义混合字符:RandomStringUtils.randomAscii(length, string); 7 82、生成随机数字:(import java.util.concurrent.ThreadLocalRandom;) 9 数字:int random_number = ThreadLocalRandom.current().nextInt(min_num, max_num); 10 113、获取项目数据文件路径 12 common项目:"/resources/account.txt" 13 maven项目:Thread.currentThread().getContextClassLoader().getResource("/account.txt").getPath(); 14 maven项目获取文件内容:ReflectionUtils.getCallingClass(0).getResourceAsStream("/account.txt").getText("UTF-8") 154、读取文件: 16 txt每行单数据: String[] file_arrary = new File("/resources/account.txt") as String[]; 17 String file_data = file_arrary[arrary_index]; 18 19 txt每行双数据: String[] file_arrary = new File("/resources/account.txt") as String[]; 20 String data_one = file_arrary[arrary_index].split(",")[0]; 21 String data_two = file_arrary[arrary_index].split(",")[1]; 22 另一种方法: 23 List<String> reqDataArrList = new File(dataFilePath).readLines() 24 String data_one = reqDataArrList.get(arrary_index).split(",")[0]; 25 String data_two = reqDataArrList.get(arrary_index).split(",")[1]; 26 27 txt每行多数据可参考双数据方法。也可以参考json方式存储: 28 BufferedReader txt_content=new BufferedReader(new FileReader(new File("/resources/account.txt"))) 29 data_json = new JSONObject() 30 String text_line = "" 31 while(( text_line=txt_content.readLine())!=null){ 32 data_json.put(text_line.split(",")[0],text_line.split(",")[1]) 33 } 34 String data_one = data_json.keys[0] 35 String data_two = data_json.getString(data_one) 365、写入文件: 37 覆盖写入: def write = new File(file_path, file_name).newPrintWriter(); 38 write.write(write_text); 39 write.flush(); 40 write.close() 41 42 追加写入: def write = new File(file_path, file_name).newPrintWriter(); 43 write.append(write_text); 44 write.flush(); 45 write.close() 46 476、json文件的数据处理(import org.ngrinder.recorder.RecorderUtils) 48 json文件读取: String json_str = new File(file_path).getText("UTF-8") 49 def json_object = RecorderUtils.parseRequestToJson(json_str) 50 51 长度:json_object.length() 52 关键字:json_object.keys() 53 添加元素:json_object.put(name, value) 54 修改元素:json_object.put(name, value) 55 删除元素:json_object.remove(name, value) 56 获取对应value:json_object.getString(name) 57 587、字符串的处理 59 字符串截取:String new_str = old_str[0..3] 60 字符串替换:String string = str.replace("old","new") 61 字符串统计:int count = string.count("char") 62 字符串转化:int int_num = Integer.parseInt(string) 63 641、设置多个请求事务(即多个test方法) 65 1)设置多个静态Gtest对象: 66 public static GTest test1 67 public static GTest test2 68 2)实例化多个Gtest对象: 69 test1 = new GTest(1, "test1"); 70 test2 = new GTest(2, "test2"); 71 3)监听多个test请求: 72 test1.record(this, "test1") 73 test2.record(this, "test2") 74 4)定义多个test方法: 75 public void test1(){ 76 grinder.logger.info("---ones: {}---", grinder.threadNumber+1) 77 } 78 public void test2(){ 79 grinder.logger.info("---twos: {}---", grinder.threadNumber+1) 80 } 81 822、Ngrinder定义请求参数集: 83 add方法: List<NVPair> paramList = new ArrayList<NVPair>(); 84 paramList.add(new NVPair("name", "value")); 85 paramList.add(new NVPair("name", "value")); 86 params = paramList.toArray(); 87 88 new方法: params = [new NVPair("name", "value"), new NVPair("name", "value")]; 89 903、Ngrinder处理日志: 91 日志级别(三种常见): grinder.logger.info("----before process.----"); 92 grinder.logger.warn("----before process.----"); 93 grinder.logger.error("----before process.----"); 94 95 日志限定(仅打印error级别) : 96 1)导入依赖包 97 import ch.qos.logback.classic.Level; 98 import org.slf4j.LoggerFactory; 99 2)设定级别 100 @BeforeThread 101 LoggerFactory.getLogger("worker").setLevel(Level.ERROR); 102 3)设置打印语句 103 @test 104 grinder.logger.error("----error.----"); 105 日志输出(输出所有进程日志):将每个agent的.ngrinder_agent/agent.conf中一项修改为agent.all_logs=true 106 107 日志打印:打印变量:grinder.logger.error("{},{}",variable1,variable2); // 换行或缩进可在""中加\n或\t 108 1094、Ngrinder的cookie处理 110 1) 登录产生cookie 111 @BeforeThread 112 login_get_cookie(); // 调用登录方法 113 cookies = CookieModule.listAllCookies(HTTPPluginControl.getThreadHTTPClientContext()); // 配置cookie管理器 114 2) 读取控制器中cookie 115 @Before 116 cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) } 117 1185、Ngrinder请求方式: 119 1)通过url加参数直接访问: 120 post方法: HTTPResponse result = request.POST("http://192.168.2.135:8080/blogs", params, headers) 121 get方法: HTTPResponse result = request.GET("http://192.168.2.135:8080/blogs", params, headers) 122 参数是json:设置请求头参数{"Content-Type": "application/json"} 123 2)通过参数化所有请求数据为json对象(导入import org.ngrinder.recorder.RecorderUtils) 124 HTTPResponse result = RecorderUtils.sendBy(request, req_data_json) 125 HTTPResponse result = RecorderUtils.sendBy(request, req_data_json) 126 1276、Ngringer的test运行次数设定(将总运行测试次数按百分比例分配到相应test): 128 1)引用依赖包: 129 import net.grinder.scriptengine.groovy.junit.annotation.RunRate 130 2)设置运行次数百分比(所有test设定的比例值不够100,那不满的部分不运行,比如设定总比80,只运行这80部分): 131 @RunRate(50) // 数字代表百分比 132 @Test 133 public void test1(){} 134 @RunRate(50) // 数字代表百分比 135 @Test 136 public void test2(){} 137 1387、Ngringer获取设置的加压机总数、进程总数、线程总数等信息: 139 int tota_agents = Integer.parseInt(grinder.getProperties().get("grinder.agents").toString()) // 设置的总加压机数 140 int total_processes = Integer.parseInt(grinder.properties().get("grinder.processes").toString()) // 设置的总进程数 141 int total_threads = Integer.parseInt(grinder.properties().get("grinder.threads").toString()) // 设置的总线程数 142 int total_runs = Integer.parseInt(grinder.properties().get("grinder.runs").toString()) // 设置的总运行次数(若设置的是运行时长,则得到0) 143 1448、Ngringer获取当前运行的加压机编号、进程编号、线程编号等信息(都从0递增): 145 int agent_number = grinder.agentNumber // 当前运行的加压机编号 146 int process_number = grinder.processNumber // 当前运行的进程编号 147 int thread_number = grinder.threadNumber // 当前运行的线程编号 148 int run_number = grinder.runNumber // 当前运行的运行次数编号 149 1509、Ngringer获取唯一递增值方法(从1递增,不重复): 151 // 传递接口参数runNumber(即def runNumber = grinder.runNumber) 152 private int getIncrementId(int runNumber){ 153 // 获取压力机总数、进程总数、线程总数 154 int totalAgents = Integer.parseInt(grinder.getProperties().get("grinder.agents").toString()) 155 int totalProcess = Integer.parseInt(grinder.getProperties().get("grinder.processes").toString()) 156 int totalThreads = Integer.parseInt(grinder.getProperties().get("grinder.threads").toString()) 157 158 // 获取当前压力机数、进程数、线程数 159 int agentNum = grinder.agentNumber 160 int processNum = grinder.processNumber 161 int threadNum = grinder.threadNumber 162 163 // 获取唯一递增数id 164 int incrementId = agentNum * totalProcess * totalThreads + processNum * totalThreads + threadNum + totalAgents * totalProcess * totalThreads * runNumber 165 return incrementId 166 } 167 16810、Ngringer根据唯一递增值获取参数化文件中的唯一行号: 169 1)需要设置静态变量:private enum WhenOutOfValues { AbortVuser, ContinueInCycleManner, ContinueWithLastValue } 170 2)传递接口参数fileDataList(即def fileDataList = new File(dataFilePath).readLines()) 171 private int getLineNum(def fileDataList) { 172 // 获取当前运行数、数据读取行数、数据最大行数 173 int counter = getIncrementId(grinder.runNumber) 174 int lineNum = counter + 1 175 int maxLineNum = fileDataList.size() - 1 176 177 // 读取最大值的判断处理 178 WhenOutOfValues outHandler = WhenOutOfValues.AbortVuser 179 if (lineNum > maxLineNum) { 180 if(outHandler.equals(WhenOutOfValues.AbortVuser)) { 181 lineNum = maxLineNum //grinder.stopThisWorkerThread() 182 } else if (outHandler.equals(WhenOutOfValues.ContinueInCycleManner)) { 183 lineNum = (lineNum - 1) % maxLineNum + 1 184 } else if (outHandler.equals(WhenOutOfValues.ContinueWithLastValue)) { 185 lineNum = maxLineNum 186 } 187 } 188 return lineNum 189 } 19011、Ngrinder日志输出配置的测试信息:(import java.text.SimpleDateFormat) 191 public static String getTestInfo(){ 192 String time_string = "" 193 // 获取压测时设置的进程总数、线程总数、运行次数并在log中打印 194 int all_process = grinder.getProperties().getInt("grinder.processes", 1) // 设置的总进程数 195 int all_threads = grinder.getProperties().getInt("grinder.threads", 1) // 设置的总线程数 196 int all_runs = grinder.getProperties().getInt("grinder.runs", 1) // 设置的总运行次数(若设置的是运行时长,则得到0) 197 int all_duration = grinder.getProperties().getLong("grinder.duration", 1) // 设置的总运行时长(若设置的是运行次数,则得到0) 198 // 格式化时间毫秒输出(输出格式00:00:00) 199 SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss") 200 formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00")) 201 String all_duration_str = formatter.format(all_duration) 202 if (all_duration_str.equals("00:00:00")) 203 time_string = "Test information: the processes is "+all_process+", the threads is "+all_threads+", the run count is "+all_runs+"." 204 else 205 time_string = "Test information: the processes is "+all_process+", the threads is "+all_threads+", the run time is "+all_duration_str+"." 206 return time_string 207 } 20812、Ngrinder打印所有的配置信息 209 String property = grinder.getProperties(); 210 grinder.logger.info("------- {}", property) ; 211 21213、Ngrinder获取请求返回值: 213 HTTPResponse result = request.POST("http://192.168.2.135:8080/blogs", params, headers) 214 返回的文本:grinder.logger.info("----{}----", result.getText()) // 或者result.text 215 返回的状态码:grinder.logger.info("----{}----", result.getStatusCode()) // 或者result.statusCode 216 返回的url:grinder.logger.info("----{}----", result.getEffectiveURI()) 217 返回的请求头所有参数:grinder.logger.info("---\n{}---", result) 218 返回的请求头某参数:grinder.logger.info("----{}---- ", result.getHeader("Content-type")) 219 22014、Ngrinder返回值的匹配: 221 匹配状态码:assertThat(result.getStatusCode(), is(200)) 222 匹配包含文本:assertThat(result.getText(), containsString("success")) 223 22415、Ngrinder获取所有虚拟用户数: 225 public int getVusers() { 226 int totalAgents = Integer.parseInt(grinder.getProperties().get("grinder.agents").toString()); 227 int totalProcesses = Integer.parseInt(grinder.getProperties().get("grinder.processes").toString()); 228 int totalThreads = Integer.parseInt(grinder.getProperties().get("grinder.threads").toString()); 229 int vusers = totalAgents * totalProcesses * totalThreads; 230 return vusers; 231 } 23216、Ngrinder的断言和error日志输出 233 if (result.statusCode == 301 || result.statusCode == 302) { 234 grinder.logger.error("Possible error: {} expected: <200> but was: <{}>.",result.getEffectiveURI(),result.statusCode); 235 } else { 236 assertEquals((String)result.getEffectiveURI(), result.statusCode, 200) 237 assertThat((String)result.getEffectiveURI(), result.statusCode, is(200)) 238 }
参考文档:
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