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 ——> 支持线
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xiaomai</groupId>
<artifactId>xm-testng</artifactId>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.3.RELEASE</spring.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.9</slf4j.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.compile.encoding>UTF-8</project.compile.encoding>
</properties>
<repositories>
<repository>
<id>aliyunmaven</id>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.0.0</version>
<scope>compile</scope>
</dependency>
<!-- use to parse json document -->
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-path -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<!-- match rules in assertion -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
<!--jsonassert-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
<!--引入日志相关包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.26</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-excel</artifactId>
<version>1.0.0</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--spring4.2.3.RELEASE-->
<!--spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--/spring -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
<exclusion>
<artifactId>commons-collections</artifactId>
<groupId>commons-collections</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入 okhttp 3 相关jra 包-->
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.uncommons</groupId>
<artifactId>reportng</artifactId>
<version>1.1.4</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!--lombok引入-->
<!-- <dependency>-->
<!-- <groupId>org.projectlombok</groupId>-->
<!-- <artifactId>lombok</artifactId>-->
<!-- <version>1.18.12</version>-->
<!-- </dependency>-->
<!-- Time依赖架包下载 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.1</version>
</dependency>
<!--引入zson相关包-->
<dependency>
<groupId>link.zhangfei</groupId>
<artifactId>zson</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--添加插件 关联testng-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<!-- <forkMode>0</forkMode>-->
<!-- <argLine>-Dfile.encoding=UTF-8 -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=256m</argLine> &lt;!&ndash; 解决maven test命令时console出现中文乱码乱码 &ndash;&gt;-->
<testFailureIgnore>true</testFailureIgnore>
<suiteXmlFiles>
<file>testng.xml</file>
</suiteXmlFiles>
<properties>
<property>
<name>usedefaultlisteners</name>
<value>true</value>
</property>
</properties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<!--源码版本 -->
<source>1.8</source>
<!--编译的版本 -->
<target>1.8</target>
<!--指定编码 -->
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
<!--配置resources 资源-->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.xls</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
\ No newline at end of file
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;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.utils.*;
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.springframework.util.StringUtils;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.internal.InvokedMethod;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
public class BaseTest extends AbstractTestNGSpringContextTests {
private static final Log logger = LogFactory.getLog(XMBaseTest.class);
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 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();
}
/**
* 测试接口调用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();
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"));
if (api.containsKey("requestParamter")) {
executionApi.setRequestParamterTemplate(api.getString("requestParamter"));
}
/**
* 默认执行线上环境
*/
String env = "prod";
if (!StringUtils.isEmpty(prop.getProperty("runningEnv"))){
env = prop.getProperty("runningEnv");
}
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())) {
executionHeaders.put("instid", loginInfo.getInstId());
executionHeaders.put("bizAccountId", loginInfo.getAid());
executionHeaders.put("xmversion", "5.0");
executionHeaders.put("vn", "5.4.0");
} else if ("M".equals(executionApi.getTerminal())) {
executionHeaders.put("usertype", loginInfo.getUserType());
executionHeaders.put("deptpath", loginInfo.getDeptpath());
}
executionHeaders.put("xm_request_source", "test");
executionHeaders.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");
executionHeaders.put("Accept", "*/*");
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"));
}
}
private String getTestName(ITestResult test) {
ITestNGMethod testMethod = test.getMethod();
ITestContext context = test.getTestContext();
TestRunner run = (TestRunner) context;
String parameters = "";
Class<?> clazz = run.getClass();
try {
Field field = clazz.getDeclaredField("m_invokedMethods");
field.setAccessible(true);
List<InvokedMethod> list = (List<InvokedMethod>) field.get(run);
for (InvokedMethod in : list) {
if (testMethod.getMethodName().equals(in.getTestMethod().getMethodName())) {
Class<?> clazz_in = in.getClass();
Field field_in = clazz_in.getDeclaredField("m_parameters");
field_in.setAccessible(true);
Object[] ab = (Object[]) field_in.get(in);
for (Object o : ab) {
parameters += o.toString() + ",";
}
break;
}
}
if (parameters.length() > 0) {
parameters = parameters.substring(0, parameters.length() - 1);
parameters = "[" + parameters + "]";
}
System.out.println("testName: " + testMethod.getMethodName() + parameters);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return testMethod.getMethodName() + parameters;
}
@AfterMethod
public void afterMethod(ITestResult result) {
// List<NameValuePair> params = new ArrayList<NameValuePair>();
/*// 请求属性
params.add(new BasicNameValuePair("Url", xmAppApi.getUrl()));
params.add(new BasicNameValuePair("RequestParams", xmAppApi.getApi_request_params().toString()));
params.add(new BasicNameValuePair("RequestData", xmAppApi.getApi_request_data()));
// 测试报告添加caseOwner属性
params.add(new BasicNameValuePair("CaseOwner", dal.getCase_owner()));
params.add(new BasicNameValuePair("TraceId", xmAppApi.getApi_traceId()));
if (xmAppApi.getApi_startTime() != null) {
// 请求开始时间和结束时间
params.add(new BasicNameValuePair("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();
params.add(new BasicNameValuePair("ExpendTime", expendTime + "ms"));
params.add(new BasicNameValuePair("Response", xmAppApi.getApi_response()));*/
//result.setParameters(params.toArray());
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();
// okHttpClient.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.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.ResourceCDN;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.model.TestAttribute;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.util.*;
public class ExtentTestNGIReporterListener implements IReporter {
// static Date date = new Date();
// static String form = String.format("%tF", date);
// static String hour = String.format("%tH", date);
// static String minute = String.format("%tM", date);
// static String second = String.format("%tS", date);
//生成的路径以及文件名
private static final String OUTPUT_FOLDER = "test-output/";
private static final String FILE_NAME = "report" + ".html";
private ExtentReports extent;
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
init();
boolean createSuiteNode = false;
if (suites.size() > 1) {
createSuiteNode = true;
}
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
//如果suite里面没有任何用例,直接跳过,不在报告里生成
if (result.size() == 0) {
continue;
}
//统计suite下的成功、失败、跳过的总用例数
int suiteFailSize = 0;
int suitePassSize = 0;
int suiteSkipSize = 0;
ExtentTest suiteTest = null;
//存在多个suite的情况下,在报告中将同一个suite的测试结果归为一类,创建一级节点。
if (createSuiteNode) {
suiteTest = extent.createTest(suite.getName()).assignCategory(suite.getName());
}
boolean createSuiteResultNode = false;
if (result.size() > 1) {
createSuiteResultNode = true;
}
for (ISuiteResult r : result.values()) {
ExtentTest resultNode;
ITestContext context = r.getTestContext();
if (createSuiteResultNode) {
//没有创建suite的情况下,将在SuiteResult的创建为一级节点,否则创建为suite的一个子节点。
if (null == suiteTest) {
resultNode = extent.createTest(r.getTestContext().getName());
} else {
resultNode = suiteTest.createNode(r.getTestContext().getName());
}
} else {
resultNode = suiteTest;
}
if (resultNode != null) {
resultNode.getModel().setName(suite.getName() + " : " + r.getTestContext().getName());
if (resultNode.getModel().hasCategory()) {
resultNode.assignCategory(r.getTestContext().getName());
} else {
resultNode.assignCategory(suite.getName(), r.getTestContext().getName());
}
resultNode.getModel().setStartTime(r.getTestContext().getStartDate());
resultNode.getModel().setEndTime(r.getTestContext().getEndDate());
//统计SuiteResult下的数据
int passSize = r.getTestContext().getPassedTests().size();
int failSize = r.getTestContext().getFailedTests().size();
int skipSize = r.getTestContext().getSkippedTests().size();
suitePassSize += passSize;
suiteFailSize += failSize;
suiteSkipSize += skipSize;
if (failSize > 0) {
resultNode.getModel().setStatus(Status.FAIL);
}
resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;", passSize, failSize, skipSize));
}
buildTestNodes(resultNode, context.getFailedTests(), Status.FAIL);
buildTestNodes(resultNode, context.getSkippedTests(), Status.SKIP);
buildTestNodes(resultNode, context.getPassedTests(), Status.PASS);
}
if (suiteTest != null) {
suiteTest.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;", suitePassSize, suiteFailSize, suiteSkipSize));
if (suiteFailSize > 0) {
suiteTest.getModel().setStatus(Status.FAIL);
}
}
}
extent.flush();
}
private void init() {
//文件夹不存在的话进行创建
File reportDir = new File(OUTPUT_FOLDER);
if (!reportDir.exists() && !reportDir.isDirectory()) {
reportDir.mkdir();
}
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
// 设置静态文件的DNS
htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);
//怎么样解决cdn.rawgit.com访问不了的情况
htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);
htmlReporter.config().setDocumentTitle("自动化测试报告");
htmlReporter.config().setReportName("小麦自动化测试报告");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setCSS(".node.level-1 ul{ display:none;} .node.level-1.active ul{display:block;}");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
}
private void buildTestNodes(ExtentTest extenttest, IResultMap tests, Status status) {
//存在父节点时,获取父节点的标签
String[] categories = new String[0];
if (extenttest != null) {
List<TestAttribute> categoryList = extenttest.getModel().getCategoryContext().getAll();
categories = new String[categoryList.size()];
for (int index = 0; index < categoryList.size(); index++) {
categories[index] = categoryList.get(index).getName();
}
}
ExtentTest test;
if (tests.size() > 0) {
//调整用例排序,按时间排序
Set<ITestResult> treeSet = new TreeSet<ITestResult>(new Comparator<ITestResult>() {
public int compare(ITestResult o1, ITestResult o2) {
return o1.getStartMillis() < o2.getStartMillis() ? -1 : 1;
}
});
treeSet.addAll(tests.getAllResults());
for (ITestResult result : treeSet) {
//Object[] parameters = result.getParameters();
String name = "";
String description = result.getMethod().getDescription();
if (description != null) {
name = description + "_" + result.getMethod().getMethodName();
} else {
String ApiName = "测试请求";
if (null != result.getAttribute("ApiName")) {
ApiName += result.getAttribute("ApiName").toString();
}
name = ApiName + "_" + result.getMethod().getMethodName();
}
String parametersStr = "";
for (Object param : result.getParameters()) {
parametersStr += param +",";
}
if (parametersStr.length() > 0) {
parametersStr = parametersStr.substring(0, parametersStr.length() - 1);
parametersStr = "[" + parametersStr + "]";
}
name += parametersStr;
if (extenttest == null) {
test = extent.createTest(name);
} else {
//作为子节点进行创建时,设置同父节点的标签一致,便于报告检索。
test = extenttest.createNode(name).assignCategory(categories);
}
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
List<String> outputList = Reporter.getOutput(result);
for (String output : outputList) {
//将用例的log输出报告中
test.debug(output);
}
//如果有参数,则使用参数的toString组合代替报告中
String[] attrNames = {"Url", "RequestParams", "RequestData", "CaseOwner", "TraceId","StartTime", "ExpendTime", "Response"};
for (String attrName : attrNames) {
String infoName = "<span class=\"label start-time\">" + attrName + "</span><br>";
test.debug(infoName + result.getAttribute(attrName));
}
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
} else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
test.getModel().setStartTime(getTime(result.getStartMillis()));
test.getModel().setEndTime(getTime(result.getEndMillis()));
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
\ No newline at end of file
package com.xiaomai.client;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.util.*;
/**
* OkHttpClient
* Created by adu on 2019/8/4 14:34
*/
public class OkHttpClient {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static okhttp3.OkHttpClient okHttpClient;
public static Logger logger = LoggerFactory.getLogger(OkHttpClient.class);
Response response ;
int responseCode;
JSONObject responseBody;
HashMap<String, String> responseHeadsMap;
RequestBody requestBody;
Request request;
Headers.Builder headerBuilder;
String responseStr;
Headers responseHeaderes;
static {
//ssl认证重写
okHttpClient = new okhttp3.OkHttpClient.Builder().hostnameVerifier(
new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
).build();
}
/**
* json格式参数post请求
* @param url
* @param jsonDate
* @param headers
*/
/** 适用所有post的请求 **/
/** 发送json请求 */
public void doPostRequest(String url, String json, Map<String, String> headers) {
try {
// 设置请求主体格式
requestBody = RequestBody.create(JSON, json);
//添加请求头
headerBuilder =new Headers.Builder();
// 以 Entry 添加消息头
if (headers != null && headers.size() > 0) {
Iterator iterator = headers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
headerBuilder.add((String) entry.getKey(), (String) entry.getValue());
}
}
request = new Request.Builder()
.url(url)
.post(requestBody)
.headers(headerBuilder.build())
.build();
response = okHttpClient.newCall(request).execute();
responseCode = response.code();
responseHeaderes = response.headers();
responseStr = response.body().string();
}catch (Exception e){
logger.error("okhttp3 执行 doPostRequest 异常 >> ex = {}", ExceptionUtils.getStackTrace(e));
}finally {
try {
if (response != null) {
// response.close();
}
}catch (Exception e){
logger.error("okhttp3 执行 doPostRequest 异常 >> ex = {}", ExceptionUtils.getStackTrace(e));
}
}
}
public void doPostRequest(String url, IdentityHashMap<String, String> params,
Map<String, String> headers) {
FormBody.Builder FormBodyBuilder = new FormBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
FormBodyBuilder.add(key, String.valueOf(params.get(key)));
}
}
headerBuilder =new Headers.Builder();
// 以 Entry 添加消息头
if (headers != null && headers.size() > 0) {
Iterator iterator = headers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
headerBuilder.add((String) entry.getKey(), (String) entry.getValue());
}
}
request = new Request.Builder()
.url(url)
.post(FormBodyBuilder.build())
.headers(headerBuilder.build())
.build();
try {
response = okHttpClient.newCall(request).execute();
responseCode = response.code();
responseHeaderes = response.headers();
responseStr = response.body().string();
int status = response.code();
Assert.assertEquals(status, 200);
} catch (Exception e) {
logger.error("okhttp3 执行失败 >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
// response.close();
}
}
}
/**
* 发送Form 表单 post 请求
* @param url
* @param paramsMap
*/
public void doPostForForm(String url, IdentityHashMap<String, String> paramsMap,Map<String, String> headers) {
FormBody.Builder FormBodyBuilder = new FormBody.Builder();
//添加参数
if (paramsMap != null && paramsMap.keySet().size() > 0) {
for (String key : paramsMap.keySet()) {
FormBodyBuilder.add(key, String.valueOf(paramsMap.get(key)));
}
}
headerBuilder =new Headers.Builder();
// 以 Entry 添加消息头
if (headers != null && headers.size() > 0) {
Iterator iterator = headers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
headerBuilder.add((String) entry.getKey(), (String) entry.getValue());
}
}
request = new Request.Builder()
.url(url)
.post(FormBodyBuilder.build())
.headers(headerBuilder.build())
.addHeader("contentType", "application/x-www-form-urlencoded; charset=UTF-8")
.build();
try {
response = okHttpClient.newCall(request).execute();
responseCode = response.code();
responseHeaderes = response.headers();
responseStr = response.body().string();
// 如果校验失败,会导致后续传参不执行
// Assert.assertEquals(responseCode,200,responseCode+":请求失败");
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
// response.close();
}
}
}
/**
*
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public void doGetRequest(String url, IdentityHashMap<String, String> queries,Map<String, String> headerParamsMap) {
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, Object>) iterator.next();
if (firstFlag) {
sb.append("?" + entry.getKey() + "=" + entry.getValue());
firstFlag = false;
} else {
sb.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
}
Headers.Builder headerBuilder =new Headers.Builder();
// 以 Entry 添加消息头
if (headerParamsMap != null && headerParamsMap.size() > 0) {
Iterator iterator = headerParamsMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
headerBuilder.add((String) entry.getKey(), (String) entry.getValue());
}
}
request = new Request.Builder()
.url(sb.toString())
.headers(headerBuilder.build())
.build();
try {
response = okHttpClient.newCall(request).execute();
responseCode = response.code();
responseHeaderes = response.headers();
responseStr = response.toString();
// Assert.assertEquals(responseCode,200,responseCode+":请求失败");
} catch (Exception e) {
logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
// response.close();
}
}
}
/**
* 以JSON格式获取到反馈的主体
* @return
*/
public JSONObject getBodyInJSON() {
if (responseStr!= null){
try {
//responseBody = com.alibaba.fastjson.JSON.parseObject(responseStr);
responseBody =JSONObject.parseObject(responseStr);
}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() {
System.out.println("===============================================\n");
System.out.println("This is your response body ==> \n" + responseStr);
System.out.println("===============================================\n\n");
return responseStr ;
}
/**
* 以哈希图的方式获取到反馈头部
* @return
*/
public HashMap<String,String> getHeaders(){
responseHeadsMap= new HashMap<String,String>();
if(null != responseHeaderes){
Set<String> names = responseHeaderes.names();
for (String name:names){
responseHeadsMap.put(name,responseHeaderes.get(name));
}
}
/* System.out.println("===============================================\n");
System.out.println("This is your response header ==> \n" + responseHeadsMap);
System.out.println("===============================================\n\n");*/
return responseHeadsMap;
}
/**
* 获取反馈状态码
* @return
*/
public int getResponseCode(){
System.out.println("===============================================\n");
System.out.println("This is your response code ==> \n" + responseCode);
System.out.println("===============================================\n\n");
return responseCode;
}
/**
* okHttpClient 不需要手动关闭请求连接
*/
// public void shutDownConnection(){
// try {
// okHttpClient.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
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.client;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.utils.*;
import org.springframework.util.StringUtils;
import org.testng.Assert;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
public class XMAppApi {
//private String tk;
//private String deviceId;
//private String app;
// private String userNickName;
//private String userPass;
private String path;
private String host;
private String url;
//private String emailCode;
//private String publicKey;
//private String os;
//private String model;
//private String osv;
//private String isApp;
//private String data;
//private String protocol;
//private String port;
//private String sign;
//private String appKey;
private String apiName;
@Deprecated
private String env;
private String apiModule;
private String loginUser;
private String apiDesc;
private String requestParamterTemplate; // 接口入参模板
private IdentityHashMap<String, String> api_request_params = new IdentityHashMap<String, String>();
private String api_request_data ;
private Map<String, String> api_request_headers=null;
private String api_response;
private String api_traceId;
public Long getApi_startTime() {
return api_startTime;
}
public XMAppApi setApi_startTime(Long api_startTime) {
this.api_startTime = api_startTime;
return this;
}
public Long getApi_endTime() {
return api_endTime;
}
public XMAppApi setApi_endTime(Long api_endTime) {
this.api_endTime = api_endTime;
return this;
}
private Long api_startTime;
private Long api_endTime;
private Long api_requestTime;
private CommonRequestParameters loginInfo;
private Map<String, String> headrs = new HashMap<>();
private IdentityHashMap<String, String> params = new IdentityHashMap<>();
private String dataJson="";
public CommonRequestParameters getLoginInfo(){
this.loginInfo = CommonLoginInfo.getLoginUser(this.loginUser);
return this.loginInfo;
}
public Long getApi_requestTime() {
return api_requestTime;
}
public XMAppApi setApi_requestTime(Long api_requestTime) {
this.api_requestTime = api_requestTime;
return this;
}
public String getApiDesc() {
return apiDesc;
}
public void setApiDesc(String apiDesc) {
this.apiDesc = apiDesc;
}
public IdentityHashMap<String, String> getApi_request_params() {
return api_request_params;
}
public String getApi_request_data() {
return api_request_data;
}
public Map<String, String> getApi_request_headers() {
return api_request_headers;
}
public String getApi_response() {
return api_response;
}
public String getApi_traceId() {
return api_traceId;
}
// 测试接口所属端位:B端,M端,C端
private String terminal;
public XMAppApi setApi_request_params(IdentityHashMap<String, String> api_request_params) {
this.api_request_params = api_request_params;
if(null != api_request_params){
System.out.println("===============================================\n");
System.out.println("This is your request params ==> \n" + api_request_params);
System.out.println("===============================================\n\n");
}
return this;
}
public XMAppApi setApi_request_data(String api_request_data) {
this.api_request_data = api_request_data;
if(!StringUtils.isEmpty(api_request_data)){
System.out.println("===============================================\n");
System.out.println("This is your request json ==> \n" + api_request_data);
System.out.println("===============================================\n\n");
}
return this;
}
public XMAppApi setApi_request_headers(Map<String, String> api_request_headers) {
this.api_request_headers = api_request_headers;
return this;
}
public XMAppApi setApi_response(String api_response) {
this.api_response = api_response;
return this;
}
public XMAppApi setApi_traceId(String api_traceId) {
this.api_traceId = api_traceId;
return this;
}
public String getTerminal() {
return terminal;
}
public XMAppApi setTerminal(String terminal) {
this.terminal = terminal;
return this;
}
public String getPath() {
return path;
}
public XMAppApi setPath(String path) {
this.path = path;
return this;
}
public String getHost() {
return host;
}
public XMAppApi setHost(String host) {
this.host = host;
return this;
}
public String getUrl() {
return url;
}
public XMAppApi setUrl(String url) {
this.url = url;
return this;
}
public String getApiName() {
return apiName;
}
public XMAppApi setApiName(String apiName) {
this.apiName = apiName;
return this;
}
@Deprecated
public String getEnv() {
return env;
}
@Deprecated
public XMAppApi setEnv(String env) {
this.env = env;
return this;
}
public String getApiModule() {
return apiModule;
}
public XMAppApi setApiModule(String apiModule) {
this.apiModule = apiModule;
return this;
}
public String getLoginUser() {
return loginUser;
}
public XMAppApi setLoginUser(String loginUser) {
this.loginUser = loginUser;
return this;
}
@Deprecated
public void doPost (OkHttpClient okHttpClient, String url,IdentityHashMap<String,String> params, String json, HashMap<String, String> headers) {
// 计算请求开始时间
Long start=System.currentTimeMillis();
okHttpClient.doPostRequest(url,json,headers);
// 计算请求结束时间
Long end=System.currentTimeMillis();
JSONObject jsonBody = okHttpClient.getBodyInJSON();
Map<String ,String> head = okHttpClient.getHeaders();
this.api_endTime=end;
this.api_startTime=start;
Long requestTime=end-start;
this.api_requestTime=requestTime;
this.api_traceId =head.get("traceId");
this.api_request_data = json;
this.api_request_params = params;
this.api_request_headers = headers;
this.api_response =jsonBody.toJSONString();
}
/**
*
* @param requestType 请求类型
* @param params 请求参数
* @param json 请求发送的json 数据
* @param headers 请求头
*/
public XMAppApi doRequest(String requestType, IdentityHashMap<String,String> params, String json, HashMap<String, String> headers) {
OkHttpClient okHttpClient = new OkHttpClient();
Long start=System.currentTimeMillis();
switch (requestType) {
case "JSON":
okHttpClient.doPostRequest(url, json, headers);
break;
case "PARAM":
okHttpClient.doPostRequest(url, params, headers);
break;
case "FORM":
okHttpClient.doPostForForm(url, params, headers);
break;
case "GET":
okHttpClient.doGetRequest(url, params, headers);
break;
}
Long end=System.currentTimeMillis();
Map<String, String> head = okHttpClient.getHeaders();
String response = okHttpClient.getBody();
this.api_endTime=end;
this.api_startTime=start;
Long requestTime=end-start;
this.api_requestTime=requestTime;
this.api_response = response;
this.api_traceId = head.get("traceId");
this.setApi_request_data(json);
this.setApi_request_params(params);
this.api_request_headers = headers;
return this;
}
/**
* 简单success 结果断言
* @param flag
*/
public void assetsSuccess(boolean flag,String ...msg){
String msgStr = "请求结果校验失败";
if(msg.length>0){
msgStr = msg[0];
}
String success = XMJSONPath.readPath(this.api_response,"$.success");
if(flag){
Assert.assertEquals(success, "true",msgStr);
}else {
Assert.assertEquals(success, "false",msgStr);
}
}
public void assetsResultCode(boolean flag,String ...msg){
String msgStr = "请求结果校验失败";
if(msg.length>0){
msgStr = msg[0];
}
String success = XMJSONPath.readPath(this.api_response,"$.resultCode");
if(flag){
Assert.assertEquals(success, "0",msgStr);
}else {
Assert.assertNotEquals(success, "0",msgStr);
}
}
//
/**
* 简单success 结果断言
* @param flag
*/
public void assetsResultMsg(boolean flag,String ...msg){
String msgStr = "请求结果校验失败";
if(msg.length>0){
msgStr = msg[0];
}
String success = XMJSONPath.readPath(this.api_response,"$.resultMsg");
if(flag){
Assert.assertEquals(success, "成功",msgStr);
}else {
Assert.assertEquals(success, "失败",msgStr);
}
}
/**
* 以JSON格式获取到反馈的主体
* @return
*/
public JSONObject getBodyInJSON() {
JSONObject api_response_json = null;
if (this.api_response!= null){
try {
api_response_json =JSONObject.parseObject(api_response);
}catch (Exception e){
e.printStackTrace();
}
}
return api_response_json;
}
public DataUserInfo getUserInfo(){
DataUserInfo dataUserInfo = new DataUserInfo();
dataUserInfo.setLoginUser(this.getLoginUser());
dataUserInfo.setEnv(this.getEnv());
return dataUserInfo;
}
public Map<String, String> getHeadrs() {
return headrs;
}
public XMAppApi setHeadrs(Map<String, String> headrs) {
this.headrs = headrs;
return this;
}
public IdentityHashMap<String, String> getParams() {
return params;
}
public XMAppApi setParams(IdentityHashMap<String, String> params) {
this.params = params;
return this;
}
public String getDataJson() {
return dataJson;
}
public void setDataJson(String dataJson) {
this.dataJson = dataJson;
}
public String getRequestParamterTemplate() {
return requestParamterTemplate;
}
public void setRequestParamterTemplate(String requestParamterTemplate) {
this.requestParamterTemplate = requestParamterTemplate;
}
public JSONObject getRequestParamterTemplateJSON(){
JSONObject requestParamterTemplateJSON = JSONObject.parseObject(this.requestParamterTemplate);
requestParamterTemplateJSON.replace("bizAccountId",getLoginInfo().getAid());
requestParamterTemplateJSON.replace("instId",getLoginInfo().getInstId());
requestParamterTemplateJSON.replace("objectId", RandomStringUtil.randomString(20));
requestParamterTemplateJSON.replace("operationDate", TimeUtils.getCurrentTime());
return requestParamterTemplateJSON;
}
}
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.client.OkHttpClient;
import com.xiaomai.enums.Terminal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import java.util.*;
/**
* 公共登录工具类
*/
public class CommonLogin {
JsonAndFile fileHandle;
OkHttpClient okHttpClient;
// 组装请求
IdentityHashMap<String, String> params;
HashMap<String, String> headers;
String url;
Properties prop;
JSONObject body;
String xmTtoken = "";
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();
String parameters = JsonAndFile.readTxtFile(System.getProperty("user.dir") + "/src/main/resources/parameter.json");
JSONObject object = JSON.parseObject(parameters).getJSONObject(loginUser); //获取name在parameter.json文件中的信息
Assert.assertNotNull(object, "找不到用户登录信息,请检查parameter.json 文件是否已有保存登录账号信息。");
if (!object.isEmpty()) {
JSONObject account = object.getJSONObject(env);
String accountNo = account.getString("accountNo");
String uid = account.getString("uid");
String userType = account.getString("userType");
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");
String certificate = account.get("certificate").toString();
String instId = account.getString("instId");
String aid = account.getString("aid");
String tid = account.getString("tid");
url = host + "/business/anon/b/login?p=w&v=v5.0.0&userType=B&aid=" + aid;
String data = "{\"accountNo\":\"" + accountNo + "\",\"certificate\":\"" + certificate + "\",\"appTerm\":\"PC\",\"loginType\":\"PHONE_PWD\"}";
okHttpClient.doPostRequest(url, data, headers);
body = okHttpClient.getBodyInJSON();
// 获取token
Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
xmTtoken = body.getJSONObject("result").get("xmToken").toString();
Assert.assertNotNull(xmTtoken, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
// 设置登录信息
// CommonRequestParameters loginIofo = new CommonRequestParameters().setAid(aid)
// 上面写法会导致参数传空
CommonRequestParameters loginIofo = new CommonRequestParameters();
loginIofo.setAid(aid)
.setUid(uid).setTid(tid).setUserType("B").setP("PC").setXmversion("5.0").setB("552595").setSaasV("5.0")
.setVn("5.4.3")
.setDeviceVersion("13.4.1")
.setV("5.4.3")
.setToken(xmTtoken)
.setTid(tid)
.setInstId(instId)
.setAccountNo(accountNo);
loginInfoMap.add(loginUser, loginIofo);
} else if (Terminal.M.equals(loginTerminal)) {
url = host + "/api-m/m/login/authCode";
String deptpath = account.getString("deptpath");
IdentityHashMap<String, String> param = new IdentityHashMap<>();
param.put("phone", accountNo);
param.put("code", "000000");
okHttpClient.doPostForForm(url, param, headers);
body = okHttpClient.getBodyInJSON();
// 获取token
Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
xmTtoken = body.getJSONObject("data").get("token").toString();
Assert.assertNotNull(xmTtoken, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
// 设置登录信息
CommonRequestParameters loginIofo = new CommonRequestParameters().setDeptpath(deptpath)
.setUid(uid).setUserType(userType)
.setToken(xmTtoken)
.setU(accountNo)
.setAccountNo(accountNo);
;
loginInfoMap.add(loginUser, loginIofo);
} else if (Terminal.C.equals(loginTerminal)) {
headers.remove("User-Agent");
headers.remove("Cookie");
headers.remove("Accept");
headers.remove("Connection");
String appId = account.get("appId").toString();
String token = account.get("xmtoken").toString();
String openId = account.get("openId").toString();
String p = account.getString("p");
headers.put("accept", "application/json");
headers.put("appId", appId);
headers.put("openId", openId);
headers.put("xmtoken", token);
headers.put("p", p);
// 执行获取验证码
headers.put("content-type", "application/json; charset=UTF-8");
url = host + "/horn/anon/horn/msgAuthCode";
String data = "{\n" +
" \"serverType\": \"BIND_PHONE\",\n" +
" \"phone\": " + accountNo + "\n" +
"}";
okHttpClient.doPostRequest(url, data, headers);
// 执行验证码登录
url = host + "/account/public/account/bindPhone";
data = "{\n" +
" \"authCode\": \"0000\",\n" +
" \"phone\": " + accountNo + "\n" +
"}";
okHttpClient.doPostRequest(url, data, headers);
body = okHttpClient.getBodyInJSON();
// 获取token
Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
String id = body.getJSONObject("result").getString("id");
Assert.assertNotNull(id, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
// 设置登录信息
CommonRequestParameters loginIofo = new CommonRequestParameters()
.setUid(id).setUserType(userType)
.setToken(token)
.setP(p)
.setAccountNo(accountNo)
.setOpenId(openId)
.setWechatAppId(appId);
loginInfoMap.add(loginUser, loginIofo);
} else if (Terminal.minApp.equals(loginTerminal)) {
String appId = account.getString("appId");
String openId = account.getString("openId");
String verifyCode = account.getString("verifyCode");
params.put("phone", accountNo);
params.put("verifyCode", verifyCode);
params.put("xcxOpenId", openId);
params.put("appId", appId);
params.put("serverType", "HOMEWORK_LOGIN");
url = host + "/api-h/c/login/xcx/homework/loginVersionTwo";
okHttpClient.doPostForForm(url, params, headers);
body = okHttpClient.getBodyInJSON();
Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
// 获取token
String token = body.getJSONObject("data").getString("token");
Assert.assertNotNull(token, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
String userId = body.getJSONObject("data").getString("userId");
// 设置登录信息
CommonRequestParameters loginIofo = new CommonRequestParameters()
.setUid(userId).setUserType(loginTerminal)
.setToken(token)
.setP("xcx")
.setAccountNo(accountNo)
.setOpenId(openId)
.setWechatAppId(appId);
loginInfoMap.add(loginUser, loginIofo);
} else if (Terminal.APP_C.equals(loginTerminal)) {
//app 每课学堂,手动滑动滑块, 可以 账户 + 0000 登录成功
JSONObject loginInfo = new JSONObject();
loginInfo.put("accountNo", accountNo);
loginInfo.put("certificate", account.get("certificate").toString());
loginInfo.put("loginType", "PHONE_AUTH_CODE");
loginInfo.put("appTerm", "ANDROID");
loginInfo.put("userType", "C");
url = host + "/zeus/anon/account/login";
okHttpClient.doPostRequest(url, loginInfo.toJSONString(), headers);
body = okHttpClient.getBodyInJSON();
Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
// 获取token
String token = body.getJSONObject("result").getString("xmToken");
Assert.assertNotNull(token, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败!");
String userId = body.getJSONObject("result").getString("userId");
// 设置登录信息
CommonRequestParameters loginIofo = new CommonRequestParameters()
.setUid(userId).setUserType(loginTerminal)
.setToken(token)
.setAccountNo(accountNo);
loginInfoMap.add(loginUser, loginIofo);
}
} else {
logger.warn("账号信息不存在!");
}
}
}
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 java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class TimeUtils{
private static Date praseDate(String time,SimpleDateFormat sdf ) {
try {
return sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* @Description: 获取当天某一时分的时间
* @Author: pdd
* @Date: 2020/11/26/15:27
*/
public static long getToDayTime(int hour,int minute){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
long data = calendar.getTime().getTime();
return data;
}
/**
* @return 获取当天日期时间戳(0点)
*/
public static long getTodayTime(){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
long today_date = calendar.getTime().getTime();
return today_date;
}
/**
* @return 获取当天结束日期时间戳(24点)
*/
public static long getTodayEndTime(){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
long today_end_date = calendar.getTime().getTime();
return today_end_date;
}
/**
*
* @return 获取当前时间戳
*/
public static long getCurrentTime(){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
long today_date = calendar.getTime().getTime();
return today_date;
}
// 获取一周前的日期
public static long getLastWeekDate() {
// 获取一周前的时间
SimpleDateFormat sdf_hms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
Calendar c_1 = Calendar.getInstance();
c_1.setTime(new Date());
c_1.add(Calendar.DATE, - 7);
Date d = c_1.getTime();
String lastweek_day = sdf_day.format(d) +" 00:00:00";
Date lastweek_date = null;
lastweek_date = praseDate(lastweek_day,sdf_hms);
long lastweek_time = lastweek_date.getTime();
return lastweek_time;
}
// 获取几天后的23:59:59
public static long getAfterDayDate(int addDay) {
// 获取几天后的时间
SimpleDateFormat sdf_hms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
Calendar c_1 = Calendar.getInstance();
c_1.setTime(new Date());
c_1.add(Calendar.DATE, +addDay);
Date d = c_1.getTime();
String lastday_day = sdf_day.format(d) +" 23:59:59";
Date lastday_date = null;
lastday_date = praseDate(lastday_day,sdf_hms);
long afterday_time = lastday_date.getTime();
return afterday_time;
}
/**
* 获取数月后日期时间戳
* @param sDate 初始时间
* @param addMonth 增加的月份数
* @param addDay 增加的天数
* @return
* @throws ParseException
*/
public static long getAfterMonthDate(long sDate,int addMonth, int addDay) {
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf_hms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date smdate = new Date(sDate);
Calendar c_1 = Calendar.getInstance();
c_1.setTime(smdate);
//购买一个月的课程
c_1.add(Calendar.MONTH, +addMonth);
// 计算时需要减去最后一天时间,不记入时间计算
c_1.add(Calendar.DATE, -1);
// 计算赠送的天数
c_1.add(Calendar.DATE, +addDay);
Date lastweek_aftermonth_d = c_1.getTime();
String lastweek_aftermonth = sdf_day.format(lastweek_aftermonth_d) +" 00:00:00";
Date date_month = praseDate(lastweek_aftermonth,sdf_hms);
long time_month = date_month.getTime();
return time_month;
}
/**
* 获取数月前的日期
* @param sDate 初始时间
* @param addMonth 往前数的月份数
* @param addDay 往前增加的天数
* @return
* @throws ParseException
*/
public static long getLastrMonthDate(long sDate,int addMonth, int addDay) {
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf_hms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date smdate =new Date(sDate);
Calendar c_1 = Calendar.getInstance();
c_1.setTime(smdate);
//购买一个月的课程
c_1.add(Calendar.MONTH, -addMonth);
// 计算赠送的天数
c_1.add(Calendar.DATE, -addDay);
// 计算时需要减去最后一天时间,不记入时间计算
c_1.add(Calendar.DATE, 1);
Date lastweek_aftermonth_d = c_1.getTime();
String lastweek_aftermonth = sdf_day.format(lastweek_aftermonth_d) +" 00:00:00";
Date date_month = praseDate(lastweek_aftermonth,sdf_hms);
long time_month = date_month.getTime();
return time_month;
}
/**
*
* @return 获取当月第一天时间戳 零点零分
* @throws ParseException
*/
public static long getMonthFristDay() {
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf_hms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
//c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
Date lastweek_aftermonth_d = c.getTime();
String lastweek_aftermonth = sdf_day.format(lastweek_aftermonth_d) + " 00:00:00";
Date date_month = praseDate(lastweek_aftermonth,sdf_hms);
long time_month = date_month.getTime();
return time_month;
}
/**
*
* @return 获取当月第一天时间戳 零点零分
* @throws ParseException
*/
public static long getMonthLastDay() {
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf_hms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//获取当前月最后一天
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
Date lastweek_aftermonth_d = ca.getTime();
String lastweek_aftermonth = sdf_day.format(lastweek_aftermonth_d) + " 00:00:00";
Date date_month = praseDate(lastweek_aftermonth,sdf_hms);
long time_month = date_month.getTime();
return time_month;
}
/**
*
* @return 获取当月最后一天时间戳 23:59:59
* @throws ParseException
*/
public static long getMonthLastTime() {
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf_hms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//获取当前月最后一天
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
Date lastweek_aftermonth_d = ca.getTime();
String lastweek_aftermonth = sdf_day.format(lastweek_aftermonth_d) + " 23:59:59";
Date date_month = praseDate(lastweek_aftermonth,sdf_hms);
long time_month = date_month.getTime();
return time_month;
}
/**
*
* @return 获取当周第一天时间戳 零点零分
* @throws ParseException
*/
public static String getWeekFirstTime() {
Calendar cld = Calendar.getInstance(Locale.CHINA);
cld.setFirstDayOfWeek(Calendar.MONDAY);//以周一为首日
cld.set(Calendar.HOUR_OF_DAY, 0);
cld.set(Calendar.MINUTE, 0);
cld.set(Calendar.SECOND, 0);
cld.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);//周一
String beginWeekTime = String.valueOf(cld.getTime().getTime());
return beginWeekTime;
}
/**
*
* @return 获取当周最后一天时间戳 23:59:59
* @throws ParseException
*/
public static String getWeekLastTime() {
Calendar cld = Calendar.getInstance(Locale.CHINA);
int week = cld.get(Calendar.DAY_OF_WEEK);
cld.add(Calendar.DATE, 8-week);
cld.set(Calendar.HOUR_OF_DAY, 23);
cld.set(Calendar.MINUTE, 59);
cld.set(Calendar.SECOND, 59);
String endWeekTime = String.valueOf(cld.getTime().getTime());
return endWeekTime;
}
/**
* 获取两个日期之间的天数差
* @param time_s 起始时间
* @param time_e 结束时间
* @return
* @throws ParseException
*/
public static int daysBetween(long time_s,long time_e) {
long between_days = (time_e - time_s) / (1000 * 3600 * 24);
// 消耗天数,需计算当天
int daysBetween = Integer.parseInt(String.valueOf(between_days))+1;
return Integer.parseInt(String.valueOf(daysBetween));
}
public static void main1(String[] args) {
// 获取当天时间
long todayDate = getTodayTime();
long lastWeekDate = getLastWeekDate();
// 获取当前日期前一个星期,再往后推一个月 再加两天赠送天数的 日期
long afterMonthDate= getAfterMonthDate(lastWeekDate,1,2);
// 获取当前日期前一个星期,再往前推一个月 再加两天赠送天数的 日期
long lastMonthDate= getLastrMonthDate(lastWeekDate,1,2);
// 计算上周,到上周往后推一个月后的天数差
int lastWeekDate_afterMonthDate = daysBetween(lastWeekDate,afterMonthDate);
// 上周 往后推一个月 的天数差,为实际购买天数 // 减去赠送的2 天
//已消耗 7天 ,剩余天数 = 购买天数- 消耗天数
int leftDays_1 = lastWeekDate_afterMonthDate - 7;
// 剩余购买天数 要减去赠送天数
int lastWeekDate_lastMonthDate= daysBetween(lastMonthDate,lastWeekDate);
System.out.println("上周往后推一个月的日期 到上周的天数差:" + lastWeekDate_afterMonthDate);
System.out.println("上周往前推一个月的日期 到上周的天数差:" + lastWeekDate_lastMonthDate);
// 获取本周周一的时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Calendar cld = Calendar.getInstance(Locale.CHINA);
cld.setFirstDayOfWeek(Calendar.MONDAY);//以周一为首日
cld.set(Calendar.HOUR_OF_DAY, 0);
cld.set(Calendar.MINUTE, 0);
cld.set(Calendar.SECOND, 0);
cld.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);//周一
long Monday_date = cld.getTime().getTime();
System.out.println("本周周一:"+df.format(cld.getTime()) + " --"+Monday_date);
cld.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);//周日
cld.set(Calendar.HOUR_OF_DAY, 23);
cld.set(Calendar.MINUTE, 59);
cld.set(Calendar.SECOND, 59);
long Sunday_date = cld.getTime().getTime();
System.out.println("本周周日"+df.format(cld.getTime()) + " --"+Sunday_date);
}
/**
* 获取当前日期 ”yyyymmdd“
* @return
*/
public static String getCurrentDateString(){
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
String today_date = sdf_day.format(calendar.getTime());
return today_date;
}
}
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