Commit 48264825 by xuyamei

初始化

parents
# Created by .ignore support plugin (hsz.mobi)
### Java template
# Compiled class file
*.class
# xm-autotest
.idea
com.xiaomai.iml
target
test-output
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
.idea/.gitignore
.idea/.name
.idea/compiler.xml
.idea/dbnavigator.xml
.idea/encodings.xml
.idea/jarRepositories.xml
.idea/libraries/
.idea/misc.xml
.idea/modules.xml
.idea/vcs.xml
target/
test-output/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="员工信息场景case"> <!-- 起一个好听且唯一的名字-->
<test name="员工信息模块测试" preserve-order="true" verbose="3"> <!-- 再起一个听且唯一的名字 -->
<packages>
<package name="com.xiaomai.cases.polar.admin.*"></package> <!-- 添加自己想要集成测试的case 范围自己定 -->
</packages>
</test>
<listeners>
<listener class-name="com.xiaomai.client.RetryListener" />
<listener class-name="com.xiaomai.client.TestListener" />
<listener class-name="com.xiaomai.client.ExtentTestNGIReporterListener"/>
</listeners>
</suite>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="整个场景case"> <!-- 起一个好听且唯一的名字-->
<test name="整个场馆信息模块测试" preserve-order="true" verbose="3"> <!-- 再起一个听且唯一的名字 -->
<packages>
<package name="com.xiaomai.cases.polar.*"></package> <!-- 添加自己想要集成测试的case 范围自己定 -->
</packages>
</test>
<listeners>
<listener class-name="com.xiaomai.client.RetryListener" />
<listener class-name="com.xiaomai.client.TestListener" />
<listener class-name="com.xiaomai.client.ExtentTestNGIReporterListener"/>
</listeners>
</suite>
\ No newline at end of file
This diff is collapsed. Click to expand it.
package com.xiaomai.basetest;
import com.xiaomai.utils.XMBaseTest;
import org.testng.annotations.BeforeClass;
/**
* @Auther: pdd
* @Date: 2020/11/24/21:04
* @Description: 抽取公共继承工具类可用
*/
public abstract class BaseTestImpl extends XMBaseTest implements BaseTestInterface {
private String apiModuleName;
private String apiName;
private String loginUser;
private String terminal;
private String caseOwner;
@Override
public String getApiModuleName() {
return this.apiModuleName;
}
/**
* @Description: 每次必重写方法
* @Author: pdd
* @Date: 2020/11/26/11:20
*/
@Override
public String getApiName() {
return this.apiName;
}
@Override
public String getLoginUser() {
return this.loginUser;
}
@Override
public String getTerminal() {
return this.terminal;
}
@Override
public String getCaseOwner() {
return this.caseOwner;
}
public void setTestInfo(String apiModuleName, String loginUser, String terminal, String caseOwner) {
this.apiModuleName = apiModuleName;
this.loginUser = loginUser;
this.terminal = terminal;
this.caseOwner = caseOwner;
}
public void setTestInfo(String apiModuleName, String apiName, String loginUser, String terminal, String caseOwner) {
this.apiModuleName = apiModuleName;
this.loginUser = loginUser;
this.terminal = terminal;
this.caseOwner = caseOwner;
this.apiName = apiName;
}
@BeforeClass
@Override
public void beforeTest() {
xmAppApi.setApiModule(getApiModuleName())
.setApiName(getApiName())
.setLoginUser(getLoginUser())
.setTerminal(getTerminal());
dal.setCase_owner(getCaseOwner());
super.beforeTest();
}
@Override
public void businessData() { }
}
package com.xiaomai.basetest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
/**
* @Auther: pdd
* @Date: 2020/11/24/20:58
* @Description:
*/
public interface BaseTestInterface {
String getApiModuleName();
String getApiName();
String getLoginUser();
String getTerminal();
String getCaseOwner();
@BeforeMethod
void beforeTest();
/**
* @Description:测试之前数据准备
* @Author: pdd
* @Date: 2021/4/12/21:33
*/
@BeforeClass
void businessData();
}
package com.xiaomai.cases.polar.admin;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
import com.xiaomai.enums.RequestType;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.XMBaseTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @BelongsProject: xm-sportstest
* @BelongsPackage: com.xiaomai.cases
* @Author: xuyamei
* @CreateTime: 2024-02-26 15:34
* @Description: 员工
* @Version: 1.0
*/
public class TestGetAdmin extends XMBaseTest {
@BeforeMethod
public void beforeTest() {
xmAppApi.setApiModule(ApiModule.Polar_Admin) // API 所属模块
.setApiName("API_getAdmin")
.setLoginUser(LoginAccount.XYM_DEV) // http 接口,测试账号
.setTerminal(Terminal.B); // 所属端位(B端,C端,M端等, 必传)
dal.setCase_owner("xym")
.setCase_name( Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
super.beforeTest();
}
@Test
public void testGetAdmin(){
String body = "{\"id\":\"1760544702379651074\"}";
xmAppApi.doRequest(RequestType.JSON,params,body,headers);
JSONObject response = xmAppApi.getBodyInJSON();
System.out.println("-------:"+response);
}
}
package com.xiaomai.client;
import java.util.HashMap;
import java.util.Map;
/**
* @Auther: pdd
* @Date: 2020/09/10/15:59
* @Description:
*/
public class ApiResult {
private Map<String, String> api_request_params = new HashMap<String, String>();
private String api_request_data ;
private Map<String, String> api_request_headers=null;
private String api_response;
private String api_traceId;
private String url;
private String apiDesc;
public String getApiDesc() {
return apiDesc;
}
public void setApiDesc(String apiDesc) {
this.apiDesc = apiDesc;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String> getApi_request_params() {
return api_request_params;
}
public void setApi_request_params(Map<String, String> api_request_params) {
this.api_request_params = api_request_params;
}
public String getApi_request_data() {
return api_request_data;
}
public void setApi_request_data(String api_request_data) {
this.api_request_data = api_request_data;
}
public Map<String, String> getApi_request_headers() {
return api_request_headers;
}
public void setApi_request_headers(Map<String, String> api_request_headers) {
this.api_request_headers = api_request_headers;
}
public String getApi_response() {
return api_response;
}
public void setApi_response(String api_response) {
this.api_response = api_response;
}
public String getApi_traceId() {
return api_traceId;
}
public void setApi_traceId(String api_traceId) {
this.api_traceId = api_traceId;
}
}
package com.xiaomai.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.utils.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.util.StringUtils;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import java.util.*;
@ContextConfiguration(locations = {"classpath:/spring-core.xml"})
public class ApiTest extends AbstractTestNGSpringContextTests {
public static RestfulClient httpclient = null;
public static SSLRestfulClient sslhttpclient = null;
public static OkHttpClient okHttpClient = null;
// 支持业务数据方法参数
private static String host = null;
private static String url = null;
private Properties prop = null;
public static UtDal dal = new UtDal();
private static CommonRequestParameters loginInfo;
private ApiResult apiResult = new ApiResult();
public ApiTest() { }
@BeforeClass
public static void beforeClass() {
httpclient = new RestfulClient();
sslhttpclient = new SSLRestfulClient();
okHttpClient = new OkHttpClient();
}
/**
* 测试接口调用API
*/
@BeforeMethod
public void beforeTest() {
}
/**
* 测试接口调用API
*/
public void initApi(XMAppApi xmAppApi) {
clearApiData(xmAppApi);// 清空上次API调用信息
dataPreparation(xmAppApi);
}
private void clearApiData(XMAppApi api){
api.setApi_request_params(new IdentityHashMap());
api.setApi_request_data(null);
api.setApi_request_headers(new HashMap<>());
api.setApi_response(null);
api.setApi_traceId(null);
}
/**
* 数据业务方法调用 可选参数userInfos 测试时需要切换端位时传入要登录的user信息
*/
public void beforeDataRequest(XMAppApi dataApi,DataUserInfo...userInfos){
clearApiData(dataApi);// 清空上次API调用信息
// 默认同端位接口调用, dataApi 使用被测试接口信息里的 登录信息
/* dataApi.setLoginUser(xmAppApi.getLoginUser()) // http 接口,测试账号
.setTerminal(xmAppApi.getTerminal())
.setEnv(xmAppApi.getEnv()); // 所属端位(B端,C端,M端等, 必传)*/
// 支持切换端位调用
if(userInfos.length>0){
DataUserInfo info = userInfos[0];
Assert.assertNotNull(info,"userInfos 为空!!!");
if(!StringUtils.isEmpty(info.getLoginUser())){
dataApi.setLoginUser(info.getLoginUser());
}
if(!StringUtils.isEmpty(info.getTerminal())){
dataApi.setTerminal(info.getTerminal());
}
if(!StringUtils.isEmpty(info.getApiModule())){
dataApi.setApiModule(info.getApiModule());
}
}
dataPreparation(dataApi);
}
/**
* 业务API调用专用
*/
private void dataPreparation(XMAppApi executionApi) {
Assert.assertNotNull(executionApi.getApiModule(), "必要的api信息不存在!");
prop = CommUtil.getconfig();
JsonAndFile fileHandle = new JsonAndFile();
String apiModule = prop.getProperty(executionApi.getApiModule());
// 获取接口模块参数
String fileParam = fileHandle.readTxtFile(System.getProperty("user.dir") + apiModule);
Assert.assertNotNull(fileParam, "必要的API模块信息未找到,请检查api模块文件路径!");
JSONObject api = (JSONObject) JSON.parseObject(fileParam).get(executionApi.getApiName());
Assert.assertNotNull(api, "必要的API接口信息未找到,请检查apiName信息!");
executionApi.setApiDesc(api.getString("apiName"));
/**
* 测试环境测试
* M端测试默认使用rc 环境
* 其他系统测试默认使用线上
*/
// String env = "rc";
// if (!StringUtils.isEmpty(executionApi.getEnv())) {
// env = executionApi.getEnv();
// } /*else if (executionApi.getTerminal().equals("M")) {
// env = "rc";
// } */
// 本地执行时使用
// String env = "prod";
// 防止多个工程运行时,环境变量名冲突
// 服务器集成测试配置
String env = System.getenv("env");
logger.info(env);
host = prop.getProperty(env);
// 预置登陆信息
CommonLoginInfo loginInfoMap = (CommonLoginInfo) SpringContextUtil.getBean("commonLoginInfoMap");
loginInfo = loginInfoMap.get(executionApi.getLoginUser());
if (StringUtils.isEmpty(loginInfo.getToken())) {
CommonLogin common_login = new CommonLogin();
common_login.login(env, executionApi.getLoginUser(), executionApi.getTerminal());
loginInfo = loginInfoMap.get(executionApi.getLoginUser());
}
// 组装URL
url = host + api.getString("apiPath") + loginInfo.getCommonParam(executionApi.getTerminal());
executionApi.setUrl(url);
// 请求头设置
if ("B".equals(executionApi.getTerminal())) {
executionApi.getHeadrs().put("tenant", loginInfo.getTenant());
executionApi.getHeadrs().put("adminId", loginInfo.getAdminId());
executionApi.getHeadrs().put("token", loginInfo.getToken());
executionApi.getHeadrs().put("user", loginInfo.getUser());
executionApi.getHeadrs().put("usertype", "B");
}
executionApi.getHeadrs().put("xm_request_source", "TestGetAdmin");
executionApi.getHeadrs().put("User-Agent", "XMSport/1.0 (com.jiejing.sport; build:1; iOS 15.8.1) Alamofire/5.8.0");
executionApi.getHeadrs().put("Accept", "*/*");
executionApi.getHeadrs().put("Connection", "Keep-Alive");
executionApi.getHeadrs().put("domain", "FITNESS_ADMIN");
// 接口未设置请求头,则默认为 application/json
if (api.containsKey("apiContentType") || StringUtils.isEmpty(api.getString("apiContentType"))) {
executionApi.getHeadrs().put("Content-type", "application/json;charset=utf-8");
} else {
executionApi.getHeadrs().put("Content-type", api.getString("apiContentType"));
}
}
/**
* @param xmAppApi
* @param requestType 请求类型
*/
public XMAppApi doRequest(XMAppApi xmAppApi,String requestType) {
OkHttpClient okHttpClient = new OkHttpClient();
switch (requestType) {
case "JSON":
okHttpClient.doPostRequest(xmAppApi.getUrl(), xmAppApi.getDataJson(), xmAppApi.getHeadrs());
break;
case "PARAM":
okHttpClient.doPostRequest(xmAppApi.getUrl(), xmAppApi.getParams(), xmAppApi.getHeadrs());
break;
case "FORM":
okHttpClient.doPostForForm(xmAppApi.getUrl(), xmAppApi.getParams(), xmAppApi.getHeadrs());
break;
case "GET":
okHttpClient.doGetRequest(xmAppApi.getUrl(), xmAppApi.getParams(), xmAppApi.getHeadrs());
break;
}
Map<String, String> head = okHttpClient.getHeaders();
String response = okHttpClient.getBody();
xmAppApi.setApi_response(response) ;
xmAppApi.setApi_traceId(head.get("traceId")) ;
xmAppApi.setApi_request_data(xmAppApi.getDataJson());
xmAppApi.setApi_request_params(xmAppApi.getParams());
xmAppApi.setApi_request_headers(head) ;
apiResult.setApi_response(response) ;
apiResult.setApi_traceId(head.get("traceId")) ;
apiResult.setApi_request_data(xmAppApi.getDataJson());
apiResult.setApi_request_params(xmAppApi.getParams());
apiResult.setApi_request_headers(head) ;
return xmAppApi;
}
@AfterMethod
public void afterMethod(ITestResult result) {
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Host",apiResult.getUrl()));
params.add(new BasicNameValuePair("traceId",apiResult.getApi_traceId()));
params.add(new BasicNameValuePair("RequestParams",apiResult.getApi_request_params().toString()));
params.add(new BasicNameValuePair("RequestData",apiResult.getApi_request_data()));
params.add(new BasicNameValuePair("Response",apiResult.getApi_response()));
result.setParameters(params.toArray());
result.setAttribute("ApiDesc",apiResult.getApiDesc());
}
@AfterClass
public static void afterClass() {
httpclient.shutDownConnection();
sslhttpclient.shutDownConnection();
}
}
package com.xiaomai.client;
import com.xiaomai.enums.Terminal;
import com.xiaomai.jdbc.dao.DataDao;
import com.xiaomai.jdbc.entity.ApiInfo;
import com.xiaomai.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Properties;
public class BaseTest extends AbstractTestNGSpringContextTests {
private static final Log logger = LogFactory.getLog(XMBaseTest.class);
private static DataDao dataDao;
public static RestfulClient httpclient = null;
public static SSLRestfulClient sslhttpclient = null;
public static OkHttpClient okHttpClient = null;
public static HashMap<String, String> headers;
public static IdentityHashMap<String, String> params;
// 该map 主要用于rest-assured 风格请求参数组装预置对象
public static Map restParams;
public static Map miniAppRestParams;
public static Map restParamsAnother;
private static String host = null;
public static String url = null;
private Properties prop = null;
public static UtDal dal;
public static volatile XMAppApi xmAppApi;
//private static CommonRequestParameters loginInfo;
public static CommonRequestParameters loginInfo;
// 支持业务数据方法参数
public static HashMap<String, String> dataheadrs;
public static IdentityHashMap<String, String> dataparams;
public static XMAppApi dataApi;
private static final Logger LOGGER = LoggerFactory.getLogger(BaseTest.class);
public BaseTest() {
}
@BeforeClass
public static void beforeClass() {
httpclient = new RestfulClient();
sslhttpclient = new SSLRestfulClient();
okHttpClient = new OkHttpClient();
xmAppApi = new XMAppApi();
dal = new UtDal();
//loginInfo=new CommonRequestParameters();
}
/**
* 测试接口调用API
*/
@BeforeMethod
public void beforeTest() {
// 每次执行测试case 前,初始化公共信息对象
params = new IdentityHashMap<>();
restParams = new HashMap();
miniAppRestParams = new HashMap();
restParamsAnother = new HashMap();
dataparams = new IdentityHashMap<>();
dataApi = new XMAppApi();
clearApiData(xmAppApi);// 清空上次API调用信息
headers = new HashMap<String, String>();
dataPreparation(xmAppApi, headers);
}
private void clearApiData(XMAppApi api) {
api.setApi_request_params(new IdentityHashMap());
api.setApi_request_data(null);
api.setApi_request_headers(new HashMap<>());
api.setApi_response(null);
api.setApi_traceId(null);
}
/**
* 数据业务方法调用 可选参数userInfos 测试时需要切换端位时传入要登录的user信息
*/
public void beforeDataRequest(DataUserInfo... userInfos) {
clearApiData(dataApi);// 清空上次API调用信息
dataheadrs = new HashMap<String, String>();
// 默认同端位接口调用, dataApi 使用被测试接口信息里的 登录信息
dataApi.setLoginUser(xmAppApi.getLoginUser()) // http 接口,测试账号
.setTerminal(xmAppApi.getTerminal());
// 支持切换端位调用
if (userInfos.length > 0) {
DataUserInfo info = userInfos[0];
Assert.assertNotNull(info, "userInfos 为空!!!");
if (!StringUtils.isEmpty(info.getLoginUser())) {
dataApi.setLoginUser(info.getLoginUser());
}
if (!StringUtils.isEmpty(info.getTerminal())) {
dataApi.setTerminal(info.getTerminal());
}
}
dataPreparation(dataApi, dataheadrs);
}
/**
* 业务API调用专用
*/
private void dataPreparation(XMAppApi executionApi, HashMap<String, String> executionHeaders) {
Assert.assertNotNull(executionApi.getApiModule(), "必要的api信息不存在!");
prop = CommUtil.getconfig();
dataDao = (DataDao) SpringContextUtil.getBean("dataDao");
ApiInfo apiInfo = dataDao.getApiInfo(executionApi.getApiModule(), executionApi.getApiName());
Assert.assertNotNull(apiInfo, "接口信息不存在!");
executionApi.setRequestParamterTemplate(apiInfo.getRequestParameter());
executionApi.setApiDesc(apiInfo.getApi_name());
// 服务器集成测试配置
String env = System.getenv("env");
if (StringUtils.isBlank(env)) {
env = prop.getProperty("env");
}
logger.info(env);
host = prop.getProperty(env);
// 预置登陆信息
CommonLoginInfo loginInfoMap = (CommonLoginInfo) SpringContextUtil.getBean("commonLoginInfoMap");
loginInfo = loginInfoMap.get(executionApi.getLoginUser());
if (StringUtils.isEmpty(loginInfo.getToken())) {
CommonLogin common_login = new CommonLogin();
common_login.login(env, executionApi.getLoginUser(), executionApi.getTerminal());
loginInfo = loginInfoMap.get(executionApi.getLoginUser());
}
// 组装URL
url = host + apiInfo.getApi_path() + loginInfo.getCommonParam(executionApi.getTerminal());
executionApi.setUrl(url);
// 业务url
logger.info("业务请求URL==>>" + url);
// 请求头设置
if ("B".equals(executionApi.getTerminal())) {
executionHeaders.put("tenant", loginInfo.getTenant());
executionHeaders.put("adminId", loginInfo.getAdminId());
executionHeaders.put("token", loginInfo.getToken());
executionHeaders.put("user", loginInfo.getUser());
executionHeaders.put("usertype", "B");
}
executionHeaders.put("xm_request_source", "TestGetAdmin");
executionHeaders.put("User-Agent", "XMSport/1.0 (com.jiejing.sport; build:1; iOS 15.8.1) Alamofire/5.8.0");
executionHeaders.put("Accept", "*/*");
executionHeaders.put("domain", "FITNESS_ADMIN");
executionHeaders.put("Connection", "Keep-Alive");
// 接口未设置请求头,则默认为 application/json
/* if (api.containsKey("apiContentType") || StringUtils.isEmpty(api.getString("apiContentType"))) {
executionHeaders.put("Content-type", "application/json;charset=utf-8");
} else {
executionHeaders.put("Content-type", api.getString("apiContentType"));
}*/
if (StringUtils.isEmpty(apiInfo.getApi_contentType())) {
executionHeaders.put("Content-type", "application/json;charset=utf-8");
} else {
executionHeaders.put("Content-type", apiInfo.getApi_contentType());
}
}
@AfterMethod
public void afterMethod(ITestResult result) {
result.setAttribute("ApiDesc", xmAppApi.getApiDesc());
// 请求属性
result.setAttribute("Url", xmAppApi.getUrl());
result.setAttribute("RequestParams", xmAppApi.getApi_request_params().toString());
result.setAttribute("RequestData", xmAppApi.getApi_request_data());
// 测试报告添加caseOwner属性
result.setAttribute("CaseOwner", dal.getCase_owner());
result.setAttribute("TraceId", xmAppApi.getApi_traceId());
if (xmAppApi.getApi_startTime() != null) {
// 请求开始时间和结束时间
result.setAttribute("StartTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(xmAppApi.getApi_startTime()));
}
// params.add(new BasicNameValuePair("EndTime",new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(xmAppApi.getApi_endTime())));
Long expendTime = xmAppApi.getApi_requestTime();
result.setAttribute("ExpendTime", expendTime + "ms");
result.setAttribute("Response", xmAppApi.getApi_response());
// 打印异常请求
if (expendTime != null) {
if (expendTime >= 500 && expendTime <= 1000) {
LOGGER.warn(xmAppApi.getApiDesc() + "接口请求时间超过500毫秒 = " + expendTime.toString());
} else if (expendTime > 1000) {
LOGGER.error(xmAppApi.getApiDesc() + " 接口请求时间超过1秒 = " + expendTime.toString());
}
}
}
@AfterClass
public static void afterClass() {
httpclient.shutDownConnection();
sslhttpclient.shutDownConnection();
}
}
package com.xiaomai.client;
/**
* 多个端位切换调用接口, 使用此对象完成登录端位信息切换
*/
public class DataUserInfo {
private String loginUser; // 登录人
private String Terminal; // 登录端位
private String apiModule; // 登录模块
@Deprecated
private String env;
public String getLoginUser() {
return loginUser;
}
public void setLoginUser(String loginUser) {
this.loginUser = loginUser;
}
public String getTerminal() {
return Terminal;
}
public void setTerminal(String terminal) {
Terminal = terminal;
}
public String getApiModule() {
return apiModule;
}
public void setApiModule(String apiModule) {
this.apiModule = apiModule;
}
@Deprecated
public String getEnv() {
return env;
}
@Deprecated
public void setEnv(String env) {
this.env = env;
}
}
package com.xiaomai.client;
import io.restassured.response.Response;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import static com.xiaomai.client.BaseTest.xmAppApi;
import static io.restassured.RestAssured.given;
/**
* 封装RestAssuredRequest 类型的请求
*/
public class RestAssuredRequest {
/**
* 发送get请求
* @param params
* @param headers
* @param url
* @return
*/
public static Response doGetRequestRA(IdentityHashMap<String, String> params, HashMap<String,String> headers, String url){
Response response = given()
.queryParams(params)
.headers(headers)
.when()
.get(url)
.then().log().all().extract().response();
// 提取报告内容
setReporterInfo(response,headers);
return response;
}
/**
* json格式参数post请求
* @param params
* @param headers
* @param bodydata
* @param url
* @return 返回响应结果
*/
public static Response doPostRequestRA(IdentityHashMap<String, String> params, HashMap<String,String> headers, String bodydata, String url){
Response response = given()
.queryParams(params)
.headers(headers)
.body(bodydata)
.when()
.post(url)
.then().log().all().extract().response();
// 提取报告内容
setReporterInfo(response,bodydata,headers);
return response;
}
/**
* 没有请求头
* @param headers
* @param bodydata
* @param url
* @return
*/
public static Response doPostRequestRA(HashMap<String,String> headers, String bodydata, String url){
Response response = given()
.headers(headers)
.body(bodydata)
.when()
.post(url)
.then().log().all().extract().response();
setReporterInfo(response,bodydata,headers);
return response;
}
/**
* 没有请求参数
* @param headers
* @param url
* @return
*/
public static Response doPostRequestRA(IdentityHashMap<String, String> params,HashMap<String,String> headers, String url){
Response response = given()
.queryParams(params)
.headers(headers)
.when()
.post(url)
.then().log().all().extract().response();
setReporterInfo(response,headers);
return response;
}
/**
* headers 增加appId
* @param headers
* @param bodydata
* @param url
* @return
*/
public static Response doPostRequestRA(Map<String, String> params, HashMap<String,String> headers, String bodydata, String url){
Response response = given()
.queryParams(params)
.headers(headers)
.header("appId","wxdd6b458500d4c224")
.body(bodydata)
.when()
.post(url)
.then().log().all().extract().response();
setReporterInfo(response,headers);
return response;
}
/**
* headers 增加appId,没有请求body
* @param headers
* @param url
* @return
*/
public static Response doPostRequestRA(HashMap<String,String> headers, String url){
Response response = given()
.headers(headers)
.header("appId","wxdd6b458500d4c224")
.when()
.post(url)
.then().log().all().extract().response();
setReporterInfo(response,headers);
return response;
}
/**
* 设置测试报告提取信息
* @param response 请求结果
* @param bodydata 请求数据
* @param headers 请求头
*/
public static void setReporterInfo(Response response, String bodydata, HashMap<String, String> headers){
// 提取报告内容
xmAppApi.setApi_response(response.asString()) ;// 请求结果
xmAppApi.setApi_traceId(response.getHeader("traceId")) ;// 结果traceId
xmAppApi.setApi_request_data(bodydata); // 请求体
xmAppApi.setApi_request_headers(headers) ;
}
public static void setReporterInfo(Response response, HashMap<String, String> headers){
// 提取报告内容
xmAppApi.setApi_response(response.asString()) ;// 请求结果
xmAppApi.setApi_traceId(response.getHeader("traceId")) ;// 结果traceId
xmAppApi.setApi_request_headers(headers) ;
}
}
package com.xiaomai.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class RestfulClient {
CloseableHttpClient httpclient= HttpClients.createDefault();
HttpGet httpGet;
HttpPost httpPost;
CloseableHttpResponse httpResponse;
int responseCode;
JSONObject responseBody;
HashMap<String, String> responseHeads;
public void doPutRequest(){
//todo
}
public void doDeleteRequest(){
//todo
}
/**
* json格式参数post请求
* @param url
* @param jsonDate
* @param headers
*/
/** 适用所有post的请求 **/
/** 发送json请求 */
public void doPostRequest(String url,List<NameValuePair> params,String json,HashMap<String, String> headers) {
// CloseableHttpClient hp = createSSLClientDefault();
httpPost = new HttpPost(url);
try {
// 设置请求主体格式
try {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Set<String> set= headers.keySet();
for (Iterator<String> iterator= set.iterator();iterator.hasNext();){
String key = iterator.next();
String value=headers.get(key);
httpPost.addHeader(key,value);
}
if(json.length() != 0) {
// json传递
StringEntity postingString = new StringEntity(json, "utf-8");
httpPost.setEntity(postingString);
}
httpResponse=httpclient.execute(httpPost);
}catch (Exception e){
e.getMessage();
}finally {
try {
httpclient.close();
}catch (Exception e){
System.out.println("httpclient执行异常:"+e.getMessage());
}
}
}
/**
* 通过httpclient获取post请求的反馈
* @param url
* @param params
* @param headers
*/
public void doPostRequest(String url, List<NameValuePair> params,
HashMap<String, String> headers) {
// 创建请求对象
httpPost =new HttpPost(url);
// 设置请求主体格式
try {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 设置请求头信息
Set<String> set= headers.keySet();
for (Iterator<String> iterator= set.iterator();iterator.hasNext();){
String key = iterator.next();
String value=headers.get(key);
httpPost.addHeader(key,value);
}
try {
httpResponse=httpclient.execute(httpPost);
} catch (IOException e) {
System.out.println("httpclient执行doPostRequest异常:"+e.getMessage());
}
}
/**
* 通过httpclient获取post请求的反馈
* @param url
* @param
* @param headers
*/
public void doGetRequest(String url,
HashMap<String, String> headers) {
// 创建请求对象
httpGet =new HttpGet(url);
// 设置请求头信息
Set<String> set= headers.keySet();
for (Iterator<String> iterator= set.iterator();iterator.hasNext();){
String key = iterator.next();
String value=headers.get(key);
httpGet.addHeader(key,value);
}
try {
httpResponse=httpclient.execute(httpGet);
} catch (IOException e) {
System.out.println("httpclient执行doPostRequest异常:"+e.getMessage());
}
}
/**
* 通过httpclient获取请求的反馈
* @param url
*/
public void doGetRequest(String url) {
httpGet=new HttpGet(url);
try {
httpResponse=httpclient.execute(httpGet);
} catch (IOException e) {
System.out.println("httpclient执行doGetRequest异常:"+e.getMessage());
}
}
/**
* 以JSON格式获取到反馈的主体
* @return
*/
public JSONObject getBodyInJSON() {
HttpEntity entity;
String entityToString = null;
if (httpResponse!= null){
entity = httpResponse.getEntity();
try {
entityToString = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
try {
responseBody = JSON.parseObject(entityToString);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("===============================================\n");
System.out.println("This is your response body ==> " + responseBody);
}else {
responseBody=null;
}
return responseBody;
}
/**
* 以String格式获取到反馈的主体
* @return
* @throws IOException
*/
public String getBody() {
HttpEntity entity;
String entityToString = null;
if (httpResponse!=null){
entity = httpResponse.getEntity();
try {
entityToString = EntityUtils.toString(entity);
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println("===============================================\n");
System.out.println("This is your response body ==> " + entityToString);
}else {
entityToString=null;
}
return entityToString;
}
/**
* 以哈希图的方式获取到反馈头部
* @return
*/
public HashMap<String,String> getHeaders(){
Header[] headers=httpResponse.getAllHeaders();
responseHeads= new HashMap<String,String>();
for (Header header:headers){
responseHeads.put(header.getName(),header.getValue());
}
System.out.println("===============================================\n");
System.out.println("This is your response header ==> " + responseHeads);
return responseHeads;
}
/**
* 获取反馈状态码
* @return
*/
public int getResponseCode(){
responseCode=httpResponse.getStatusLine().getStatusCode();
System.out.println("===============================================\n");
System.out.println("This is your response code ==> " + responseCode);
return responseCode;
}
public void shutDownConnection(){
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.xiaomai.client;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class Retry implements IRetryAnalyzer {
private int retryCount = 0;
private int maxRetryCount = 2;
@Override
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
System.out.println("Retrying TestGetAdmin " + result.getName() + " with status "
+ getResultStatusName(result.getStatus()) + " for the " + (retryCount + 1) + " time(s).");
retryCount++;
return true;
}
resetRetrycount(); // 每次跑完一条用例后,重置retryCount为0,这样dataProvider 数据驱动测试叶支持
return false;
}
public String getResultStatusName(int status) {
String resultName = null;
if (status == 1)
resultName = "SUCCESS";
if (status == 2)
resultName = "FAILURE";
if (status == 3)
resultName = "SKIP";
return resultName;
}
public boolean isRetryAvailable() {
return retryCount < maxRetryCount;
}
public void resetRetrycount() {
retryCount = 0;
}
}
\ No newline at end of file
package com.xiaomai.client;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class RetryListener implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation testannotation, Class testClass,
Constructor testConstructor, Method testMethod) {
IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
if (retry == null) {
testannotation.setRetryAnalyzer(Retry.class);
}
}
}
\ No newline at end of file
package com.xiaomai.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.utils.SSLClientCAR;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class SSLRestfulClient {
CloseableHttpClient sslhttpclient= SSLClientCAR.createSSLClientDefault();
HttpGet httpGet;
HttpPost httpPost;
CloseableHttpResponse httpResponse;
int responseCode;
JSONObject responseBody;
HashMap<String, String> responseHeads;
public void doPutRequest(){
//todo
}
public void doDeleteRequest(){
//todo
}
/**
* json格式参数post请求
* @param url
* @param jsonDate
* @param headers
*/
/** 适用所有post的请求 **/
/** 发送json请求 */
public void doPostRequest(String url, List<NameValuePair> params, String json, HashMap<String, String> headers) {
// CloseableHttpClient hp = createSSLClientDefault();
try {
// 设置请求主体格式
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.setParameters(params);
httpPost = new HttpPost(uriBuilder.build());
Set<String> set= headers.keySet();
for (Iterator<String> iterator = set.iterator(); iterator.hasNext();){
String key = iterator.next();
String value=headers.get(key);
httpPost.addHeader(key,value);
}
if(json.length() != 0) {
// json传递
StringEntity postingString = new StringEntity(json, "utf-8");
httpPost.setEntity(postingString);
}
httpResponse=sslhttpclient.execute(httpPost);
}catch (Exception e){
e.getMessage();
}finally {
try {
// sslhttpclient.close();
}catch (Exception e){
System.out.println("httpclient执行异常:"+e.getMessage());
}
}
}
/**
* 通过httpclient获取post请求的反馈
* @param url
* @param params
* @param headers
*/
public void doPostRequest(String url, List<NameValuePair> params,
HashMap<String, String> headers) {
// 创建请求对象
httpPost =new HttpPost(url);
// 设置请求主体格式
try {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 设置请求头信息
Set<String> set= headers.keySet();
for (Iterator<String> iterator= set.iterator();iterator.hasNext();){
String key = iterator.next();
String value=headers.get(key);
httpPost.addHeader(key,value);
}
try {
httpResponse=sslhttpclient.execute(httpPost);
} catch (IOException e) {
System.out.println("httpclient执行doPostRequest异常:"+e.getMessage());
}
}
/**
* 通过httpclient获取post请求的反馈
* @param url
* @param
* @param headers
*/
public void doGetRequest(String url,
HashMap<String, String> headers) {
// 创建请求对象
httpGet =new HttpGet(url);
// 设置请求头信息
Set<String> set= headers.keySet();
for (Iterator<String> iterator= set.iterator();iterator.hasNext();){
String key = iterator.next();
String value=headers.get(key);
httpGet.addHeader(key,value);
}
try {
httpResponse=sslhttpclient.execute(httpGet);
} catch (IOException e) {
System.out.println("httpclient执行doPostRequest异常:"+e.getMessage());
}
}
/**
* 通过httpclient获取请求的反馈
* @param url
*/
public void doGetRequest(String url) {
httpGet=new HttpGet(url);
try {
httpResponse=sslhttpclient.execute(httpGet);
} catch (IOException e) {
System.out.println("httpclient执行doGetRequest异常:"+e.getMessage());
}
}
/**
* 以JSON格式获取到反馈的主体
* @return
*/
public JSONObject getBodyInJSON() {
HttpEntity entity;
String entityToString = null;
if (httpResponse!= null){
entity = httpResponse.getEntity();
try {
entityToString = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
try {
responseBody = JSON.parseObject(entityToString);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("===============================================\n");
System.out.println("This is your response body ==> \n" + responseBody);
System.out.println("===============================================\n\n");
}else {
responseBody=null;
}
return responseBody;
}
/**
* 以String格式获取到反馈的主体
* @return
* @throws IOException
*/
public String getBody() {
HttpEntity entity;
String entityToString = null;
if (httpResponse!=null){
entity = httpResponse.getEntity();
try {
entityToString = EntityUtils.toString(entity);
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println("===============================================\n");
System.out.println("This is your response body ==> \n" + entityToString);
System.out.println("===============================================\n\n");
}else {
entityToString=null;
}
return entityToString;
}
/**
* 以哈希图的方式获取到反馈头部
* @return
*/
public HashMap<String,String> getHeaders(){
Header[] headers=httpResponse.getAllHeaders();
responseHeads= new HashMap<String,String>();
for (Header header:headers){
responseHeads.put(header.getName(),header.getValue());
}
System.out.println("===============================================\n");
System.out.println("This is your response header ==> \n" + responseHeads);
System.out.println("===============================================\n\n");
return responseHeads;
}
/**
* 获取反馈状态码
* @return
*/
public int getResponseCode(){
responseCode=httpResponse.getStatusLine().getStatusCode();
System.out.println("===============================================\n");
System.out.println("This is your response code ==> \n" + responseCode);
System.out.println("===============================================\n\n");
return responseCode;
}
public void shutDownConnection(){
try {
sslhttpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.xiaomai.client;
public class TestDal {
public String test_item;
public String device;
public String start_time;
public String tester;
public String case_name;
public String case_owner;
public StringBuilder failMessage;
public String fail_info;
public String end_time;
public String priority;
public String result;
public String title;
public String build_id;
public String random_id;
public TestDal(){}
public String getTest_item() {
return test_item;
}
public TestDal setTest_item(String test_item) {
this.test_item = test_item;
return this;
}
public String getDevice() {
return device;
}
public TestDal setDevice(String device) {
this.device = device;
return this;
}
public String getStart_time() {
return start_time;
}
public TestDal setStart_time(String start_time) {
this.start_time = start_time;
return this;
}
public String getTester() {
return tester;
}
public TestDal setTester(String tester) {
this.tester = tester;
return this;
}
public String getCase_name() {
return case_name;
}
public TestDal setCase_name(String case_name) {
this.case_name = case_name;
return this;
}
public String getCase_owner() {
return case_owner;
}
public TestDal setCase_owner(String case_owner) {
this.case_owner = case_owner;
return this;
}
public StringBuilder getFailMessage() {
return failMessage;
}
public TestDal setFailMessage(StringBuilder failMessage) {
this.failMessage = failMessage;
return this;
}
public String getFail_info() {
return fail_info;
}
public TestDal setFail_info(String fail_info) {
this.fail_info = fail_info;
return this;
}
public String getEnd_time() {
return end_time;
}
public TestDal setEnd_time(String end_time) {
this.end_time = end_time;
return this;
}
public String getPriority() {
return priority;
}
public TestDal setPriority(String priority) {
this.priority = priority;
return this;
}
public String getResult() {
return result;
}
public TestDal setResult(String result) {
this.result = result;
return this;
}
public String getTitle() {
return title;
}
public TestDal setTitle(String title) {
this.title = title;
return this;
}
public String getBuild_id() {
return build_id;
}
public TestDal setBuild_id(String build_id) {
this.build_id = build_id;
return this;
}
public String getRandom_id() {
return random_id;
}
public TestDal setRandom_id(String random_id) {
this.random_id = random_id;
return this;
}
}
package com.xiaomai.client;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import java.util.*;
import java.util.logging.Logger;
public class TestListener implements ITestListener {
private static Logger logger = Logger.getLogger(String.valueOf(ITestListener.class));
@Override
public void onFinish(ITestContext testContext) {
// super.onFinish(testContext);
// List of TestGetAdmin results which we will delete later
ArrayList<ITestResult> testsToBeRemoved = new ArrayList<ITestResult>();
// collect all id's from passed TestGetAdmin
Set<Integer> passedTestIds = new HashSet<Integer>();
for (ITestResult passedTest : testContext.getPassedTests().getAllResults()) {
logger.info("PassedTests = " + passedTest.getName());
passedTestIds.add(getId(passedTest));
}
Set<Integer> failedTestIds = new HashSet<Integer>();
for (ITestResult failedTest : testContext.getFailedTests().getAllResults()) {
logger.info("failedTest = " + failedTest.getName());
// id = class + method + dataprovider
int failedTestId = getId(failedTest);
// if we saw this TestGetAdmin as a failed TestGetAdmin before we mark as to be
// deleted
// or delete this failed TestGetAdmin if there is at least one passed
// version
if (failedTestIds.contains(failedTestId) || passedTestIds.contains(failedTestId)) {
testsToBeRemoved.add(failedTest);
} else {
failedTestIds.add(failedTestId);
}
}
// finally delete all tests that are marked
for (Iterator<ITestResult> iterator = testContext.getFailedTests().getAllResults().iterator(); ((Iterator) iterator)
.hasNext();) {
ITestResult testResult = iterator.next();
if (testsToBeRemoved.contains(testResult)) {
logger.info("Remove repeat Fail Test: " + testResult.getName());
iterator.remove();
}
}
}
private int getId(ITestResult result) {
int id = result.getTestClass().getName().hashCode();
id = id + result.getMethod().getMethodName().hashCode();
id = id + (result.getParameters() != null ? Arrays.hashCode(result.getParameters()) : 0);
return id;
}
public void onTestStart(ITestResult result) {
}
public void onTestSuccess(ITestResult result) {
}
public void onTestFailure(ITestResult result) {
}
public void onTestSkipped(ITestResult result) {
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
public void onStart(ITestContext context) {
}
}
package com.xiaomai.client;
public class UtDal {
public String test_item;
public String device;
public String start_time;
public String getTest_item() {
return test_item;
}
public UtDal setTest_item(String test_item) {
this.test_item = test_item;
return this;
}
public String getDevice() {
return device;
}
public UtDal setDevice(String device) {
this.device = device;
return this;
}
public String getStart_time() {
return start_time;
}
public UtDal setStart_time(String start_time) {
this.start_time = start_time;
return this;
}
public String getTester() {
return tester;
}
public UtDal setTester(String tester) {
this.tester = tester;
return this;
}
public String getCase_name() {
return case_name;
}
public UtDal setCase_name(String case_name) {
this.case_name = case_name;
return this;
}
public String getCase_owner() {
return case_owner;
}
public UtDal setCase_owner(String case_owner) {
this.case_owner = case_owner;
return this;
}
public StringBuilder getFailMessage() {
return failMessage;
}
public UtDal setFailMessage(StringBuilder failMessage) {
this.failMessage = failMessage;
return this;
}
public String getFail_info() {
return fail_info;
}
public UtDal setFail_info(String fail_info) {
this.fail_info = fail_info;
return this;
}
public String getEnd_time() {
return end_time;
}
public UtDal setEnd_time(String end_time) {
this.end_time = end_time;
return this;
}
public String getPriority() {
return priority;
}
public UtDal setPriority(String priority) {
this.priority = priority;
return this;
}
public String getResult() {
return result;
}
public UtDal setResult(String result) {
this.result = result;
return this;
}
public String getTitle() {
return title;
}
public UtDal setTitle(String title) {
this.title = title;
return this;
}
public String getBuild_id() {
return build_id;
}
public UtDal setBuild_id(String build_id) {
this.build_id = build_id;
return this;
}
public String getRandom_id() {
return random_id;
}
public UtDal setRandom_id(String random_id) {
this.random_id = random_id;
return this;
}
public String tester;
public String case_name;
public String case_owner;
public StringBuilder failMessage;
public String fail_info;
public String end_time;
public String priority;
public String result;
public String title;
public String build_id;
public String random_id;
public String testApiPath;
public String testApiParam;
public String testApiResponse;
public String testApiTraceId;
public UtDal(){}
public String getTestApiPath() {
return testApiPath;
}
public void setTestApiPath(String testApiPath) {
this.testApiPath = testApiPath;
}
public String getTestApiParam() {
return testApiParam;
}
public void setTestApiParam(String testApiParam) {
this.testApiParam = testApiParam;
}
public String getTestApiResponse() {
return testApiResponse;
}
public void setTestApiResponse(String testApiResponse) {
this.testApiResponse = testApiResponse;
}
public String getTestApiTraceId() {
return testApiTraceId;
}
public void setTestApiTraceId(String testApiTraceId) {
this.testApiTraceId = testApiTraceId;
}
}
package com.xiaomai.enums;
/**
* API 模块名称 常量定义 可自己分模块自定义
* 如以后要在自己的业务线下划分多个模块,建议在自己业务线模块中单独维护
*/
public class ApiModule {
public static String Polar_Admin ="polar_admin";
}
\ No newline at end of file
package com.xiaomai.enums;
/**
* 测试运行环境常量
*/
public class Env {
public static String DEV= "dev";
public static String RC = "rc";
public static String PROD = "prod";
public static String GRAY ="gray";
}
package com.xiaomai.enums;
/**
* @Auther: pdd
* @Date: 2021/06/19/16:17
* @Description: 登录账号名称
*/
public class LoginAccount {
public static String XYM_DEV = "xym_dev";
}
package com.xiaomai.enums;
public class RequestType {
public static String JSON= "JSON";
public static String PARAM= "PARAM";
public static String FORM= "FORM";
public static String GET= "GET";
}
package com.xiaomai.enums;
/**
* 登录端位常量
*/
public class
Terminal {
public final static String B = "B";
public final static String C = "C";
public final static String minApp = "minApp";
}
package com.xiaomai.jdbc.dao;
import com.xiaomai.jdbc.entity.ApiInfo;
import com.xiaomai.jdbc.entity.UserInfo;
import java.util.List;
/**
* @Auther: pdd
* @Date: 2021/04/27/16:12
* @Description: 获取数据信息
*/
public interface DataDao {
/**
* @param userName
* @Description: 获取登录账号信息
* @Author: pdd
* @Date: 2021/4/27/16:09
*/
UserInfo getUserInfo(String userName, String env);
List<UserInfo> getUserInfos(String userType, String env);
/**
* @param apiModule
* @param apiName
* @Description: 获取测试接口信息
* @Author: pdd
* @Date: 2021/4/27/16:34
*/
ApiInfo getApiInfo(String apiModule, String apiName);
}
package com.xiaomai.jdbc.dao.impl;
import com.xiaomai.jdbc.dao.DataDao;
import com.xiaomai.jdbc.entity.ApiInfo;
import com.xiaomai.jdbc.entity.UserInfo;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
/**
* @Auther: pdd
* @Date: 2021/04/27/16:29
* @Description: 获取数据信息
*/
public class DataDaoImpl implements DataDao {
// 声明一个JdbcTmplate属性及其Setter方法
private static JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public UserInfo getUserInfo(String userName, String env) {
// 定义SQL
String sql = "SELECT * FROM user_info WHERE user_name = ? and env = ? limit 1";
// 定义数组来存放SQL语句中的参数
Object[] obj = new Object[]{userName, env};
RowMapper<UserInfo> rowMapper = new BeanPropertyRowMapper<>(UserInfo.class);
List<UserInfo> userInfos = this.jdbcTemplate.query(sql, obj, rowMapper);
return userInfos.size() > 0 ? userInfos.get(0) : null;
}
@Override
public List<UserInfo> getUserInfos(String userType, String env) {
// 定义SQL
String sql = "SELECT * FROM user_info WHERE user_type = ? and env = ? limit 1";
// 定义数组来存放SQL语句中的参数
Object[] obj = new Object[]{userType, env};
RowMapper<UserInfo> rowMapper = new BeanPropertyRowMapper<>(UserInfo.class);
List<UserInfo> userInfos = this.jdbcTemplate.query(sql, obj, rowMapper);
return userInfos;
}
/**
* @Description: 获取测试接口信息
* @Author: pdd
* @Date: 2021/4/27/16:09
*/
@Override
public ApiInfo getApiInfo(String apiModule, String apiName) {
// 定义SQL
String sql = "SELECT * FROM api_info WHERE api_module = ? and api_name = ? limit 1";
// 定义数组来存放SQL语句中的参数
Object[] obj = new Object[]{apiModule, apiName};
RowMapper<ApiInfo> rowMapper = new BeanPropertyRowMapper<>(ApiInfo.class);
List<ApiInfo> apiInfos = this.jdbcTemplate.query(sql, obj, rowMapper);
return apiInfos.size() > 0 ? apiInfos.get(0) : null;
}
}
package com.xiaomai.jdbc.entity;
/**
* @Auther: pdd
* @Date: 2021/04/27/16:00
* @Description: 测试接口信息
*/
public class ApiInfo {
String api_name;
String module;
String api_module;
String api_path;
String api_contentType;
String api_describe;
String requestParameter;
public String getApi_name() {
return api_name;
}
public void setApi_name(String api_name) {
this.api_name = api_name;
}
public String getModule() {
return module;
}
public void setModule(String business_module) {
this.module = module;
}
public String getApi_module() {
return api_module;
}
public void setApi_module(String api_module) {
this.api_module = api_module;
}
public String getApi_path() {
return api_path;
}
public void setApi_path(String api_path) {
this.api_path = api_path;
}
public String getApi_contentType() {
return api_contentType;
}
public void setApi_contentType(String api_contentType) {
this.api_contentType = api_contentType;
}
public String getApi_describe() {
return api_describe;
}
public void setApi_describe(String api_describe) {
this.api_describe = api_describe;
}
public String getRequestParameter() {
return requestParameter;
}
public void setRequestParameter(String requestParameter) {
this.requestParameter = requestParameter;
}
@Override
public String toString() {
return "ApiInfo{" +
"api_name='" + api_name + '\'' +
", business_module='" + module + '\'' +
", api_module='" + api_module + '\'' +
", api_path='" + api_path + '\'' +
", api_contentType='" + api_contentType + '\'' +
", api_describe='" + api_describe + '\'' +
", requestParameter='" + requestParameter + '\'' +
'}';
}
}
package com.xiaomai.jdbc.entity;
/**
* @Auther: pdd
* @Date: 2021/04/27/15:40
* @Description: 登录账号信息
*/
public class UserInfo {
String user_name;
String tenant;
String tenant_name;
String account_no;
String password;
String env;
String adminId;
String user;
String brandId;
String user_type;
String open_id;
String app_id;
String xcx_open_id;
String xm_token;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant_id) {
this.tenant = tenant_id;
}
public String getTenant_name() {
return tenant_name;
}
public void setTenant_name(String tenant_name) {
this.tenant_name = tenant_name;
}
public String getAccount_no() {
return account_no;
}
public void setAccount_no(String account_no) {
this.account_no = account_no;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
public String getAdminId() {
return adminId;
}
public void setAdminId(String adminId) {
this.adminId = adminId;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getBrandId() {
return brandId;
}
public void setBrandId(String brandId) {
this.brandId = brandId;
}
public String getUser_type() {
return user_type;
}
public void setUser_type(String user_type) {
this.user_type = user_type;
}
public String getOpen_id() {
return open_id;
}
public void setOpen_id(String open_id) {
this.open_id = open_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getXcx_open_id() {
return xcx_open_id;
}
public void setXcx_open_id(String xcx_open_id) {
this.xcx_open_id = xcx_open_id;
}
public String getXm_token() {
return xm_token;
}
public void setXm_token(String xm_token) {
this.xm_token = xm_token;
}
@Override
public String toString() {
return "UserInfo{" +
"user_name='" + user_name + '\'' +
", tenant='" + tenant + '\'' +
", account_no='" + account_no + '\'' +
", password='" + password + '\'' +
", env='" + env + '\'' +
", adminId='" + adminId + '\'' +
", user='" + user + '\'' +
", brandId='" + brandId + '\'' +
", user_type='" + user_type + '\'' +
", open_id='" + open_id + '\'' +
", app_id='" + app_id + '\'' +
", xcx_open_id='" + xcx_open_id + '\'' +
", xm_token='" + xm_token + '\'' +
'}';
}
}
package com.xiaomai.utils;
import org.json.JSONException;
import org.skyscreamer.jsonassert.JSONAssert;
public class AssertforJson {
public static void assertResult(String result, String CaseName, boolean strict) {
JsonAndFile.WriteStringToFile(result,CaseName);
String expected = JsonAndFile.readFileToString(CaseName);
try {
JSONAssert.assertEquals(expected, result, strict);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
package com.xiaomai.utils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class CommUtil {
public static String getCurrentTime() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.toString();
}
public static String getTimeStamp() {
Long ct = System.currentTimeMillis();
return ct.toString();
}
/**
* 获取配置文件指出参数信息
*
* @return 返回一个文件对象
*/
public static Properties getconfig() {
Properties prop = null;
try {
// 数据流的形式读取配置文件
prop = new Properties();
FileInputStream fis = new FileInputStream(System.getProperty("user.dir") +
"/src/main/resources/config.properties");
prop.load(fis);
} catch (Exception e) {
e.printStackTrace();
}
return prop;
}
//把JavaBean转化为map
public static Map<String, String> bean2map(Object bean) {
Map<String, String> map = new HashMap<>();
//获取JavaBean的描述器
try {
BeanInfo b = Introspector.getBeanInfo(bean.getClass(), Object.class);
//获取属性描述器
PropertyDescriptor[] pds = b.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String propertyName = pd.getName();
Method m = pd.getReadMethod();
Object properValue = m.invoke(bean);
if (null != properValue) {
map.put(propertyName, properValue.toString());
}
}
} catch (Exception e) {
return null;
} finally {
return map;
}
}
}
package com.xiaomai.utils;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.client.OkHttpClient;
import com.xiaomai.enums.Terminal;
import com.xiaomai.jdbc.dao.DataDao;
import com.xiaomai.jdbc.entity.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Properties;
/**
* 公共登录工具类
*/
@ContextConfiguration(locations = {"classpath:/spring-core.xml", "classpath:/applicationContext.xml"})
public class CommonLogin {
JsonAndFile fileHandle;
OkHttpClient okHttpClient;
// 组装请求
IdentityHashMap<String, String> params;
HashMap<String, String> headers;
String url;
Properties prop;
JSONObject body;
String token = "";
Logger logger = LoggerFactory.getLogger(CommonLogin.class);
/**
* @param env 登录环境
* @param loginUser 登录user
* @param loginTerminal 登录端位
*/
public void login(String env, String loginUser, String loginTerminal) {
headers = new HashMap<String, String>();
params = new IdentityHashMap<String, String>();
okHttpClient = new OkHttpClient();
prop = CommUtil.getconfig();
DataDao dataDao = (DataDao) SpringContextUtil.getBean("dataDao");
UserInfo userInfo = dataDao.getUserInfo(loginUser, env);
Assert.assertNotNull(userInfo, "找不到用户登录信息, 姓名" + loginUser + "; 环境:" + env + ",请检查是否已有保存登录账号信息。");
if (null != userInfo) {
String accountNo = userInfo.getAccount_no();
String host = prop.getProperty(env);
CommonLoginInfo loginInfoMap = (CommonLoginInfo) SpringContextUtil.getBean("commonLoginInfoMap");
if (Terminal.B.equals(loginTerminal)) {
// 设置请求头
headers.put("Content-type", "application/json;charset=utf-8");
headers.put("User-Agent", "XMSport/1.0 (com.jiejing.sport; build:1; iOS 15.8.1) Alamofire/5.8.0");
String tenant = userInfo.getTenant();
String adminId = userInfo.getAdminId();
String user = userInfo.getUser();
url = host + "/polar/anon/login/loginAdmin?sfl=0.0&sft=20.0&version=1.0&sfr=0.0&build=1&platform=iOS&sfb=0.0";
// B端登录URL
logger.info("B端登录URL==>>" + url);
String data = "{\"accountNo\":\"" + accountNo + "\",\"certificate\":\"0000\",\"loginTerm\":\"FITNESS_ADMIN_APP\",\"loginMode\":\"PHONE_AUTH_CODE\",\"serverType\": \"B_LOGIN\"}";
// 发起登录请求
okHttpClient.doPostRequest(url, data, headers);
body = okHttpClient.getBodyInJSON();
// 获取token
Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
token = body.getJSONObject("result").get("authToken").toString();
Assert.assertNotNull(token, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
CommonRequestParameters loginInfo = new CommonRequestParameters();
user = body.getJSONObject("result").get("userId").toString();
loginInfo.setDomain("FITNESS_ADMIN")
.setTenant(tenant)
.setToken(token)
.setUser(user)
.setAdminId(adminId)
.setAccountNo(accountNo);
loginInfoMap.add(loginUser,loginInfo);
} else {
logger.warn(env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:" + body.getString("message"));
}
} else {
logger.warn("账号信息不存在!");
}
}
}
package com.xiaomai.utils;
import org.springframework.test.context.ContextConfiguration;
import java.util.Hashtable;
@ContextConfiguration(locations = {"classpath:/spring-core.xml", "classpath:/applicationContext.xml"})
public class CommonLoginInfo {
private Hashtable<String, CommonRequestParameters> loginInfoMap ;
public Hashtable<String, CommonRequestParameters> getLoginInfoMap() {
return loginInfoMap;
}
public void setLoginInfoMap(Hashtable<String, CommonRequestParameters> loginInfoMap) {
this.loginInfoMap = new Hashtable<String, CommonRequestParameters>();
}
public void add(String loginUser, CommonRequestParameters loginInfo){
if(null == loginInfoMap){
loginInfoMap = new Hashtable<String, CommonRequestParameters>();
}
this.loginInfoMap.put(loginUser,loginInfo);
}
public CommonRequestParameters get(String loginUser){
if(null == loginInfoMap){
return new CommonRequestParameters();
}
if(null ==loginInfoMap.get(loginUser) ){
return new CommonRequestParameters();
}
return loginInfoMap.get(loginUser);
}
/**
* 获取登录信息user 未取到信息将自动返回一个 空对象。 使用时自行处理判断
* @param loginUser
* @return
*/
public static CommonRequestParameters getLoginUser(String loginUser){
CommonLoginInfo _loginInfoMap = (CommonLoginInfo) SpringContextUtil.getBean("commonLoginInfoMap");
CommonRequestParameters loginInfo = _loginInfoMap.get(loginUser);
return loginInfo;
}
}
package com.xiaomai.utils;
import com.alibaba.fastjson.JSONArray;
import com.xiaomai.enums.Terminal;
public class CommonRequestParameters {
private String user;
private String tenant;
private String adminId;
private String token;
private String brandId;
private String studioId;
public String getCommonRequestString() {
return null;
}
private JSONArray tenandInfos;
private String accountNo;
private String domain;
public String getCommonParam(String userType) {
if ("B".equals(userType)) {
return "?build=1&user="+user+"&tenant="+tenant+"&adminId="+adminId+"&domain="+domain+"&sft=20.0&sfr=0.0&token="+token+"&brandId="+brandId+"&studioId="+studioId+"&sfb=0.0&version=1.0&sfl=0.0&platform=iOS";
} else {
return "?";
}
}
public String getUser() {
return user;
}
public CommonRequestParameters setUser(String user) {
this.user = user;
return this;
}
public String getTenant() {
return tenant;
}
public CommonRequestParameters setTenant(String tenant) {
this.tenant = tenant;
return this;
}
public String getAdminId() {
return adminId;
}
public CommonRequestParameters setAdminId(String adminId) {
this.adminId = adminId;
return this;
}
public String getToken() {
return token;
}
public CommonRequestParameters setToken(String token) {
this.token = token;
return this;
}
public String getBrandId() {
return brandId;
}
public CommonRequestParameters setBrandId(String brandId) {
this.brandId = brandId;
return this;
}
public String getStudioId() {
return studioId;
}
public CommonRequestParameters setStudioId(String studioId) {
this.studioId = studioId;
return this;
}
public JSONArray getTenandInfos() {
return tenandInfos;
}
public CommonRequestParameters setTenandInfos(JSONArray tenandInfos) {
this.tenandInfos = tenandInfos;
return this;
}
public String getAccountNo() {
return accountNo;
}
public CommonRequestParameters setAccountNo(String accountNo) {
this.accountNo = accountNo;
return this;
}
public String getDomain() {
return domain;
}
public CommonRequestParameters setDomain(String domain) {
this.domain = domain;
return this;
}
}
package com.xiaomai.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.enums.ApiModule;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
/**
* @Auther: pdd
* @Date: 2020/12/30/17:46
* @Description: 统计API数量总量
*/
public class CountApi {
private static JsonAndFile fileHandle = new JsonAndFile();
public static List<File> getFiles(String path) {
File root = new File(path);
List<File> files = new ArrayList<File>();
if (!root.isDirectory()) {
files.add(root);
} else {
File[] subFiles = root.listFiles();
for (File f : subFiles) {
files.addAll(getFiles(f.getAbsolutePath()));
}
}
return files;
}
public static void writeApiInfo2DataBase() throws IOException {
String business_model = "god";
JdbcTemplate template = JDBCConnect.getTemplate();
String filePath ="\\src\\main\\resources\\apicase\\"+business_model;
List<File> files = getFiles( System.getProperty("user.dir")+filePath);
String configPath = "\\src\\main\\resources\\config.properties";
Properties versionProp = new Properties();
versionProp.load(new FileReader(new File(System.getProperty("user.dir")+configPath)));
for (File f : files) {
if ("commonParam.json".equals(f.getName())) {
continue;
}
String api_model = null;
// 获取文件路径
String absPath = f.getAbsolutePath();
String relativePath = absPath.replace(System.getProperty("user.dir"),"").replace("\\", "/");
Enumeration<?> names = versionProp.propertyNames();
// 根据文件路径循环遍历获取路径对应的api_model名字
while (names.hasMoreElements()){
String name = names.nextElement().toString();
String value = versionProp.getProperty(name);
if(relativePath.equals(value)){
api_model = name;
// 根据api_model名字映射ApiModele类的静态属性名。没有用到
Field[] fields =ApiModule.class.getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
try {
String fieldValue = field.get(ApiModule.class).toString();
if(fieldValue.equals(name)){
String fieldName = field.getName();
// api_model = fieldName;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
if(api_model == null){
continue;
}
String fileParam = JsonAndFile.readTxtFile(f);
JSONObject apis = JSON.parseObject(fileParam);
org.json.JSONObject jsonObject_apis = new org.json.JSONObject(apis);
Iterator iterator = jsonObject_apis.keys();
// api信息插入数据库
while(iterator.hasNext()){
String api_name = (String) iterator.next();
JSONObject apiInfo = apis.getJSONObject(api_name);
String api_path = apiInfo.getString("apiPath");
String api_contentType = apiInfo.getString("apiContentType");
String api_describe = apiInfo.getString("desc");
String api_name2 = apiInfo.getString("apiName");
template.update("INSERT INTO api_info(api_name,business_model,api_model,api_path,api_contentType,api_describe,api_name2) VALUES (?,?,?,?,?,?,?)",api_name,business_model,api_model,api_path,api_contentType,api_describe,api_name2);
}
}
}
public static void countApi(){
int total = 0;
StringBuffer bf = new StringBuffer();
List<File> files = getFiles( System.getProperty("user.dir")+"\\src\\main\\resources\\apicase\\god");
for (File f : files) {
if ("commonParam.json".equals(f.getName())) {
continue;
}
String fileParam = fileHandle.readTxtFile(f);
JSONObject apis = JSON.parseObject(fileParam);
total += apis.size();
bf.append(f.getName() + ":" + apis.size() +"\r\n");
System.out.println(f.getName() + ":" + apis.size());
}
System.out.println("总数:" + total);
bf.append("总数:" + total +"\r\n");
bf.append("统计日期:" + TimeUtils.getCurrentTimeString() +"\r\n");
fileHandle.writeTxt(System.getProperty("user.dir")+ "\\src\\main\\resources\\api-count.txt",bf.toString());
}
public static void main(String[] args) throws IOException{
writeApiInfo2DataBase();
}
}
package com.xiaomai.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @Auther: pdd
* @Date: 2021/03/22/16:33
* @Description: 统计计算当前API 覆盖率
*/
public class CountApiCover {
public static void main(String[] args) {
JsonAndFile fileHandle = new JsonAndFile();
List<String> strList = new ArrayList();
try {
//(文件完整路径),编码格式
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\pdd\\Desktop\\apis.csv"), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
strList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
List<String> coverApiList = new ArrayList<>();
List<File> files = CountApi.getFiles(System.getProperty("user.dir") + "\\src\\main\\resources\\apicase\\god");
int apitotal = 0;
int coverTotal = 0;
for (File f : files) {
if ("commonParam.json".equals(f.getName())) {
continue;
}
String fileParam = fileHandle.readTxtFile(f);
JSONObject apis = JSON.parseObject(fileParam);
apitotal += apis.size();
Set<String> keys = apis.keySet();
for (String key : keys) {
JSONObject api = apis.getJSONObject(key);
String apiPath = api.getString("apiPath");
if (strList.contains(apiPath)) {
coverTotal++;
coverApiList.add(apiPath);
}
}
}
StringBuffer bf = new StringBuffer();
bf.append("统计日期:" + TimeUtils.getCurrentTimeString() + "\r\n");
bf.append("当前完成API数:" + apitotal + "\r\n");
bf.append("当前覆盖完成数:" + coverTotal + "\r\n");
bf.append("API总数:" + strList.size() + "\r\n");
bf.append("覆盖占比:" + percentInstance(coverTotal, strList.size()) + "\r\n");
bf.append("覆盖完成API:" + "\r\n");
for (String a : strList) {
bf.append(a + "\r\n");
}
fileHandle.writeTxt(System.getProperty("user.dir") + "\\src\\main\\resources\\api-cover-count.txt", bf.toString());
}
public static String percentInstance(Integer detailTotalNumber, Integer totalNumber) {
Double bfTotalNumber = Double.valueOf(detailTotalNumber);
Double zcTotalNumber = Double.valueOf(totalNumber);
double percent = bfTotalNumber / zcTotalNumber;
//获取格式化对象
NumberFormat nt = NumberFormat.getPercentInstance();
//设置百分数精确度2即保留两位小数
nt.setMinimumFractionDigits(2);
return nt.format(percent);
}
}
package com.xiaomai.utils;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
/**
*
* 用于对Object进行解析并且转换成Map键值对的形式
*
*/
public class DatatUtils {
private static final String JAVAP = "java.";
private static final String JAVADATESTR = "java.util.Date";
/**
* 获取利用反射获取类里面的值和名称
*
* @param obj
* @return
* @throws IllegalAccessException
*/
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> clazz = obj.getClass();
System.out.println(clazz);
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
map.put(fieldName, value);
}
return map;
}
/**
* 利用递归调用将Object中的值全部进行获取
*
* @param timeFormatStr 格式化时间字符串默认<strong>2017-03-10 10:21</strong>
* @param obj 对象
* @param excludeFields 排除的属性
* @return
* @throws IllegalAccessException
*/
public static Map<String, String> objectToMapString(String timeFormatStr, Object obj, String... excludeFields) {
Map<String, String> map = new HashMap<String, String>();
if (excludeFields.length!=0){
List<String> list = Arrays.asList(excludeFields);
try {
objectTransfer(timeFormatStr, obj, map, list);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else{
try {
objectTransfer(timeFormatStr, obj, map,null);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return map;
}
/**
* 递归调用函数
*
* @param obj 对象
* @param map map
* @param excludeFields 对应参数
* @return
* @throws IllegalAccessException
*/
private static Map<String, String> objectTransfer(String timeFormatStr, Object obj, Map<String, String> map, List<String> excludeFields) throws IllegalAccessException {
boolean isExclude=false;
//默认字符串
String formatStr = "YYYY-MM-dd HH:mm:ss";
//设置格式化字符串
if (timeFormatStr != null && !timeFormatStr.isEmpty()) {
formatStr = timeFormatStr;
}
if (excludeFields!=null){
isExclude=true;
}
Class<?> clazz = obj.getClass();
//获取值
for (Field field : clazz.getDeclaredFields()) {
String fieldName = clazz.getSimpleName() + "." + field.getName();
//判断是不是需要跳过某个属性
if (isExclude&&excludeFields.contains(fieldName)){
continue;
}
//设置属性可以被访问
field.setAccessible(true);
Object value = field.get(obj);
Class<?> valueClass = value.getClass();
if (valueClass.isPrimitive()) {
map.put(fieldName, value.toString());
} else if (valueClass.getName().contains(JAVAP)) {//判断是不是基本类型
if (valueClass.getName().equals(JAVADATESTR)) {
//格式化Date类型
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
Date date = (Date) value;
String dataStr = sdf.format(date);
map.put(fieldName, dataStr);
} else {
map.put(fieldName, value.toString());
}
} else {
objectTransfer(timeFormatStr, value, map,excludeFields);
}
}
return map;
}
}
\ No newline at end of file
package com.xiaomai.utils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelProcess {
public Object[][] proessExcel(String filePath,int sheetId) {
// 数据流读入excel
File file= new File(System.getProperty("user.dir")+filePath);
FileInputStream fis= null;
HSSFWorkbook wb =null;
try {
fis = new FileInputStream(file);
wb = new HSSFWorkbook(fis);
} catch (IOException e) {
e.printStackTrace();
}
//读取特定表单,并计算行列数
HSSFSheet sheet=wb.getSheetAt(sheetId);
int numberOfRow =sheet.getPhysicalNumberOfRows();
int numberOfCell =sheet.getRow(0).getLastCellNum();
//将表单数据处理存入dtt对象
Object[][] dttData=new Object[numberOfRow][numberOfCell];
for(int i=0;i<numberOfRow;i++){
if(null==sheet.getRow(i)||"".equals(sheet.getRow(i))){
continue;
}
for(int j=0;j<numberOfCell;j++) {
if(null==sheet.getRow(i).getCell(j)||"".equals(sheet.getRow(i).getCell(j))){
continue;
}
HSSFCell cell = sheet.getRow(i).getCell(j);
cell.setCellType(CellType.STRING);
dttData[i][j] = cell.getStringCellValue();
}
}
return dttData;
}
}
package com.xiaomai.utils;
import java.io.File;
/**
* 用来统计api 个数
*/
public class GetFilesNum {
public static int num = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println( show (new File("src/main/java/com/xiaomai/cases")));
}
public static int show(File file) {
// TODO Auto-generated method stub
for(File f : file.listFiles()) {
if(f.isFile()) {
if(f.getName().startsWith("Test")) {
num++;
}
}else {
show(f);
}
}
return num;
}
}
package com.xiaomai.utils;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class JDBCConnect {
public void testjdbc(){
JdbcTemplate template = JDBCConnect.getTemplate();
List userInfoList = template.queryForList("select * from `api_info`");
System.out.println(userInfoList);
}
public static JdbcTemplate getTemplate(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://120.27.248.253:3306/xm_sports");
dataSource.setName("TestGetAdmin");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
return new JdbcTemplate(dataSource);
}
}
package com.xiaomai.utils;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@Configuration
@PropertySource("classpath:/jdbc.properties")
public class JdbcConfiguration {
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.initialSize}")
private int initialSize;
@Value("${jdbc.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${jdbc.maxWait}")
private int maxWait;
@Bean
public DataSource getDataSource(){
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
dataSource.setMaxActive(this.initialSize);
dataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
dataSource.setMaxWait(this.maxWait);
return dataSource;
}
}
package com.xiaomai.utils;
import java.io.*;
public class JsonAndFile {
/**
* 读文件
* @return
*/
public static String readFileToString(String caseName) {
String fileName = String.format("%s_basedata.html", caseName);
int len = 0;
StringBuffer str = new StringBuffer();
File file = new File("src/main/resources/baseresult/" + fileName);
try {
FileInputStream is = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String line = null;
while ((line = in.readLine()) != null) {
if (len != 0) { // 处理换行符的问题
str.append("\r\n" + line);
} else {
str.append(line);
}
len++;
}
in.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
/**
* 写文件
* @param data
*/
public static void WriteStringToFile(String data,String caseName) {
String fileBaseDataName = String.format("%s_basedata.html", caseName);
File fileBase = new File("src/main/resources/baseresult/" + fileBaseDataName);
System.out.println(fileBase.getPath());
if (!fileBase.exists()) { //如果存在不写入
try {
FileOutputStream fos = new FileOutputStream(fileBase.getPath());
String s = data;
if (s.isEmpty()){
return;
}else {
fos.write(s.getBytes());
System.out.println("写入" + fileBaseDataName + "成功!");
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
String fileContrastDataName=String.format("%s_contrastdata.html", caseName);
File fileContrast = new File("src/main/resources/contrastresult/" + fileContrastDataName);
FileOutputStream fos = new FileOutputStream(fileContrast.getPath());
String s = data;
if (s.isEmpty()){
return;
}else {
fos.write(s.getBytes());
System.out.println("写入" + fileContrastDataName + "成功!");
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 数据写入txt文件中
* @param txtPath duwen
* @return
*/
public static String readTxtFile(String txtPath){
// String txtPath = "../../resources/token.txt";
File file = new File(txtPath);
if(file.isFile() && file.exists()){
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
// InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
StringBuffer sb = new StringBuffer();
String text = null;
while((text = bufferedReader.readLine()) != null){
sb.append(text);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static String readTxtFile(File file){
// String txtPath = "../../resources/token.txt";
if(file.isFile() && file.exists()){
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer();
String text = null;
while((text = bufferedReader.readLine()) != null){
sb.append(text);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 往txt文件中写入内容
* @param txtPath 写文件路径
* @param content 写入文件的内容
*/
public static void writeTxt(String txtPath,String content){
FileOutputStream fileOutputStream = null;
File file = new File(txtPath);
try {
if(file.exists()){
//判断文件是否存在,如果不存在就新建一个txt
file.createNewFile();
}
// fileOutputStream = new FileOutputStream(file,IsAppend);//多个true就是追加
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes("utf-8"));
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JsonAndFile filehandle = new JsonAndFile();
System.out.println(System.getProperty("user.dir")+"/src/main/resources/token.txt");;
// filehandle.writeTxt(System.getProperty("user.dir")+"/src/main/resources/token.txt","ttttttttttttttt");
String token = filehandle.readTxtFile(System.getProperty("user.dir")+"/src/main/resources/token.txt");
System.out.println(token);
}
}
\ No newline at end of file
package com.xiaomai.utils;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.jdbc.dao.DataDao;
import com.xiaomai.jdbc.entity.ApiInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.Assert;
/**
* 获取requestParamter
*
* @Author laosy
* @Date 2020/11/17 20:22
*/
public class ParamterTemplate {
public static JSONObject getApiParamterTemplate(String apiModule, String apiName) {
/* Assert.assertNotNull(apiModule, "必要的api信息不存在!");
Properties prop = CommUtil.getconfig();
JsonAndFile fileHandle = new JsonAndFile();
String apiModulePath = prop.getProperty(apiModule);
// 获取接口模块参数
String fileParam = fileHandle.readTxtFile(System.getProperty("user.dir") + apiModulePath);
Assert.assertNotNull(fileParam, "必要的API模块信息未找到,请检查api模块文件路径!");
JSONObject api = (JSONObject) JSON.parseObject(fileParam).get(apiName);
Assert.assertNotNull(api, "必要的API接口信息未找到,请检查apiName信息!");
if (api.containsKey("requestParamter")) {
*//* executionApi.setRequestParamterTemplate(api.getString("requestParamter"));*//*
}
return api.getJSONObject("requestParamter");*/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataDao dataDao = (DataDao) applicationContext.getBean("dataDao");
ApiInfo apiInfo = dataDao.getApiInfo(apiModule, apiName);
Assert.assertNotNull(apiInfo, "接口信息不存在!");
return JSONObject.parseObject(apiInfo.getRequestParameter());
}
}
package com.xiaomai.utils;
import org.springframework.util.StringUtils;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
public class RandomStringUtil {
/**
* @param string_length
* @param randomstring
* @return
*/
public static String randomNumber(int string_length, String randomstring) {
String chars = "1234567890";
int randomstring_lenth;
if (StringUtils.isEmpty(randomstring) || null == randomstring)
randomstring_lenth = 0;
else
randomstring_lenth = randomstring.length();
if (randomstring.length() >= string_length)
return "error:前缀字符不得长于总字符长度";
for (int i = 0; i < string_length - randomstring_lenth; i++) {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(chars.length());
randomstring += chars.substring(randomInt, randomInt + 1);
}
return randomstring;
}
public static String getTimestamp() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
long today_date = calendar.getTime().getTime();
return String.valueOf(today_date);
}
public static String getTimestampToPhone() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
long today_date = calendar.getTime().getTime();
String today_date_str = String.valueOf(today_date);
return today_date_str.substring(0, 11);
}
public static String randomMobile(String... randomstring) {
String str = "109";
if (randomstring.length > 0) {
str = randomstring[0];
}
return randomNumber(11, str);
}
public static String random_name() {
String names_first = "赵钱孙李周吴郑王杜贾谢林彭张陈何刘杨";
String names_last = "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
String names_num = "零一二三四五六七八九十";
String randomstring = "";
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(names_first.length());
randomstring += names_first.substring(randomInt, randomInt + 1);
randomInt = randomGenerator.nextInt(names_last.length());
randomstring += names_last.substring(randomInt, randomInt + 1);
randomInt = randomGenerator.nextInt(names_num.length());
randomstring += names_num.substring(randomInt, randomInt + 1);
return randomstring;
}
public static String randomString(int length) {
String str = "";
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghijklmnopqrstuvwxyz0123456789";
for (int i = 0; i < length; i++) {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(chars.length());
str += chars.substring(randomInt, randomInt + 1);
}
return str;
}
}
package com.xiaomai.utils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class SSLClientCAR {
public static CloseableHttpClient createSSLClientDefault(){
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
//信任所有
public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException{
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
}
package com.xiaomai.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.Locale;
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext contex)
throws BeansException
{
System.out.println("--------------------contex---------"+contex);
SpringContextUtil.context = contex;
}
public static ApplicationContext getApplicationContext() {
return context;
}
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
public static String getMessage(String key) {
return context.getMessage(key, null, Locale.getDefault());
}
}
package com.xiaomai.utils;
import com.xiaomai.client.BaseTest;
import org.springframework.test.context.ContextConfiguration;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
@ContextConfiguration(locations = {"classpath:/spring-core.xml", "classpath:/applicationContext.xml"})
public class XMBaseTest extends BaseTest {
@BeforeClass
public static void beforeClass() {
BaseTest.beforeClass();
}
@AfterClass
public static void afterClass() {
BaseTest.afterClass();
}
@BeforeMethod
public void beforeTest() {
super.beforeTest();
}
@AfterMethod
public void afterTest(ITestResult result) {
super.afterMethod(result);
}
}
package com.xiaomai.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.springframework.util.StringUtils;
/**
* 简单封装 根据 jsonPath 获取对象
*/
public class XMJSONPath {
public static String readPath(String jsonString, String path) {
if (StringUtils.isEmpty(jsonString)) {
return "";
} else {
try {
Object object = JSONPath.read(jsonString, path);
if (null == object) {
return "";
} else {
return object.toString();
}
} catch (Exception e) {
return "";
}
}
}
public static String readPath(JSONObject json, String path) {
if (null == json) {
return "";
} else {
try {
Object object = JSONPath.read(json.toJSONString(), path);
if (null == object) {
return "";
} else {
return object.toString();
}
} catch (Exception e) {
return "";
}
}
}
public static JSONObject getJSONObjectByReadPath(String jsonString, String path) {
if (StringUtils.isEmpty(jsonString)) {
return null;
} else {
try {
Object object = JSONPath.read(jsonString, path);
if (null == object) {
return null;
} else {
return (JSONObject) object;
}
} catch (Exception e) {
return null;
}
}
}
public static JSONArray getJSONArrayByReadPath(String jsonString, String path) {
if (StringUtils.isEmpty(jsonString)) {
return null;
} else {
try {
Object object = JSONPath.read(jsonString, path);
if (null == object) {
return null;
} else {
return (JSONArray) object;
}
} catch (Exception e) {
return null;
}
}
}
public static JSONObject getJSONObjectByReadPath(JSONObject json, String path) {
if (null == json) {
return null;
} else {
try {
Object object = JSONPath.read(json.toJSONString(), path);
if (null == object) {
return null;
} else {
return (JSONObject) object;
}
} catch (Exception e) {
return null;
}
}
}
public static JSONArray getJSONArrayByReadPath(JSONObject json, String path) {
if (null == json) {
return null;
} else {
try {
Object object = JSONPath.read(json.toJSONString(), path);
if (null == object) {
return null;
} else {
return (JSONArray) object;
}
} catch (Exception e) {
return null;
}
}
}
public static JSONObject getJSONObjectByKeyValue(JSONArray jsonArray, String key, String value) {
if (null == jsonArray) {
return null;
} else {
jsonArray.stream().filter(o -> {
JSONObject jsonObject = (JSONObject) o;
return jsonObject.getString(key).equals(value) ? true : false;
});
return jsonArray.getJSONObject(0);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 1.配置数据源 -->
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource">
<!-- 1.1.数据库驱动 -->
<property name="driverClassName"
value="${jdbc.driverClassName}"></property>
<!-- 1.2.连接数据库的url -->
<property name="url"
value="${jdbc.url}"></property>
<!-- 1.3.连接数据库的用户名 -->
<property name="username" value="${jdbc.username}"></property>
<!-- 1.4.连接数据库的密码 -->
<property name="password" value="${jdbc.password}"></property>
<property name="initialSize" value="${jdbc.initialSize}"></property>
<property name="maxWait" value="${jdbc.maxWait}"></property>
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"></property>
<property name="filters" value="${jdbc.filters}"></property>
</bean>
<!-- 2配置JDBC模板 -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义id为dataDao的Bean -->
<bean id="dataDao" class="com.xiaomai.jdbc.dao.impl.DataDaoImpl">
<!-- 将jdbcTemplate注入到dataDao实例中 -->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
\ No newline at end of file
{"result":{"current":"1","total":"0","pages":"1","size":"20","records":[],"hasNext":false},"code":"200","success":true,"message":"操作成功!"}
\ No newline at end of file
#默认执行环境
env=dev
# Dev
dev=https://dev-fit.xiaomai5.com
#rc
#rc=https://rc-heimdall.xiaomai5.com
# gray
#gray=https://gray-heimdall.xiaomai5.com
#prod
#prod=https://heimdall.xiaomai5.com
# 测试运行环境 本地调试时,可指定调试环境。完成本地调试后,请注释此变量
#runningEnv = gray
testData=\\src\\main\\resources\\dataprovider\\APIcase.xls
# �����˺�
testAccount=/src/main/resources/parameter.json
\ No newline at end of file
{
"msgtype": "markdown",
"markdown": {
"title":"接口自动化测试",
"text": "### 自动化测试报告\n> ![screenshot](http://47.98.129.121:5060/job/xm-autotest/ws/src/main/resources/lAHPDeC2umcJGVBKzQFq_362_74.gif)\n> #### [本报告仅支持内网查看,传送门DMXY>>](http://jenkins-test.ixm5.cn/job/xm-autotest/HTML_20Report/) \n"
}
}
\ No newline at end of file
# 数据库配置
#jdbc.name=TestGetAdmin
#jdbc.url=jdbc:mysql://10.158.0.123:3306/xm_data?characterEncoding=UTF-8
jdbc.username=qaman
jdbc.password=qaman
jdbc.url=jdbc:mysql://120.27.248.253:3306/xm_sports?characterEncoding=UTF-8
#jdbc.username=root
#jdbc.password=root
jdbc.driverClassName=com.mysql.jdbc.Driver
######################### 连接池的配置信息 #################
#初始化连接大小
jdbc.initialSize=5
#最小连接池数量
jdbc.minIdle=5
#最大连接池数量
jdbc.maxActive=20
#获取连接时最大等待时间,单位毫秒
jdbc.maxWait=30000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
jdbc.timeBetweenEvictionRunsMillis=30000
#配置一个连接在池中最小生存的时间,单位是毫秒
jdbc.minEvictableIdleTimeMillis=300000
#测试连接
jdbc.validationQuery=SELECT 1 FROM DUAL
#申请连接的时候检测,建议配置为true,不影响性能,并且保证安全性
jdbc.testWhileIdle=true
#获取连接时执行检测,建议关闭,影响性能
jdbc.testOnBorrow=false
#归还连接时执行检测,建议关闭,影响性能
jdbc.testOnReturn=false
#是否开启PSCache,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql下建议关闭
jdbc.poolPreparedStatements=false
#开启poolPreparedStatements后生效
jdbc.maxPoolPreparedStatementPerConnectionSize=20
#配置扩展插件,常用的插件有=>stat:监控统计 log4j:日志 wall:防御sql注入
jdbc.filters=stat,wall,log4j
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<!-- 日志输出的位置 -->
<Properties>
<!-- 保存在当前路径的logs文件夹下 -->
<Property name="basePath">./logs</Property>
</Properties>
<!-- 日志输出的位置 -->
<Appenders>
<!-- filePattern表示滚动一天记录日志命名 -->
<RollingFile name="file" fileName="${basePath}/test.log"
filePattern="${basePath}/test-%d{yyyy-MM-dd}.log">
<PatternLayout charset="UTF-8" pattern="%d{YYY-MM-dd-HH:mm:ss.SSS} %-5level %c{1} -%msg%n" />
<Policies>
<!-- interval="1"基于时间触发RollingFile 表示滚动一天记录日志 -->
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
</RollingFile>
<!-- 日志在控制台输出用 Console -->
<Console name="ConsoleOut">
<!-- 日志显示的风格 -->
<PatternLayout pattern="%d{YYY-MM-dd-HH:mm:ss。SSS} %-5level %c{1} -%msg%n" />
</Console>
</Appenders>
<Loggers>
<!-- 日志输出级别为info -->
<Root level="info">
<!-- 前面有定义RollingFile的名称为file -->
<AppenderRef ref="file" />
</Root>
</Loggers>
</Configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
">
<context:component-scan base-package="com.xiaomai.cases"></context:component-scan>
<!--<bean id="loginInfo" class="com.xiaomai.base.CommonRequestParameters"></bean>-->
<bean id="commonLoginInfoMap" class="com.xiaomai.utils.CommonLoginInfo"></bean>
<bean id="springContextUtil" class="com.xiaomai.utils.SpringContextUtil"></bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="XMAUTOTEST" parallel="classes" thread-count="20" >
<listeners>
<listener class-name="com.xiaomai.client.RetryListener" />
<listener class-name="com.xiaomai.client.TestListener" />
<listener class-name="com.xiaomai.client.ExtentTestNGIReporterListener"/>
</listeners>
<!-- 保证classes 文件优先执行 -->
<!--<TestGetAdmin name="makedata" preserve-order="true" verbose="3">
<classes>
<class name="com.xiaomai.cases.god.graden.SaveStudentAPI"/>
</classes>
</TestGetAdmin>-->
<suite-files >
<suite-file path="module/polar/整个模块.xml" ></suite-file>
</suite-files>
</suite>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment