基于Java的接口测试
一览文件结构
配置
- pom.xml核心依赖配置
<dependencies> <!--httpclient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> <version>4.1.2</version> </dependency> <!--gson--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> <!--log--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> </dependencies> - 日志配置文件log4j.properties
log4j.addivity.org.apache=true # 应用于控制台 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.Threshold=INFO log4j.appender.CONSOLE.Target=System.out log4j.appender.CONSOLE.Encoding=utf-8 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=[apitest] %d - %c -%-4r [%t] %-5p %c %x - %m%n #应用于文件 #可以进行隔段时间进行输出日志 log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender #多长时间进行日志的输出和格式 log4j.appender.FILE.DatePattern='.'yyyy-MM-dd log4j.appender.FILE.File=C:\\Users\\kungfupeng\\Desktop\\log\\apitest.log log4j.appender.FILE.Threshold=INFO log4j.appender.FILE.Append=true log4j.appender.FILE.Encoding=utf-8 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=[apitest] %d %-5p - %m%n - 效果
代码实现
-
HttpGetSynchronized类
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.visionin.utils.SystemDataUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URLDecoder; import java.util.Map; import java.util.Set; public class HttpGetSynchronized { private final static Logger log = LoggerFactory.getLogger(HttpTest.class); public void execute(String uri, Map<String, Object> params, Map<String, String> mapHeaders) { log.info("=======start========="); log.info("请求地址:" + uri); String paramString = ""; if (params != null && params.size() != 0) { for (String key : params.keySet()) { paramString += "【" + key + "=" + params.get(key) + "】"; } } log.info("请求参数:" + paramString); //硬件信息--比较消耗cpu,测并发的时候可以注释掉这里 //log.info(SystemDataUtils.getRuntimeMemoryInfo()); //log.info(SystemDataUtils.getComputerMemoryInfo()); //log.info(SystemDataUtils.getAllThreads()); //log.info(SystemDataUtils.getCpuRatio()); //log.info(SystemDataUtils.getHardCardInfo()); try { if (uri == null || "".equals(uri.trim())) { log.error("请求地址为空!"); } //请求地址和请求参数拼接 if (params != null && params.size() != 0) { uri += "?"; for (String key : params.keySet()) { uri += key + "=" + params.get(key) + "&"; } } //处理%特殊字符 uri = uri.replaceAll("%(?![0-9a-fA-F]{2})", "%25"); //请求地址编码 String uriStr = URLDecoder.decode(uri, "UTF-8"); HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); HttpUriRequest httpGet = new HttpGet(uriStr); if (mapHeaders != null && mapHeaders.size() != 0) { for (String key : mapHeaders.keySet()) { httpGet.addHeader(key, mapHeaders.get(key)); } } log.info("请求方法:" + httpGet.getMethod()); log.info("请求协议:" + httpGet.getProtocolVersion()); Header[] allHeaders = httpGet.getAllHeaders(); String headerInfo = "请求头信息:【"; for (Header header : allHeaders) { headerInfo += header.getName() + ":" + header.getValue() + ","; } headerInfo += "】"; log.info(headerInfo); CloseableHttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { String entityStr = EntityUtils.toString(entity, "utf-8"); if (entityStr == null || "".equals(entityStr.trim())) { log.error("没有响应头!"); } else { //将结果转化为json对象 Gson g = new Gson(); JsonObject jsonObject = null; jsonObject = g.fromJson(entityStr, JsonObject.class); if (jsonObject == null) { log.error("返回结果:" + entityStr); log.error("json转化为null!"); } else { //获取code对象 JsonElement codeElement = null; codeElement = jsonObject.get("code"); if (codeElement == null) { log.error("没有code值!"); } else { int asInt = codeElement.getAsInt(); if (asInt == 200) { log.info("请求code对应的结果:正常!"); } else if (asInt == 400) { log.error("请求code对应的结果:执行中间错误(400)!"); } else if (asInt == 500) { log.error("请求code对应的结果:后台参数检测异常!"); } else if (asInt == 600) { log.error("请求code对应的结果:没有登录!"); } else if (asInt == 250) { log.error("请求code对应的结果:图片上传失败!"); } else { log.error("请求code对应的结果:没有对应的code解析!"); } log.info("后台返回的结果:" + entityStr); } } } } } catch (Exception e) { StackTraceElement[] stackTrace = e.getStackTrace(); String runtimeError = ""; for (StackTraceElement ste : stackTrace) { runtimeError += "\r" + "方法名" + ste.getMethodName() + ";类名" + ste.getClassName() + ";文件名" + ste.getFileName() + ";方法名" + ste.getMethodName() + ";第" + ste.getLineNumber() + "行"; } log.error(runtimeError); } log.info("=======end========="); } } -
HttpTest类
import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; //http模拟浏览器访问 public class HttpTest { //测并发 private static int threadCount = 1; public static void main(String[] args) { final CountDownLatch countDownLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { //模拟长时间访问 new Thread(new Runnable() { @Override public void run() { //长时间测 for (; ; ) { try { countDownLatch.await(); } catch (Exception e) { } try { //间隔时间 Thread.sleep(1000); } catch (Exception e) { } HttpGetSynchronized httpGetSynchronized = new HttpGetSynchronized(); //url String url = "http://kungfupeng/getPersonsById"; //参数 Map<String, Object> params = new HashMap<String, Object>(); params.put("person_id", "278"); params.put("group_id", "1"); //请求头信息 Map<String, String> headParams = new HashMap<String, String>(); headParams.put("Cookie", "visionin_cookie=9zqq6ojjra8k7u91336idpk7jkggs5nc"); httpGetSynchronized.execute(url, params, headParams); } } }).start(); countDownLatch.countDown(); } } } -
DateUtils类
import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static String getCurrentTime() { long timeStamp = System.currentTimeMillis(); return sdf.format(new Date(timeStamp)); } } -
SystemDataUtils类和autohttp类
import com.sun.management.OperatingSystemMXBean; import java.io.*; import java.lang.management.ManagementFactory; import java.util.StringTokenizer; public class SystemDataUtils { //--------------------cpu参数start------------------------ private static final int CPUTIME = 30; private static final int PERCENT = 100; private static final int FAULTLENGTH = 10; private static final File versionFile = new File("/proc/version"); private static String linuxVersion = null; //--------------------cpu参数end------------------------ //-------------------计算机物理内存start---------------- private static OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); //-------------------计算机物理内存end------------------ //--------------虚拟机内存--------start----------------- public static String getRuntimeMemoryInfo() { // 可使用内存 long totalMemory = Runtime.getRuntime().totalMemory() / 1024 / 1024; // 剩余内存 long freeMemory = Runtime.getRuntime().freeMemory() / 1024 / 1024; // 最大可使用内存 long maxMemory = Runtime.getRuntime().maxMemory() / 1024 / 1024; return "【Runtime:可使用内存: " + totalMemory + "MB,剩余内存: " + freeMemory + "MB,最大可使用内存: " + maxMemory + "MB】"; } //--------------虚拟机内存--------end----------------- //--------------计算机内存------start----------------- public static String getComputerMemoryInfo() { // 操作系统 String osName = System.getProperty("os.name"); // 总的物理内存 long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / 1024 / 1024; // 剩余的物理内存 long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / 1024 / 1024; // 已使用的物理内存 long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb .getFreePhysicalMemorySize()) / 1024 / 1024; return "【Local:操作系统: " + osName + ",总物理内存: " + totalMemorySize + "MB,剩余物理内存: " + freePhysicalMemorySize + "MB,已经使用的物理内存:" + usedMemory + " MB】"; } //--------------计算机内存--------end----------------- //------------------线程-----start-------------------- public static String getAllThreads() { // 获得线程总数 ThreadGroup parentThread; for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent()) { } int totalThread = parentThread.activeCount(); return "线程总数:" + totalThread; } //------------------线程-----end---------------------- //--------------------CPU----start------------------- public static String getCpuRatio() { double cpuRatio = 0; if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { cpuRatio = getCpuRatioForWindows(); } else { cpuRatio = getCpuRateForLinux(); } return "当前CPU的使用率为:" + cpuRatio + "%"; } private static double getCpuRatioForWindows() { try { String procCmd = System.getenv("windir") + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine," + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount"; // 取进程信息 long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd)); Thread.sleep(CPUTIME); long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd)); if (c0 != null && c1 != null) { long idletime = c1[0] - c0[0]; long busytime = c1[1] - c0[1]; return Double.valueOf( PERCENT * (busytime) / (busytime + idletime)) .doubleValue(); } else { return 0.0; } } catch (Exception ex) { ex.printStackTrace(); return 0.0; } } private static long[] readCpu(final Process proc) { long[] retn = new long[2]; try { proc.getOutputStream().close(); InputStreamReader ir = new InputStreamReader(proc.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line = input.readLine(); if (line == null || line.length() < FAULTLENGTH) { return null; } int capidx = line.indexOf("Caption"); int cmdidx = line.indexOf("CommandLine"); int rocidx = line.indexOf("ReadOperationCount"); int umtidx = line.indexOf("UserModeTime"); int kmtidx = line.indexOf("KernelModeTime"); int wocidx = line.indexOf("WriteOperationCount"); long idletime = 0; long kneltime = 0; long usertime = 0; while ((line = input.readLine()) != null) { if (line.length() < wocidx) { continue; } // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount, // ThreadCount,UserModeTime,WriteOperation String caption = Bytes.substring(line, capidx, cmdidx - 1) .trim(); String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim(); if (cmd.indexOf("wmic.exe") >= 0) { continue; } if (caption.equals("System Idle Process") || caption.equals("System")) { idletime += Long.valueOf( Bytes.substring(line, kmtidx, rocidx - 1).trim()) .longValue(); idletime += Long.valueOf( Bytes.substring(line, umtidx, wocidx - 1).trim()) .longValue(); continue; } kneltime += Long.valueOf( Bytes.substring(line, kmtidx, rocidx - 1).trim()) .longValue(); usertime += Long.valueOf( Bytes.substring(line, umtidx, wocidx - 1).trim()) .longValue(); } retn[0] = idletime; retn[1] = kneltime + usertime; return retn; } catch (Exception ex) { ex.printStackTrace(); } finally { try { proc.getInputStream().close(); } catch (Exception e) { e.printStackTrace(); } } return null; } private static double getCpuRateForLinux() { InputStream is = null; InputStreamReader isr = null; BufferedReader brStat = null; StringTokenizer tokenStat = null; try { Process process = Runtime.getRuntime().exec("top -b -n 1"); is = process.getInputStream(); isr = new InputStreamReader(is); brStat = new BufferedReader(isr); if (linuxVersion.equals("2.4")) { brStat.readLine(); brStat.readLine(); brStat.readLine(); brStat.readLine(); tokenStat = new StringTokenizer(brStat.readLine()); tokenStat.nextToken(); tokenStat.nextToken(); String user = tokenStat.nextToken(); tokenStat.nextToken(); String system = tokenStat.nextToken(); tokenStat.nextToken(); String nice = tokenStat.nextToken(); user = user.substring(0, user.indexOf("%")); system = system.substring(0, system.indexOf("%")); nice = nice.substring(0, nice.indexOf("%")); float userUsage = new Float(user).floatValue(); float systemUsage = new Float(system).floatValue(); float niceUsage = new Float(nice).floatValue(); return (userUsage + systemUsage + niceUsage) / 100; } else { brStat.readLine(); brStat.readLine(); tokenStat = new StringTokenizer(brStat.readLine()); tokenStat.nextToken(); tokenStat.nextToken(); tokenStat.nextToken(); tokenStat.nextToken(); tokenStat.nextToken(); tokenStat.nextToken(); tokenStat.nextToken(); String cpuUsage = tokenStat.nextToken(); Float usage = new Float(cpuUsage.substring(0, cpuUsage.indexOf("%"))); return (1 - usage.floatValue() / 100); } } catch (IOException ioe) { freeResource(is, isr, brStat); return 1; } finally { freeResource(is, isr, brStat); } } private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br) { try { if (is != null) is.close(); if (isr != null) isr.close(); if (br != null) br.close(); } catch (IOException ioe) { } } //--------------------CPU----end------------------- //---------------硬盘空间-----start------------------- public static String getHardCardInfo() { String result = "硬盘容量信息:"; File[] roots = File.listRoots();//获取磁盘分区列表 for (File file : roots) { result += "【" + file.getPath() + ":总容量 =" + file.getTotalSpace() / 1024 / 1024 / 1024 + "G,空闲未使用 = " + file.getFreeSpace() / 1024 / 1024 / 1024 + "G】"; } return result; } //---------------硬盘空间------end-------------------- } class Bytes { public static String substring(String src, int start_idx, int end_idx) { byte[] b = src.getBytes(); String tgt = ""; for (int i = start_idx; i <= end_idx; i++) { tgt += (char) b[i]; } return tgt; } }