Commit 48264825 by xuyamei

初始化

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