Commit cd9a00f4 by fangyuan

add xm-testng

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
## xmautotest
http接口测试项目工程,完成dopost,doget 等接口请求。
### cases 存放测试代码 分模块请求
### client 存放测试基础类
### demo 存放模板测试方法
### utils 存放基础工具类
### application.properties 文件配置dubbo 配置
### config.properties 文件配置测试资源相关
### jdbc.xml 测试数据库连接池
### jdbc.properties 数据库基本信息配置
### testng.xml 配置自动化扫描测试类文件
### baseresult存放标准测试结果
### contrastresult存放请求结果与标准结果作对比
### dataprovider存放一个请求的模板化参数
### resources/ paramter.json 存放所有登录账号信息
### case 模块划分
### god ——> 教务
### money ——> 营销
### zeus ——> 家校
### cloudclass ——> 云课堂
### earth ——> 支持线
This diff is collapsed. Click to expand it.
package com.xiaomai.basetest;
import com.xiaomai.utils.XMBaseTest;
import org.testng.annotations.BeforeMethod;
/**
* @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;
}
@BeforeMethod
@Override
public void beforeTest() {
xmAppApi.setApiModule(getApiModuleName())
.setApiName(getApiName())
.setLoginUser(getLoginUser())
.setTerminal(getTerminal());
dal.setCase_owner(getCaseOwner());
super.beforeTest();
}
}
package com.xiaomai.basetest;
import org.testng.annotations.BeforeMethod;
/**
* @Auther: pdd
* @Date: 2020/11/24/20:58
* @Description:
*/
public interface BaseTestInterface {
public String getApiModuleName();
public String getApiName();
public String getLoginUser();
public String getTerminal();
public String getCaseOwner();
@BeforeMethod
public void beforeTest();
}
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());
}
}
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";
} */
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("instid", loginInfo.getInstId());
executionApi.getHeadrs().put("bizAccountId", loginInfo.getAid());
executionApi.getHeadrs().put("xmversion", "5.0");
executionApi.getHeadrs().put("vn", "5.4.0");
} else if ("M".equals(executionApi.getTerminal())) {
executionApi.getHeadrs().put("usertype", loginInfo.getUserType());
executionApi.getHeadrs().put("deptpath", loginInfo.getDeptpath());
}
executionApi.getHeadrs().put("xm_request_source", "test");
executionApi.getHeadrs().put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");
executionApi.getHeadrs().put("Accept", "*/*");
executionApi.getHeadrs().put("Connection", "Keep-Alive");
// 接口未设置请求头,则默认为 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;
/**
* 多个端位切换调用接口, 使用此对象完成登录端位信息切换
*/
public class DataUserInfo {
private String loginUser; // 登录人
private String Terminal; // 登录端位
@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;
}
@Deprecated
public String getEnv() {
return env;
}
@Deprecated
public void setEnv(String env) {
this.env = env;
}
}
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 test " + 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 test results which we will delete later
ArrayList<ITestResult> testsToBeRemoved = new ArrayList<ITestResult>();
// collect all id's from passed test
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 test as a failed test before we mark as to be
// deleted
// or delete this failed test 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;
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 M= "M";
public final static String B = "B";
public final static String C = "C";
public final static String minApp = "minApp";
public final static String APP_C = "app-c"; // 每课学堂 APP登录
}
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.io.FileInputStream;
import java.text.SimpleDateFormat;
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;
}
}
package com.xiaomai.utils;
import java.util.Hashtable;
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.xiaomai.enums.Terminal;
public class CommonRequestParameters {
private String p ;
private String xmversion;
private String b;
private String userType;
private String saasV;
private String vn;
private String deviceVersion;
private String v;
private String uid;
private String tid;
private String aid;
private String token;
private String accountNo;
private String instId;
// M 端接口参数
private String u;
private String authCode;
private String deptpath;
// C 端接口参数
private String wechatAppId;
private String openId;
public String getAccountNo() {
return accountNo;
}
public CommonRequestParameters setAccountNo(String accountNo) {
this.accountNo = accountNo;
return this;
}
public String getDeptpath() {
return deptpath;
}
public CommonRequestParameters setDeptpath(String deptpath) {
this.deptpath = deptpath;
return this;
}
public String getInstId() {
return instId;
}
public CommonRequestParameters setInstId(String instId) {
this.instId = instId;
return this;
}
public String getCommonRequestString (){
return null;
}
public String getCommonParam (String userType){
if("B".equals(userType)){
return "?p=w&v=v5.4.8&userType=B&token="+token+"&uid="+uid+"&tid="+tid+"&aid="+aid;
}else if("M".equals(userType)){
// M 端公共请求参数
return "?u="+u+"&token="+token+"&authCode="+authCode+"&uid="+uid;
}else if("C".equals(userType)){
// C端接口公共请求参数
return "?p=" + p +"&v="+v +"&uid="+uid+"&wechatAppId="+wechatAppId+"&token="+token+"&openId="+openId;
} else if("APP-B".equals(userType)){
// app-B 公共请求参数
return "?p=" + p + "&xmversion=" + xmversion + "&=" + "&b=" + b+ "&=userType" + userType
+ "&saasV=" + saasV + "&vn"+vn+"&deviceVersion="+deviceVersion+"&v="+v
+"&uid="+uid+"&tid="+tid+"&aid="+aid+"&token="+token;
} else if(Terminal.minApp.equals(userType)){
return "?p=" +p+"&uid="+uid+"&wechatAppId="+wechatAppId+"&token="+token+"&openId="+openId;
}else{
return "?";
}
}
public String getP() {
return p;
}
public CommonRequestParameters setP(String p) {
this.p = p;
return this;
}
public String getXmversion() {
return xmversion;
}
public CommonRequestParameters setXmversion(String xmversion) {
this.xmversion = xmversion;
return this;
}
public String getB() {
return b;
}
public CommonRequestParameters setB(String b) {
this.b = b;
return this;
}
public String getUserType() {
return userType;
}
public CommonRequestParameters setUserType(String userType) {
this.userType = userType;
return this;
}
public String getSaasV() {
return saasV;
}
public CommonRequestParameters setSaasV(String saasV) {
this.saasV = saasV;
return this;
}
public String getVn() {
return vn;
}
public CommonRequestParameters setVn(String vn) {
this.vn = vn;
return this;
}
public String getDeviceVersion() {
return deviceVersion;
}
public CommonRequestParameters setDeviceVersion(String deviceVersion) {
this.deviceVersion = deviceVersion;
return this;
}
public String getV() {
return v;
}
public CommonRequestParameters setV(String v) {
this.v = v;
return this;
}
public String getUid() {
return uid;
}
public CommonRequestParameters setUid(String uid) {
this.uid = uid;
return this;
}
public String getTid() {
return tid;
}
public CommonRequestParameters setTid(String tid) {
this.tid = tid;
return this;
}
public String getAid() {
return aid;
}
public CommonRequestParameters setAid(String aid) {
this.aid = aid;
return this;
}
public String getToken() {
return token;
}
public CommonRequestParameters setToken(String token) {
this.token = token;
return this;
}
public String getU() {
return u;
}
public CommonRequestParameters setU(String u) {
this.u = u;
return this;
}
public String getAuthCode() {
return authCode;
}
public CommonRequestParameters setAuthCode(String authCode) {
this.authCode = authCode;
return this;
}
public String getWechatAppId() {
return wechatAppId;
}
public CommonRequestParameters setWechatAppId(String wechatAppId) {
this.wechatAppId = wechatAppId;
return this;
}
public String getOpenId() {
return openId;
}
public CommonRequestParameters setOpenId(String openId) {
this.openId = openId;
return this;
}
}
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.*;
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);
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());
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.JSON;
import com.alibaba.fastjson.JSONObject;
import org.testng.Assert;
import java.util.Properties;
/**获取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");
}
}
package com.xiaomai.utils;
import org.springframework.util.StringUtils;
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 randomMobile(String ...randomstring){
String str="999";
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.*;
@ContextConfiguration(locations = {"classpath:/spring-core.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;
}
}
}
}
<?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>
<!-- <context:property-placeholder location="classpath:/application.properties" />-->
<!--<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>
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