Commit 77e633d5 authored by 马博's avatar 马博

Init

parents
Pipeline #71143 failed with stages
in 0 seconds
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.duiba</groupId>
<artifactId>test-platform</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.8.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.8.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.8.RELEASE</version>
</dependency>
<!--testng-->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
<!--rest-assured-->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.3</version>
<scope>test</scope>
</dependency>
<!-- 依赖reportNg-->
<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>
<!-- 依赖Guice -->
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
<!--日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>cn.com.duiba</groupId>
<artifactId>java-sdk</artifactId>
<version>0.0.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!--<suiteXmlFiles>-->
<!--<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>-->
<!--</suiteXmlFiles>-->
<includes><include>${run}</include></includes>
<parallel>classes</parallel>
<threadCount>5</threadCount>
<!-- ReportNG配置 -->
<properties>
<property>
<name>usedefaultlisteners</name>
<value>false</value>
</property>
<property>
<name>listener</name>
<value>org.uncommons.reportng.HTMLReporter,common.RetryListener,common.TestListener,common.TestReport</value>
</property>
</properties>
<workingDirectory>target/</workingDirectory>
<systemPropertyVariables>
<runEnv>tst.deploy.dui88.com</runEnv>
<noticeDD>false</noticeDD>
<noticePerson>false</noticePerson>
<sendPlatform>false</sendPlatform>
<run>${run}</run>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>data/*</directory>
</resource>
<resource>
<directory>lib/*</directory>
</resource>
<resource>
<directory>key/*</directory>
</resource>
<resource>
<filtering>true</filtering>
<directory>src/test/resources</directory>
<excludes>
<exclude>application-test.properties</exclude>
<exclude>application-dev.properties</exclude>
<exclude>application-product.properties</exclude>
<exclude>application.properties</exclude>
</excludes>
</resource>
<resource>
<filtering>true</filtering>
<directory>src/test/profiles/${environment}</directory>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>aliyun</id>
<properties>
<environment>aliyun</environment>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<environment>test</environment>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<environment>dev</environment>
</properties>
</profile>
<profile>
<id>product</id>
<properties>
<environment>product</environment>
</properties>
</profile>
</profiles>
<properties>
<run>**/*_signTest.java</run>
</properties>
</project>
\ No newline at end of file
package common;
import io.restassured.response.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.restassured.RestAssured.given;
/**
* Created by hanzhanli on 2017/11/11.
*/
public class BeTested {
//从jenkins爬取变更log,取最新一个,即第一个
private static AbstractMap.SimpleEntry<String,String> getChanges(String url) {
System.out.println("链接:"+url);
Response response=given().header("Accept-Language","zh-CN,zh;q=0.8").get(url);
String s=response.asString();
Document document=Jsoup.parse(s);
Elements elements=null;
String changeTime=null;
try{
elements= document.getElementsByTag("ol");
changeTime=document.getElementsByTag("h2").get(0).getElementsByTag("a").get(0).text();
}catch(Exception e){
return new AbstractMap.SimpleEntry<String,String>("2018-1-24 20:17:09","未修改");
}
String regex="(?<=\\()(.+?)(?=\\))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(changeTime);
String s3=null;
while (matcher.find()) {
s3 = matcher.group(0);
}
/*String s1=changeTime.split("\\(")[1];
String s2=s1.split("\\)")[0];*/
//String s3="2017-11-13 10:14:11";
return new AbstractMap.SimpleEntry<String,String>(s3,elements.get(0).text().replace("detail","").replace(" ",""));
}
//将各job的最新变更放到一个排序map,最新的在最上
public static Map<String,String> getLatestChanges(String[] jobs){
System.out.println("获取以下job的更改信息:"+jobs);
Map<String, String> map = new TreeMap<String, String>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
return compareTime(obj2,obj1);
}
});
for (String job:jobs){
job=job.trim();
String url= "http://tst.deploy.dui88.com/view/duiba/job/"+job+"/changes";
AbstractMap.SimpleEntry entry=getChanges(url);
map.put((String)entry.getKey(),job+":"+(String)entry.getValue());
}
return map;
}
public static void main(String[] args) {
String activityGroup="tuia-activity-center,tuia-ssp-center,tuia-ssp-web,tuia-ssp-manager,tuia-open-web";
String adGroup="tuia-engine,tuia-advert-center,tuia-advert-manager,tuia-advert-web,tuia-engine-billing";
String duibaGroup="credits-home-web,developer-center,goods-access-web,goods-center,activity-access-web,activity-center,trade-center,trade-access-web,duiba-manager,duiba-manager-web";
Map<String,String> map=getLatestChanges(duibaGroup.split(","));
System.out.println(map);
// System.out.println(getChangesWithin(90,map));
//System.out.println(map);
/*Set<String> keySet=map.keySet();
String[] group;
group=new String[]{map.get(keySet.toArray()[0])};
System.out.println(group[0]);*/
}
public static Map<String,String> getChangesWithin(int min, Map<String,String> changes){
if(changes==null){
return null;
}else {
System.out.println("最近更改筛选:" + changes);
Map<String, String> map = new TreeMap<String, String>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
return compareTime(obj2, obj1);
}
});
Set<String> keySet = changes.keySet();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date timeLimit = new Date(System.currentTimeMillis() - min * 60 * 1000);
String limit = sdf.format(timeLimit);
System.out.println(limit);
for (String key : keySet) {
if (compareTime(key, limit) >= 0) {
map.put(key, changes.get(key));
}
}
return map;
}
}
public static int compareTime(String time1,String time2)
{
//如果想比较日期则写成"yyyy-MM-dd"就可以了
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//将字符串形式的时间转化为Date类型的时间
Date a= null;
Date b=null;
try {
a = sdf.parse(time1);
b = sdf.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
//Date类的一个方法,如果a早于b返回true,否则返回false
//return a.getTime()-b.getTime();
if(a.before(b))
return -1;
else if(a.equals(b)){
return 0;
}else
return 1;
}
}
package common;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by hanzhanli on 2017/10/31.
*/
public class ClassResult {
String className;
int count;
List<Map<String,String>> resultList=new ArrayList<>();
public ClassResult(String className){
this.className=className;
}
public void addResult(String testName,String duration,String testOut){
this.count++;
Map<String,String> resultMap=new HashMap<>();
resultMap.put("testName",testName);
resultMap.put("duration",duration);
resultMap.put("testOut",testOut);
this.resultList.add(resultMap);
}
}
package common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* Created by mabo on 2018/9/20
*/
@Configuration
@ComponentScan(basePackages = {"ui","http","common"})
@PropertySource(value = {"duiba.properties"})
public class Config {
@Bean
public PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
pspc.setFileEncoding("UTF-8");
return pspc;
}
}
package common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.Environment;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* Created by hanzhanli on 2017/11/9.
*/
public class DingdingResult {
private static Logger logger = LogManager.getLogger(DingdingResult.class);
Object[] group={"test"};
String project="tuia-media";
String changes="";
int total;
int passCount;
int skipCount;
int failCount;
String resultUrl;
List<String> names = new ArrayList<>();
private transient String activityGroup="tuia-activity-center,tuia-ssp-manager,tuia-open-web,tuia-activity-web";
private transient String duibaGroup="credits-home-web,developer-center,goods-access-web,goods-center,activity-access-web,activity-center,trade-center,trade-access-web,duiba-manager,duiba-manager-web,activity-cms-web,activity-comm-center,consumer-center,goods-access-web,goods-center,hdtool-web,hdtool-center,intersection-service,kvtable-service,plugin-web,plugin-center,prize-center,seckill-web,sign-web,sign-center,stock-service,thirdparty-service,trade-access-web,trade-center";
private transient String adGroup="tuia-engine,tuia-advert-center,tuia-advert-manager,tuia-advert-web,tuia-engine-billing";
private transient String sspGroup="tuia-ssp-center,tuia-ssp-web,tuia-ssp-manager,tuia-open-web";
transient String caseSuites=System.getProperty("test");
private transient String run = System.getProperty("run");
transient ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
transient Environment env=context.getBean(Environment.class);
public transient static String[] name;
String path=null;
public DingdingResult(int total, int passCount, int skipCount, int failCount) throws UnsupportedEncodingException {
logger.info("job-name:"+System.getProperty("JOB_NAME"));
logger.info("属性:"+System.getProperties());
Map<String,String> changeMap=null;
group = duibaGroup.split(",");
changeMap = BeTested.getLatestChanges(duibaGroup.split(","));
project = "duiba-service";
String getName = getByRun(run,"names");
String[] getNames = getName.split(",");
name = getNames;
names.addAll(Arrays.asList(getNames));
Map<String,String> resentChanges=BeTested.getChangesWithin(30,changeMap);
System.out.println(resentChanges);
if(resentChanges!=null&&resentChanges.size()>0){
List<String> changeList=new ArrayList<>();
for(Object key:resentChanges.keySet().toArray()){
//changeList.add(key+"-"+resentChanges.get(key));
if(changes!=null&&changes.length()>0){
changes=changes+","+key+"-"+resentChanges.get(key);
}else
changes=key+"-"+resentChanges.get(key);
}
//group=changeList.toArray();
//this.changes=changeList.toString();
}else {
if(changeMap==null){
this.changes="";
}else {
Set<String> keySet = changeMap.keySet();
this.changes = keySet.toArray()[0] + "-" + changeMap.get(keySet.toArray()[0]);
}
}
if(changes.length()>140){
changes=changes.substring(0,141)+"……";
}
//project="tuia-media";
this.total=total;
this.passCount=passCount;
this.skipCount=skipCount;
this.failCount=failCount;
resultUrl=getresultUrl();
}
private String getresultUrl() throws UnsupportedEncodingException {
String resultUrl=null;
String host=System.getProperty("runEnv");
String serviceLine=null;
String caseSuites=System.getProperty("test");
resultUrl = getByRun(run,"resultUrl");
return resultUrl;
}
public Map<String,Object> getResult() throws UnsupportedEncodingException {
Map<String,Object> result=new HashMap<>();
Object[] mygroup = new Object[1];
mygroup[0]=getByRun(run,"group");
result.put("group",mygroup);
result.put("project",project);
result.put("total",this.total);
result.put("passCount",this.passCount);
result.put("skipCount",this.skipCount);
result.put("failCount",this.failCount);
result.put("resultUrl",this.resultUrl);
List<String> exceptionServices=SFExpress.getExceptionServices();
List<String> exceptionMessage=SFExpress.getExceptionMessage();
String others=null;
if(exceptionServices.size()>0){
others="以下被测服务未启动:"+exceptionServices.toString()+"<br>跳过用例总数:"+this.total;
changes=changes+"<br>"+others;
logger.info(others);
result.put("passCount",0);
result.put("skipCount",this.total);
result.put("failCount",0);
}
if(exceptionMessage.size()>0){
others="以下原因导致测试跳过:"+exceptionMessage.toString()+"<br>跳过用例总数:"+this.total;
changes=changes+"<br>"+others;
logger.info(others);
result.put("passCount",0);
result.put("skipCount",this.total);
result.put("failCount",0);
}
result.put("changes",this.changes+"<br>");
if(this.failCount>0||exceptionServices.size()>0||exceptionMessage.size()>0){
try{
String name = this.changes.split("—")[1].split("/")[0];
names.add(name);
}catch(Exception e){
System.out.println(e);
}
}else {
names.clear();
}
result.put("names",names);
return result;
}
public String getByRun(String run,String type) throws UnsupportedEncodingException {
run = run.substring(run.indexOf("_")+1, run.indexOf("."));
run =this.env.getProperty(run+"."+type);
return new String(run.getBytes("ISO-8859-1"), "UTF-8");//ISO-8859-1
}
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "**/*_signTest.java";
s = s.substring(s.indexOf("_")+1,s.indexOf("."));
System.out.println(s);
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Environment env=context.getBean(Environment.class);
String ss = env.getProperty("pluginTest.names");
System.out.println(ss =new String(ss.getBytes("ISO-8859-1"), "UTF-8"));
String run = "**/*_signTest.java";
String type = "names";
run = run.substring(run.indexOf("_")+1, run.indexOf("."));
run =env.getProperty(run+"."+type);
System.out.println(run = new String(run.getBytes("ISO-8859-1"), "UTF-8"));
String[] sp =run.split(",");
List<String> list = Arrays.asList(sp);
List<String> names = new ArrayList<>();
names.addAll(list);
}
}
\ No newline at end of file
package common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import javax.annotation.PostConstruct;
/**
* Created by mabo on 2018/9/20
*/
@ContextConfiguration(classes =Config.class)
public class DuibaBase extends AbstractTestNGSpringContextTests {
@Autowired
public MysqlConnPool jdbc;
@PostConstruct
public void setUp() {
System.out.println("setUp执行");
jdbc.initDataSource();
}
}
package common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Reporter;
import sun.reflect.Reflection;
/**
* Created by mabo on 2018/10/8
*/
public class DuibaLog {
private Logger logger;
private DuibaLog(){
/*Class c = Reflection.getCallerClass(2);
//Field logger=c.getField("logger");
Field[] fields= c.getDeclaredFields();
for (Field field:fields){
System.out.println(field);
}*/
Logger logger= LogManager.getLogger(Reflection.getCallerClass(3));
//logger=LogManager.getRootLogger();
//logger=LogManager.getLogger("name");
this.logger=logger;
}
private DuibaLog(Logger logger){
this.logger=logger;
}
public static DuibaLog getLogger(){
return new DuibaLog();
}
public void info(String msg){
logger.info(msg);
Reporter.log(msg);
}
}
package common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.*;
import org.testng.xml.XmlSuite;
import org.uncommons.reportng.HTMLReporter;
import java.io.*;
import java.util.*;
/**
* Created by hanzhanli on 2017/10/31.
*/
public class DuibaReporter implements IReporter {
Logger logger = LogManager.getLogger(DuibaReporter.class);
@Override
public void generateReport(List<XmlSuite> list, List<ISuite> list1, String s) {
logger.info("test:"+System.getProperty("test"));
// logger.info("exceptionServices-Report:"+SFExpress.getExceptionServices().toString());
// logger.info("exceptionServices-size:"+SFExpress.getExceptionServices().size());
List<SuiteResult> suiteResultList=new ArrayList<>();
List<String> failCase = new ArrayList<>();
for(ISuite suite:list1){
String suiteName=suite.getName();
//logger.info("suiteName:"+suiteName);
SuiteResult suiteResult=new SuiteResult(suiteName);
for (ISuiteResult result : suite.getResults().values()){
//logger.info(result.getTestContext().getName());
//System.out.println(result.getTestContext().getName());
//System.out.println(result.getTestContext().getPassedTests());
IResultMap iResultMap=result.getTestContext().getSkippedConfigurations();
Set<ITestResult> resultSet=iResultMap.getAllResults();
Object[] iTestResult=resultSet.toArray();
if(iTestResult.length>0) {
Object o = iTestResult[0];
//String message = ((ITestResult) o).getThrowable().getMessage();
//logger.info("skipped-info:"+message);
}
SortedMap<IClass, List<ITestResult>> passMap=null; //HTMLReporter.sortByTestClass(result.getTestContext().getPassedTests());
if(!passMap.isEmpty()){
generateStatusResult(passMap,suiteResult,"pass");
}
SortedMap<IClass, List<ITestResult>> skipMap=null; //HTMLReporter.sortByTestClassTool(result.getTestContext().getSkippedTests());
if(!skipMap.isEmpty()){
generateStatusResult(skipMap,suiteResult,"skip");
}
SortedMap<IClass, List<ITestResult>> failMap=null;// HTMLReporter.sortByTestClassTool(result.getTestContext().getFailedTests());
logger.info("***************************************************");
if(!failMap.isEmpty()){
logger.info("***************************************************");
logger.info("错误case");
failMap.forEach((k,v)->{
logger.info("k.getName()"+k.getName());
StringBuilder ca = new StringBuilder();
ca.append(k.getName());
v.forEach(itr->{
logger.info("itr.getName()"+itr.getName());
ca.append(".");
ca.append(itr.getName());
failCase.add(ca.toString());
});
});
logger.info("***************************************************");
generateStatusResult(failMap,suiteResult,"fail");
}
//logger.info(new Gson().toJson(suiteResult));
}
suiteResultList.add(suiteResult);
}
String testResult=new Gson().toJson(suiteResultList);
logger.info("test result:"+testResult);
String path=s+File.separator+"result.json";
File file=new File(path);
DuibaReporter.save2File(file,testResult);
SuiteResult sr=suiteResultList.get(0);
int total=sr.getTotal();
int passCount=sr.getPassCount();
int failCount=sr.getFailCount();
int skipCount=sr.getSkipCount();
DingdingResult ddResult=null;
try{
ddResult=new DingdingResult(total,passCount,skipCount,failCount);
}catch (Exception e){
e.printStackTrace();
}
//logger.info(System.getProperty("noticeDD"));
boolean noticeDD=Boolean.parseBoolean(System.getProperty("noticeDD"));
boolean noticePerson=Boolean.parseBoolean(System.getProperty("noticePerson"));
boolean sendPlatform=Boolean.parseBoolean(System.getProperty("sendPlatform"));
//logger.info("noticeDD----:"+noticeDD);
Gson gson=new GsonBuilder().create();
logger.info("gson.toJson(ddResult)~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
logger.info("钉钉通知:"+gson.toJson(ddResult));
Map<String,Object> map = null;
try {
map = ddResult.getResult();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
map.put("failCase",failCase);
if(sendPlatform)
Postman.sendTestPlatform(map);
if(noticeDD){
if(!noticePerson){
map.put("names",new ArrayList<>());
}
logger.info("noticeDD:"+noticeDD);
Postman.send2Dingding(map);
}
}
private static void generateStatusResult(SortedMap<IClass, List<ITestResult>> StatusMap, SuiteResult suiteResult, String key){
List<ClassResult> passClassResultList=new ArrayList<>();
int caseCount=0;
for(IClass testClass: StatusMap.keySet()){
List<ITestResult> classResultList= StatusMap.get(testClass);
String className=testClass.getName();
ClassResult classResult=new ClassResult(className);
for(ITestResult methodResult:classResultList){
caseCount++;
//classResult.count++;
String title=methodResult.getName();
String description=methodResult.getMethod().getDescription();
if(description!=null&&description.length()>0){
title=title+":"+description;
}
String testOut=null;
if(key.equals("pass")){
testOut=Reporter.getOutput(methodResult).toString();
}else if(key.equals("skip")){
testOut= DuibaReporter.getDependentMethods(methodResult);
}else if(key.equals("fail")){
String throwable=methodResult.getThrowable().toString();
testOut=Reporter.getOutput(methodResult).toString()+";"+throwable;
}
long duration=methodResult.getEndMillis()-methodResult.getStartMillis();
classResult.addResult(title,String.valueOf(duration),testOut);
}
passClassResultList.add(classResult);
}
suiteResult.addResult(key,passClassResultList,caseCount);
}
private static String commaSeparate(Collection<String> strings)
{
StringBuilder buffer = new StringBuilder();
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext())
{
String string = iterator.next();
buffer.append(string);
if (iterator.hasNext())
{
buffer.append(", ");
}
}
return buffer.toString();
}
private static String getDependentMethods(ITestResult result)
{
String[] methods = result.getMethod().getMethodsDependedUpon();
return commaSeparate(Arrays.asList(methods));
}
private static void save2File(File file,String content){
OutputStream out = null;
Writer writer =null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
writer = new BufferedWriter(new OutputStreamWriter(out,"utf-8"));
writer.write(content);
writer.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer!=null) try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// private SortedMap<IClass, List<ITestResult>> sortByTestClass(IResultMap results)
// {
// SortedMap<IClass, List<ITestResult>> sortedResults = new TreeMap<IClass, List<ITestResult>>(CLASS_COMPARATOR);
// for (ITestResult result : results.getAllResults())
// {
// List<ITestResult> resultsForClass = sortedResults.get(result.getTestClass());
// if (resultsForClass == null)
// {
// resultsForClass = new ArrayList<ITestResult>();
// sortedResults.put(result.getTestClass(), resultsForClass);
// }
// int index = Collections.binarySearch(resultsForClass, result, RESULT_COMPARATOR);
// if (index < 0)
// {
// index = Math.abs(index + 1);
// }
// resultsForClass.add(index, result);
// }
// return sortedResults;
// }
public static void test(int i){
i+=1;
}
public static void main(String[] args) {
// Calendar c = Calendar.getInstance();
// Date date = new Date();
// c.setTime(date);
// int week_num =c.get(Calendar.WEEK_OF_YEAR);
// System.out.println(week_num);
// System.out.println(26%2==0);
int i = 2;
test(i);
System.out.println(i);
}
}
package common;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.annotations.BeforeSuite;
/**
* Created by mabo on 2018/10/9
*/
public class DuibaTestBase extends DuibaBase {
// @Autowired
// public MysqlConnPool jdbc;
//
// @BeforeSuite
// public void setUp() {
// if(jdbc == null){
// return;
// }
//
// jdbc.getDbs();
//
// }
}
package common;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by mabo on 2018/10/9
*/
//@Component
@Service
public class MysqlConnPool {
//数据库用户名
@Value("${db.name}")
String USERNAME;
//数据库密码
@Value("${db.password}")
String PASSWORD;
//url
@Value("${db.url}")
String URL;
//驱动信息
@Value("${db.driver}")
String DRIVER;
//最大连接池
@Value("${db.maxtotal}")
int maxtotal;
public BasicDataSource bds;
public DuibaLog log = DuibaLog.getLogger();
public void initDataSource(){
if(bds != null){
return;
}
synchronized (MysqlConnPool.class){
if(bds != null){
return;
}
System.out.println("初始化数据库");
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName(DRIVER);
bds.setUrl(URL);
bds.setUsername(USERNAME);
bds.setPassword(PASSWORD);
bds.setMaxTotal(maxtotal);
this.bds = bds;
}
}
/**
* 查询结果只有一行数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return map
* @throws SQLException
*/
public Map<String, Object> findSimpleResult(String sql, Object ...params) throws SQLException {
Map<String, Object> map = null;
try(Connection conn = bds.getConnection()){
map = new HashMap<String, Object>();
int index = 1;
PreparedStatement pstmt = conn.prepareStatement(sql);
log.info(conn.toString());
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
ResultSet resultSet = pstmt.executeQuery();//返回查询结果
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();
while(resultSet.next()){
for(int i=0; i<col_len; i++ ){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}catch(Exception e){
e.printStackTrace();
}
return map;
}
/**
* 增加、删除、改
* @param sql sql语句
* @param params 参数,替换 ?
* @return true or false
* @throws SQLException
*/
public boolean update(String sql, Object ...params) throws SQLException{
Connection conn=null;
boolean flag = false;
try{
int result = -1;
conn = bds.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
int index = 1;
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
result = pstmt.executeUpdate();
flag = result > 0 ? true : false;
}catch(Exception e){
e.printStackTrace();
}finally {
if(conn!=null) conn.close();
}
return flag;
}
/**
* 返回多条数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return list
* @throws SQLException
*/
public List<Map<String, Object>> findModeResult(String sql, Object ...params) throws SQLException{
Connection conn=null;
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try{
int index = 1;
conn = bds.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
ResultSet resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while(resultSet.next()){
Map<String, Object> map = new HashMap<String, Object>();
for(int i=0; i<cols_len; i++){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(conn!=null) conn.close();
}
return list;
}
}
package common;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by mabo on 2018/10/8
*/
public class MysqlUtils {
//数据库用户名
private String USERNAME;// = "root";
//数据库密码
private String PASSWORD; //= "yanzi";
//驱动信息
private String DRIVER="com.mysql.jdbc.Driver";
private BasicDataSource bds;
public DuibaLog log = DuibaLog.getLogger();
//数据库地址
private String URL;// = "jdbc:mysql://localhost:3306/mydb";
private Connection connection;
private PreparedStatement pstmt;
private ResultSet resultSet;
private DuibaLog logger = DuibaLog.getLogger();
private MysqlUtils(String username,String password,String url){
USERNAME = username;
PASSWORD = password;
URL = url;
connection = getConnection();
}
public MysqlUtils(){
bds = getDbs();
}
/**
*
* @param username 用户名
* @param password 密码
* @param ip 数据库ip
* @param port 端口号
* @param databaseName 数据库名
*/
public MysqlUtils(String username,String password,String ip,String port,String databaseName){
this(username,password,"jdbc:mysql://"+ip+":"+port+"/"+databaseName);
}
/**
* 阿里云数据库连接
* @param databaseName 数据库名字
*/
public MysqlUtils(String databaseName){
this("duiba_test","svbP3KUw2PurAnBb2rbs3vohF","rdswy2b9wy53044250u1o.mysql.rds.aliyuncs.com","3306",databaseName);
}
public static MysqlUtils mysqlDuiba(String databaseName){
return new MysqlUtils("duiba_test","svbP3KUw2PurAnBb2rbs3vohF","rdswy2b9wy53044250u1o.mysql.rds.aliyuncs.com","3306",databaseName);
}
/**
* 获得数据库的连接
* @return
*/
public Connection getConnection(){
try {
try {
Class.forName(DRIVER);
logger.info("数据库连接成功!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public BasicDataSource getDbs(){
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://rdswy2b9wy53044250u1o.mysql.rds.aliyuncs.com:3306/");
bds.setUsername("duiba_test");
bds.setPassword("svbP3KUw2PurAnBb2rbs3vohF");
bds.setMaxTotal(2);
return bds;
}
public Connection getconnectionByDataSource() throws SQLException {
return bds.getConnection();
}
/**
* 增加、删除、改
* @param sql sql语句
* @param params 参数,替换 ?
* @return true or false
* @throws SQLException
*/
public boolean update(String sql, Object ...params)throws SQLException{
boolean flag = false;
int result = -1;
pstmt = connection.prepareStatement(sql);
int index = 1;
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
result = pstmt.executeUpdate();
flag = result > 0 ? true : false;
return flag;
}
/**
* 查询结果只有一行数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return map
* @throws SQLException
*/
public Map<String, Object> findSimpleResult(String sql, Object ...params) throws SQLException{
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
resultSet = pstmt.executeQuery();//返回查询结果
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();
while(resultSet.next()){
for(int i=0; i<col_len; i++ ){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
return map;
}
/**
* 返回多条数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return list
* @throws SQLException
*/
public List<Map<String, Object>> findModeResult(String sql, Object ...params) throws SQLException{
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while(resultSet.next()){
Map<String, Object> map = new HashMap<String, Object>();
for(int i=0; i<cols_len; i++){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
/**
* 释放数据库连接
*/
public void releaseConn(){
if(resultSet != null){
try{
resultSet.close();
logger.info("数据库连接释放成功");
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
package common;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import static io.restassured.RestAssured.given;
/**
* Created by hanzhanli on 2017/11/9.
*/
public class Postman {
static String dingdingUrl="https://shark.dui88.com/test/integration";
static String testPlatformUrl = "http://101.37.27.82:8080/insert";
//dingdingUrl="http://www.json.cn/";
private Logger logger = LogManager.getLogger(Postman.class);
public static void send2Dingding(Map result){
System.out.println("Dingding:"+result);
RestAssuredConfig config = RestAssured.config();
config.getHttpClientConfig()
.setParam(ClientPNames.CONN_MANAGER_TIMEOUT, 150000) // HttpConnectionManager connection return time
.setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 150000) // Remote host connection time
.setParam(CoreConnectionPNames.SO_TIMEOUT, 150000) ; // Remote host response time
Response response=given().relaxedHTTPSValidation().contentType(ContentType.JSON).body(result).post(dingdingUrl);
System.out.println("--------DingdingTest--------:");
response.prettyPrint();
System.out.println("--------DingdingTest1--------:");
Boolean bl = response.jsonPath().getString("success").equals("false");
if(bl){
String[] name = DingdingResult.name;
result.put("names",name);
response=given().contentType(ContentType.JSON).body(result).post(dingdingUrl);
System.out.println("--------DingdingTest2--------:");
response.prettyPrint();
System.out.println("--------DingdingTest2--------:");
}
}
public static void sendTestPlatform(Map result){
Response response=given().contentType(ContentType.JSON).body(result).post(testPlatformUrl);
System.out.println("--------testPlatform--------:");
response.prettyPrint();
System.out.println("--------testPlatform--------:");
}
public static Boolean getName(){
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
int week_num =c.get(Calendar.WEEK_OF_YEAR);
System.out.println(week_num);
System.out.println(week_num==0);
if(week_num%2==0)return true;
else return false;
}
}
package common;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import com.sun.net.httpserver.Authenticator;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
/**
* Created by mabo on 2018/9/29
*/
public class RetryListener implements IAnnotationTransformer {
public void transform(ITestAnnotation annotation, Class testClass,
Constructor testConstructor, Method testMethod) {
IRetryAnalyzer retry = annotation.getRetryAnalyzer();
if (retry == null) {
annotation.setRetryAnalyzer(RetryToRunCase.class);
}
}
}
\ No newline at end of file
package common;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
/**
* Created by mabo on 2018/9/29
*/
public class RetryToRunCase implements IRetryAnalyzer {
private int retryCount = 0;
private int maxRetryCount = 0; // retry a failed test 2 additional times
public boolean retry(ITestResult result) {
if (retryCount <maxRetryCount) {
retryCount++;
return true;
}
return false;
}
}
package common;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by hanzhanli on 2017/11/30.
*/
public class SFExpress {
private final static List<String> exceptionServices=new ArrayList<>();
private final static List<String> exceptionMessage=new ArrayList<>();
private final static Set<String> toBeTestedServices=new HashSet<>();
public static void addToBeTestedServices(Set<String> services){
toBeTestedServices.addAll(services);
}
public static void addExceptionService(String service){
exceptionServices.add(service);
}
public static void addExceptionMessage(String message){
exceptionMessage.add(message);
}
public static void addExceptionService(List<String> service){
exceptionServices.addAll(service);
}
public static Set<String> getToBeTestedServices(){
return toBeTestedServices;
}
public static List<String> getExceptionServices(){
return exceptionServices;
}
public static List<String> getExceptionMessage(){
return exceptionMessage;
}
}
package common;
import org.testng.IClass;
import org.testng.ISuiteResult;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.uncommons.reportng.HTMLReporter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
/**
* Created by hanzhanli on 2017/11/1.
*/
public class SuiteResult {
String suiteName;
int total=0;
int passCount=0;
int skipCount=0;
public int getTotal() {
return total;
}
public int getPassCount() {
return passCount;
}
public int getSkipCount() {
return skipCount;
}
public int getFailCount() {
return failCount;
}
int failCount=0;
Map<String,List<ClassResult>> result=new HashMap<>();
public SuiteResult(String suiteName){
this.suiteName=suiteName;
}
public void addResult(String key,List<ClassResult> classResultList,int count){
result.put(key,classResultList);
this.total=total+count;
if(key.equals("pass")){
this.passCount=count;
}else if(key.equals("skip")){
this.skipCount=count;
}else if (key.equals("fail")){
this.failCount=count;
}
}
//{"suiteName":"myName","results":{"total":3,"data":{"pass":{"count":1,"data":{"method":"mathodNameB","duration":10,"out":"contents"}},"skip":null,"fail":null}}}
// public SuiteResult(ISuiteResult result){
// this.result=new HashMap<>();
// int total=0;
// Map<String,Object> data=new HashMap<>();
// SortedMap<IClass, List<ITestResult>> failedMap = HTMLReporter.sortByTestClassTool(result.getTestContext().getFailedConfigurations());
// Map<String,Object> failedResultMap=new HashMap<>();
//
// for(IClass testClass:failedMap.keySet()){
// List<ITestResult> testResultList=failedMap.get(testClass);
//
// for(ITestResult testResult:testResultList){
//
// }
// }
//
//
// }
public Map<String,String> getMethodResult(ITestResult testResult){
Map<String,String> methodResult=new HashMap<>();
String title=testResult.getName();
String description=testResult.getMethod().getDescription();
if(description!=null&&description.length()>0){
title=title+":"+description;
}
String duration=String.valueOf(testResult.getEndMillis()-testResult.getStartMillis());
String output= Reporter.getOutput(testResult).toString();
methodResult.put("title",title);
methodResult.put("duration",duration);
methodResult.put("output",output);
return methodResult;
}
}
package common;
import java.util.Iterator;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
/**
* Created by mabo on 2018/9/29
*/
public class TestListener implements ITestListener {
private static DuibaLog logger = DuibaLog.getLogger();
public void onFinish(ITestContext context) {
Iterator<ITestResult> listOfFailedTests = context.getFailedTests().getAllResults().iterator();
while (listOfFailedTests.hasNext()) {
ITestResult failedTest = listOfFailedTests.next();
ITestNGMethod method = failedTest.getMethod();
if (context.getFailedTests().getResults(method).size() > 1) {
listOfFailedTests.remove();
} else {
if (context.getPassedTests().getResults(method).size() > 0) {
listOfFailedTests.remove();
}
}
}
}
// Following are all the method stubs that you do not have to implement
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
logger.info("Current Thread Id: " + Thread.currentThread().getId());
}
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
}
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
}
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
}
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
}
}
\ No newline at end of file
package common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by mabo on 2018/10/12
*/
public class TestReport implements IReporter{
private DuibaLog logger = DuibaLog.getLogger();
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
int total=0;
int passCount=0;
int skipCount=0;
int failCount=0;
List<String> failCase = new ArrayList<>();
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
total = context.getAllTestMethods().length;
passCount = context.getPassedTests().size();
failCount = context.getFailedTests().size();
skipCount = context.getSkippedTests().size();
for (ITestNGMethod m:
context.getFailedTests().getAllMethods()) {
String[] classes = m.getTestClass().toString().split(" ");
String cla = classes[classes.length-1];
failCase.add( cla.substring(0,cla.length()-1)+"."+m.getMethodName());
}
}
}
DingdingResult ddResult=null;
try{
ddResult=new DingdingResult(total,passCount,skipCount,failCount);
}catch (Exception e){
e.printStackTrace();
}
boolean noticeDD=Boolean.parseBoolean(System.getProperty("noticeDD"));
boolean noticePerson=Boolean.parseBoolean(System.getProperty("noticePerson"));
boolean sendPlatform=Boolean.parseBoolean(System.getProperty("sendPlatform"));
Gson gson=new GsonBuilder().create();
Map<String,Object> map = null;
try {
map = ddResult.getResult();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
map.put("failCase",failCase);
logger.info("gson.toJson(ddResult)~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
logger.info("钉钉通知:"+gson.toJson(map));
//发送运行结果到自动化数据收集平台
if(sendPlatform)
Postman.sendTestPlatform(map);
//发送钉钉通知
if(noticeDD){
if(!noticePerson){
map.put("names",new ArrayList<>());
}
logger.info("noticeDD:"+noticeDD);
Postman.send2Dingding(map);
}
}
}
package http;
import org.springframework.stereotype.Service;
/**
* Created by mabo on 2018/9/20
*/
@Service
public class Testhttp_Test {
public void test(){
// throw new Exception("hello");
System.out.println("hello");
}
}
package http.cases.SignTest;
import org.testng.SkipException;
import org.testng.annotations.BeforeSuite;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by hanzhanli on 2017/9/21.
*/
public class Server_signTest {
// private DuibaLog logger = DuibaLog.getLogger();
// private Map<String,String> fromMap=new HashMap<>();
// private Map<String,List<String>> logMap=new HashMap<>();
// @BeforeSuite
// public void onStart() {
// //logger.info("job-name:"+System.getProperty("JOB_NAME"));
// //logger.info("属性:"+System.getProperties());
// logger.info("duiba-server开始检测");
// ServiceDoctor serviceDoctor=new ServiceDoctor("duiba-server.properties");
// SFExpress.addToBeTestedServices(serviceDoctor.getToBeTestedServices());
// //fromMap.putAll(serviceDoctor.getLogLenth());
// SFExpress.addExceptionService(serviceDoctor.getExceptionService(60*2));
// logger.info("duiba-server检测完毕");
// logger.info("duiba-server-center开始检测");
// serviceDoctor=new ServiceDoctor("duiba-server-center.properties");
// SFExpress.addToBeTestedServices(serviceDoctor.getToBeTestedServices());
// //fromMap.putAll(serviceDoctor.getLogLenth());
// SFExpress.addExceptionService(serviceDoctor.getExceptionService(60*2));
// logger.info("duiba-server-center检测完毕");
// if(SFExpress.getExceptionServices().size()>0){
// logger.info("服务未启动:"+SFExpress.getExceptionServices().toString());
// throw new SkipException("被测服务未全部启动");
// }
//
// }
public static void main(String[] args) {
// String s = "最近变更:2018-1-3 13:48:07-activity-access-web:疯狂打气球—jiangxixi/疯狂打气球—jiangxixi/\n";
// String name = s.split("—")[1].split("/")[0];
// System.out.println(name);
// List<String> list = new ArrayList<>();
// list.clear();
// Map<String,Object> map = new HashMap<>();
// map.put("name",list);
// ServiceDoctor serviceDoctor=new ServiceDoctor("duiba-server.properties");
}
}
package http.cases.SignTest;
import common.DuibaLog;
import common.DuibaTestBase;
import http.service.Activity.SignactivityService;
import http.service.Authorization;
import http.service.hd.SigninService;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import utils.MatcherString;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import static io.restassured.RestAssured.given;
//@ContextConfiguration(classes = DuibaConfig.class)
public class Signin_signTest extends DuibaTestBase {
@Autowired
SigninService signinService;
@Autowired
Authorization authorization;
@Autowired
SignactivityService signactivityService;
// MysqlUtils jdbc = null;;
DuibaLog logger = DuibaLog.getLogger();
//指定用户
private int uid = 2722;
private Map<String,Object> maptest ;
@BeforeClass
public void beforeclass(){
// jdbc = new MysqlUtils("");
maptest = authorization.dafuwengLogin(uid);
logger.info("_ac:"+maptest.get("_ac"));
try {
jdbc.update("delete from sign_record.tb_sign_log where consumer_id=100028002 and source_relation_id=69");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id=100028002 and source_relation_id=69");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id=100028002 and source_relation_id=65");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id=100028002 and source_relation_id=65");
} catch (SQLException e) {
logger.info("数据库更新异常");
}
}
// @AfterClass
// public void afterclass()
// {
//
// jdbc.releaseConn();
// }
// @Test(description = "日历签到")
//17.日历签到活动
public void sign(){
Response response = signinService.getSignActivityUrl("2239","58");
String url = MatcherString.getString(response.asString(),"\"resultUrl\": \"(.*?)\"",1);
System.out.println(url);
response = given(). cookies(maptest).get(url);
response.prettyPrint();
System.out.println(response.getDetailedCookies());
}
@Test
public void 签到_今日签到() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//签到信息查询
Response response = signactivityService.getSignInfo(maptest,"65");
//今日奖励抽奖次数
String activityCount = response.jsonPath().getString("signInfoVO.activityCount");
//明天签到奖励抽奖次数
String activityCountTomorrow = response.jsonPath().getString("signInfoVO.activityCountTomorrow");
//今日是否签到
String todaySigned = response.jsonPath().getString("signInfoVO.todaySigned");
//连续签到天数
String continueDay = response.jsonPath().getString("signInfoVO.continueDay");
Assert.assertEquals(activityCount,"1","今日抽奖次数不正确");
Assert.assertEquals(activityCountTomorrow,"2","明天签到奖励抽奖次数不正确");
Assert.assertEquals(todaySigned,"false","今日是否签到不正确");
Assert.assertEquals(continueDay,"0","连续签到天数不正确");
//签到
response = signactivityService.doSign(maptest,"65");
//今日是否签到
todaySigned = response.jsonPath().getString("signInfoVO.todaySigned");
//连续签到天数
continueDay = response.jsonPath().getString("signInfoVO.continueDay");
Assert.assertEquals(todaySigned,"true","今日是否签到不正确");
Assert.assertEquals(continueDay,"1","连续签到天数不正确");
//获取签到logId
String logId = response.jsonPath().getString("logId");
response = signactivityService.getSignResult(maptest,logId);
//签到状态
String status = response.jsonPath().getString("status");
//接口异步处理
int i=3;
while(status.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(maptest,logId);
status = response.jsonPath().getString("status");
i--;
}
Assert.assertEquals(status,"2","签到状态不正确");
}
@Test
public void 补签() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
// Map<String,String> map = authorization.dafuwengLogin(uid);
Map consumerCredits= jdbc.findSimpleResult("select * from consumer.consumer_0010 where id=100028002");
logger.info("数据库积分:"+consumerCredits.get("credits"));
//签到信息查询
logger.info("_ac1:"+maptest.get("_ac"));
Response response = signactivityService.getSignInfo(maptest,"69");
//获取当前用户积分
String credits = response.jsonPath().getString("credits");
//补签前一天
response = signactivityService.reSign(maptest,"69",null,getTime(-1));
//补签加抽奖次数
String activityCount = response.jsonPath().getString("data.activityCount");
//补签加积分
String creditsFirst = response.jsonPath().getString("data.credits");
//是否有补签消耗
String hasConsume = response.jsonPath().getString("data.hasConsume");
//补签消耗数量
String reSignConsumeCount = response.jsonPath().getString("data.reSignConsumeCount");
//补签logid
String logId = response.jsonPath().getString("data.logId");
Assert.assertEquals(activityCount,"1","补签加抽奖次数不正确");
Assert.assertEquals(creditsFirst,"1","补签加积分不正确");
Assert.assertEquals(hasConsume,"true","补签消耗与否不正确");
Assert.assertEquals(reSignConsumeCount,"1","补签消耗数量不正确");
response = signactivityService.getSignResult(maptest,logId);
//签到状态
String status = response.jsonPath().getString("status");
//接口异步处理
int i=3;
while(status.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(maptest,logId);
status = response.jsonPath().getString("status");
i--;
}
// response.prettyPrint();
//加积分数量
String addCredits = response.jsonPath().getString("addCredits");
//积分余额
String totalCredits = response.jsonPath().getString("totalCredits");
Assert.assertEquals(addCredits,"1","补签加抽奖次数不正确");
int act = Integer.valueOf(credits);
int exp = Integer.valueOf(credits)+Integer.valueOf(creditsFirst)-Integer.valueOf(reSignConsumeCount);
logger.info("credits:"+credits);
logger.info("creditsSecond:"+creditsFirst);
logger.info("reSignConsumeCount:"+reSignConsumeCount);
Assert.assertEquals(act,exp,"积分与预期不符");
//校验consumer和user表的积分
Thread.sleep(2000);
consumerCredits= jdbc.findSimpleResult("select * from consumer.consumer_0010 where id=100028002");
Map userCredits = jdbc.findSimpleResult("select * from dafuweng.user where id ="+uid);
Assert.assertEquals(consumerCredits.get("credits").toString().trim(),String.valueOf(exp),"consumer积分与预期不符");
Assert.assertEquals(userCredits.get("credits").toString().trim(),String.valueOf(exp),"user积分与预期不符");
//补签前两天
response = signactivityService.reSign(maptest,"69",null,getTime(-2));
//补签加抽奖次数
activityCount = response.jsonPath().getString("data.activityCount");
//补签加积分
String creditsSecond = response.jsonPath().getString("data.credits");
//是否有补签消耗
hasConsume = response.jsonPath().getString("data.hasConsume");
//补签消耗数量
reSignConsumeCount = response.jsonPath().getString("data.reSignConsumeCount");
Assert.assertEquals(activityCount,"2","补签加抽奖次数不正确");
Assert.assertEquals(creditsSecond,"2","补签加积分不正确");
Assert.assertEquals(hasConsume,"true","补签消耗与否不正确");
Assert.assertEquals(reSignConsumeCount,"1","补签消耗数量不正确");
//补签logid
logId = response.jsonPath().getString("data.logId");
response = signactivityService.getSignResult(maptest,logId);
//签到状态
status = response.jsonPath().getString("status");
//接口异步处理
i=3;
while(status.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(maptest,logId);
status = response.jsonPath().getString("status");
i--;
}
// response.prettyPrint();
//加积分数量
addCredits = response.jsonPath().getString("addCredits");
//积分余额
totalCredits = response.jsonPath().getString("totalCredits");
Assert.assertEquals(addCredits,"2","补签加抽奖次数不正确");
act = Integer.valueOf(credits)+1;
exp = Integer.valueOf(credits)+Integer.valueOf(creditsSecond)-Integer.valueOf(reSignConsumeCount);
logger.info("credits:"+credits);
logger.info("creditsSecond:"+creditsSecond);
logger.info("reSignConsumeCount:"+reSignConsumeCount);
Assert.assertEquals(act,exp,"积分与预期不符");
//校验consumer和user表的积分
Thread.sleep(2000);
consumerCredits= jdbc.findSimpleResult("select * from consumer.consumer_0010 where id=100028002");
userCredits = jdbc.findSimpleResult("select * from dafuweng.user where id ="+uid);
Assert.assertEquals(consumerCredits.get("credits").toString().trim(),String.valueOf(exp),"consumer积分与预期不符");
Assert.assertEquals(userCredits.get("credits").toString().trim(),String.valueOf(exp),"user积分与预期不符");
//补签前三天
response = signactivityService.reSign(maptest,"69",null,getTime(-3));
// response.prettyPrint();
String message = response.jsonPath().getString("message");
Assert.assertEquals(message,"补签失败,补签超过限定次数","补签超过限制次数");
}
public String getTime(int amount){
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy",Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, amount);
date = calendar.getTime();
// System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
// System.out.println(time);
return time;
}
public static void main(String[] args) {
// String s="http://wechat.duiba.com.cn/dbredirect/dafuweng?dbredirect=https%3A%2F%2Factivity1.m.duibatest.com.cn%2Fsignactivity%2Findex%3Fid%3D148%26dpm%3D2239.41.1.0%26dcm%3D216.148.49.0%26appKey%3D2wGQc3MZaQsqYFWcX4gguya5PnnS%26open4share%3Dtongdun";
//
// String [] ss = s.split("=");
// System.out.println(0);
// List<String> list = new ArrayList<>();
// list.clear();
// if(list==null){
// System.out.println("555");
// }
//Sun May 06 2018 08:00:00 GMT+0800 (CST)
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy",Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 0);
date = calendar.getTime();
System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
System.out.println(time);
}
}
package http.cases.SignTest;
import common.DuibaLog;
import common.DuibaTestBase;
import http.service.Activity.ActivityPlugDrawInfoService;
import http.service.Activity.SignactivityService;
import http.service.Authorization;
import http.service.hd.SigninService;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
/**
* Created by zhaoran on 2018/6/6.
*/
//@ContextConfiguration(classes = DuibaConfig.class)
public class 周期签到测试_signTest extends DuibaTestBase {
@Autowired
SigninService signinService;
@Autowired
Authorization authorization;
@Autowired
SignactivityService signactivityService;
@Autowired
ActivityPlugDrawInfoService activityPlugDrawInfoService;
// MysqlUtils jdbc = null;
private static DuibaLog logger = DuibaLog.getLogger();
//指定用户
private int uid = 3744;
private String consumer_id = "100085130";
private Map<String,Object> map ;
@BeforeClass
public void beforeclass() {
// jdbc = new MysqlUtils("");
map = authorization.dafuwengLogin(uid);
try {
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=79");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=79");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=88");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=88");
} catch (SQLException e) {
logger.info("数据库更新异常");
}
}
// @AfterClass
// public void afterclass() {
// jdbc.releaseConn();
// }
@Test(description = "活动id:79,规则:周期2天,签到第3天循环第一天奖励,加一次抽奖机会,加10积分")
public void 周期签到测试() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//补签前天,凑足连续签到2天
Response response_1 = this.resign("79",-2);
Response response_2 = this.resign("79",-1);
// response_2.prettyPrint();
//当日签到之前插件信息查询
Response response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1179");
String limitCount = response_plug.jsonPath().getString("limitCount");
int num = Integer.valueOf(limitCount);
//消耗抽奖次数
while(num>0){
this.plug(uid,"1179");
num--;
}
//签到信息查询
Response response = signactivityService.getSignInfo(uid,"79");
//response.prettyPrint();
//获取当前用户积分
String credits = response.jsonPath().getString("credits");
logger.info("当日签到之前查询用户积分为:"+credits);
credits = String.valueOf(Integer.valueOf(credits)+10);
String acmDay = response.jsonPath().getString("signInfoVO.acmDay");//历史累积签到次数
String acmDays = response.jsonPath().getString("signInfoVO.acmDays");//周期内累计签到天数
String activityCount = response.jsonPath().getString("signInfoVO.activityCount"); //今日奖励抽奖次数
String activityCountTomorrow = response.jsonPath().getString("signInfoVO.activityCountTomorrow"); //明天签到奖励抽奖次数
String continueDay = response.jsonPath().getString("signInfoVO.continueDay"); //连续签到天数
String creditsTody = response.jsonPath().getString("signInfoVO.credits"); //今日奖励积分
String creditsTomorrow = response.jsonPath().getString("signInfoVO.creditsTomorrow"); //明日签到奖励积分
String lastDays = response.jsonPath().getString("signInfoVO.lastDays");//连续签到天数
String todaySigned = response.jsonPath().getString("signInfoVO.todaySigned"); //今日是否签到
Assert.assertEquals(acmDay,"2","历史累积签到次数不正确");
Assert.assertEquals(acmDays,"2","周期内累计签到天数不正确");
Assert.assertEquals(activityCount,"1","今日奖励抽奖次数不正确");
Assert.assertEquals(activityCountTomorrow,"2","明天签到奖励抽奖次数不正确");
Assert.assertEquals(continueDay,"2","连续签到天数不正确");
Assert.assertEquals(creditsTody,"10","今日奖励积分不正确");
Assert.assertEquals(creditsTomorrow,"20","明日签到奖励积分不正确");
Assert.assertEquals(lastDays,"2","连续签到天数不正确");
Assert.assertEquals(todaySigned,"false","今日是否签到状态不正确");
//签到
response = this.sign("79");
String addActivityCount = response.jsonPath().getString("addActivityCount"); //加活动次数
String addCredits = response.jsonPath().getString("addCredits");//加积分
String activityCountStatus = response.jsonPath().getString("activityCountStatus"); //加活动次数状态,0:处理中,1:失败,2:成功
String creditsStatus = response.jsonPath().getString("creditsStatus"); //加积分状态,0:处理中,1:失败,2:成功
Assert.assertEquals(activityCountStatus,"2","签到增加抽奖状态失败");
Assert.assertEquals(addActivityCount,"1","签到增加抽奖次数不正确");
Assert.assertEquals(addCredits,"10","签到增加积分不正确");
Assert.assertEquals(creditsStatus,"2","签到增加积分状态失败");
//当日签到后的信息查询
Response response2 = signactivityService.getSignInfo(uid,"79");
//response.prettyPrint();
todaySigned = response2.jsonPath().getString("signInfoVO.todaySigned");//今日是否签到
acmDay = response2.jsonPath().getString("signInfoVO.acmDay"); //历史累计签到
continueDay = response2.jsonPath().getString("signInfoVO.continueDay"); //连续签到天数
Assert.assertEquals(todaySigned,"true","当日是否签到显示不正确");
Assert.assertEquals(acmDay,"3","历史累积签到次数不正确");
Assert.assertEquals(continueDay,"3","连续签到天数不正确");
//获取当前用户积分
String creditsNew = response2.jsonPath().getString("credits");
logger.info("签到之后查询签到的积分为:"+creditsNew);
Assert.assertEquals(creditsNew,credits,"签到之后积分计算不正确");
//签到之后插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1179");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"1","签到之后未增加插件抽奖次数");
logger.info("当日签到之后插件抽奖次数:"+limitCount);
//插件工具抽奖
this.plug(uid,"1179");
//抽奖之后插件信息查询
Thread.sleep(1000);
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1179");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","抽奖之后插件抽奖次数不正确");
logger.info("抽奖之后插件抽奖次数:"+limitCount);
}
@Test(description = "活动id:88,规则:周期7天,第3天断签,第4天签到奖励按第一天算")
public void 周期签到_断签() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
String act_id = "88";
String plug_id = "2165";
//补签前天和大前天, 无补签奖励
Response resign_res = this.resign(act_id, -2);
String result = resign_res.jsonPath().getString("success");
Assert.assertEquals(result, "true","补签前天失败");
resign_res = this.resign(act_id, -3);
result = resign_res.jsonPath().getString("success");
Assert.assertEquals(result, "true","补签大前天失败");
//签到前查询getSignInfo接口信息
Response signInfo_res = signactivityService.getSignInfo(uid, act_id);
int consumerCredits = Integer.valueOf(signInfo_res.jsonPath().getString("credits"));
logger.info("今日签到前查询用户积分为: " + consumerCredits);
//签到前查询插件信息
Response plug_res = activityPlugDrawInfoService.getPrizeInfo(map, plug_id);
int limitCount = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
logger.info("今日签到前插件抽奖次数为: " + limitCount);
//签到今日, getSignResult接口校验
Response sign_res = this.sign(act_id);
String addActivityCount = sign_res.jsonPath().getString("addActivityCount");
Assert.assertEquals(addActivityCount, "1", "加抽奖次数不正确");
String activityCountStatus = sign_res.jsonPath().getString("activityCountStatus");
Assert.assertEquals(activityCountStatus, "2", "签到加抽奖状态不正确");
String addCredits = sign_res.jsonPath().getString("addCredits");
Assert.assertEquals(addCredits, "1", "签到加积分不正确");
String creditsStatus = sign_res.jsonPath().getString("creditsStatus");
Assert.assertEquals(creditsStatus, "2", "签到加积分状态不正确");
//getSignInfo接口信息校验
signInfo_res = signactivityService.getSignInfo(uid, act_id);
String todaySigned = signInfo_res.jsonPath().getString("signInfoVO.todaySigned");
Assert.assertEquals(todaySigned, "true", "今日签到状态不正确");
String credits = signInfo_res.jsonPath().getString("signInfoVO.credits");
Assert.assertEquals(credits, "1", "今日签到奖励积分不正确");
String activityCount = signInfo_res.jsonPath().getString("signInfoVO.activityCount");
Assert.assertEquals(activityCount, "1", "今日签到加抽奖次数不正确");
int consumerCreditsNew = Integer.valueOf(signInfo_res.jsonPath().getString("credits"));
logger.info("今日签到后用户积分为: " + consumerCreditsNew);
Assert.assertEquals(consumerCreditsNew, consumerCredits + 1, "签到后用户增加积分不正确");
//getPrizeInfo接口信息校验
plug_res = activityPlugDrawInfoService.getPrizeInfo(map, plug_id);
int limitCountNew = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
logger.info("今日签到后插件抽奖次数为:" + limitCountNew);
Assert.assertEquals(limitCountNew, limitCount + 1, "今日签到加抽奖次数不正确");
}
// 获取时间方法
public String getTime(int amount){
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy", Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, amount);
date = calendar.getTime();
// System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
// System.out.println(time);
return time;
}
//签到
public Response sign(Map cookies,String activityId) throws Exception {
//签到
Response response = signactivityService.doSign(cookies,activityId);
//获取签到logId
String logId = response.jsonPath().getString("logId");
response = signactivityService.getSignResult(cookies,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0")|| activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
public Response sign(String activityId) throws Exception {
//签到
Response response = signactivityService.doSign(map,activityId);
//获取签到logId
String logId = response.jsonPath().getString("logId");
response = signactivityService.getSignResult(map,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0")|| activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(map,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
//补签
public Response resign(Map cookies,String activityId,int data) throws Exception {
//补签前天,凑足累计签到2天
Response response = signactivityService.reSign(cookies,activityId,null,getTime(data));
//补签logid
String logId = response.jsonPath().getString("data.logId");
response = signactivityService.getSignResult(cookies,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0") || activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
public Response resign(String activityId,int data) throws Exception {
//补签前天,凑足累计签到2天
Response response = signactivityService.reSign(map,activityId,null,getTime(data));
//补签logid
String logId = response.jsonPath().getString("data.logId");
response = signactivityService.getSignResult(map,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0") || activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(map,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
//插件抽奖
public void plug(int uid,String id) throws Exception {
Response response = activityPlugDrawInfoService.doJoinPlugdraw(uid,id);
String orderId = response.jsonPath().getString("orderId");
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
int i = 30;
while ("成功-等待".equals(response.jsonPath().getString("message")) && i > 0) {
Thread.sleep(1000);
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
i--;
}
}
//@Test
public void plug2() throws Exception {
Response response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1179");
response_plug.prettyPrint();
//
Response response = activityPlugDrawInfoService.doJoinPlugdraw(uid,"1179");
String orderId = response.jsonPath().getString("orderId");
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
int i = 10;
while ("成功-等待".equals(response.jsonPath().getString("message")) && i > 0) {
Thread.sleep(500);
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
i--;
}
response.prettyPrint();
}
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy",Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 0);
date = calendar.getTime();
System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
System.out.println(time);
}
}
package http.cases.SignTest;
import common.DuibaLog;
import common.DuibaTestBase;
import http.service.Activity.ActivityPlugDrawInfoService;
import http.service.Activity.SignactivityService;
import http.service.Authorization;
import http.service.hd.SigninService;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
/**
* Created by zhaoran on 2018/6/5.
*/
//@ContextConfiguration(classes = DuibaConfig.class)
public class 累计签到测试_signTest extends DuibaTestBase {
@Autowired
SigninService signinService;
@Autowired
Authorization authorization;
@Autowired
SignactivityService signactivityService;
@Autowired
ActivityPlugDrawInfoService activityPlugDrawInfoService;
// MysqlUtils jdbc = null;
private static DuibaLog logger = DuibaLog.getLogger();
//指定用户
private int uid = 3745;
private String consumer_id = "100085131";
private Map<String,Object> map;
@BeforeClass
public void beforeclass() {
// jdbc = new MysqlUtils("");
map = authorization.dafuwengLogin(uid);
try {
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=82");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=82");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=83");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=83");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=91");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=91");
} catch (SQLException e) {
logger.info("数据库更新异常");
}
}
// @AfterClass
// public void afterclass() {
// jdbc.releaseConn();
// }
//@Test(description = "活动id:82,规则:累计签到2天,加一次抽奖机会,加10积分")
public void 连续_累计奖励() throws Exception {
//签到信息查询
Response response = signactivityService.getSignInfo(map,"82");
//获取当前用户积分(没补签之前的,getSignInfo接口中的返回字段)
String credits = response.jsonPath().getString("credits");
logger.info("没签之前查询签到的积分为:"+credits);
credits = String.valueOf(Integer.valueOf(credits)+10);
//今日奖励抽奖次数
String activityCount = response.jsonPath().getString("signInfoVO.activityCount");
//明日奖励抽奖次数
String activityCountTomorrow = response.jsonPath().getString("signInfoVO.activityCountTomorrow");
//今日奖励积分
String creditsInfo = response.jsonPath().getString("signInfoVO.credits");
//明日奖励积分
String creditsTomorrow = response.jsonPath().getString("signInfoVO.creditsTomorrow");
//今日是否签到
String todaySigned = response.jsonPath().getString("signInfoVO.todaySigned");
//连续签到天数
String continueDay = response.jsonPath().getString("signInfoVO.continueDay");
Assert.assertEquals(activityCount,"0","今日签到增加抽奖次数不正确");
Assert.assertEquals(activityCountTomorrow,"1","明日签到增加抽奖次数不正确");
Assert.assertEquals(creditsInfo,"0","今日签到增加积分不正确");
Assert.assertEquals(creditsTomorrow,"10","明日签到增加积分不正确");
Assert.assertEquals(todaySigned,"false","今日是否签到不正确");
Assert.assertEquals(continueDay,"0","连续签到天数不正确");
//当日签到之前插件信息查询
Response response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
String limitCount = response_plug.jsonPath().getString("limitCount");
int num = Integer.valueOf(limitCount);
//消耗抽奖次数
while(num>0){
this.plug(uid,"1154");
num--;
}
//签到之前插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","签到之前插件抽奖次数不正确");
logger.info("签到之前插件抽奖次数:"+limitCount);
//签到当日
response = this.sign(map,"82");
//补签前天,凑足累计签到2天
response = this.resign(map,"82",-1);
//加活动次数
String addActivityCount = response.jsonPath().getString("addActivityCount");
//加积分
String addCredits = response.jsonPath().getString("addCredits");
//加活动次数状态,0:处理中,1:失败,2:成功
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
//加积分状态,0:处理中,1:失败,2:成功
String creditsStatus = response.jsonPath().getString("creditsStatus");
Assert.assertEquals(activityCountStatus,"2","签到增加抽奖状态失败");
Assert.assertEquals(addActivityCount,"1","签到增加抽奖次数不正确");
Assert.assertEquals(addCredits,"10","签到增加积分不正确");
Assert.assertEquals(creditsStatus,"2","签到增加积分状态失败");
//签到信息查询
Response response2 = signactivityService.getSignInfo(map,"82");
//今日是否签到
todaySigned = response2.jsonPath().getString("signInfoVO.todaySigned");
Assert.assertEquals(todaySigned,"true","当日是否签到显示不正确");
//历史累计签到数
String acmDay = response2.jsonPath().getString("signInfoVO.acmDay");
Assert.assertEquals(acmDay,"2","历史累积签到次数不正确");
//获取当前用户积分
String creditsNew = response2.jsonPath().getString("credits");
logger.info("签到之后查询签到的积分为:"+creditsNew);
Assert.assertEquals(creditsNew,credits,"签到之后积分未增加");
//签到之后插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
limitCount = response_plug.jsonPath().getString("limitCount");
String limitScope = response_plug.jsonPath().getString("limitScope");
Assert.assertEquals(limitCount,"1","签到之后未增加插件抽奖次数");
Assert.assertEquals(limitScope,"1","签到之后未增加插件抽奖次数的类型不对");
logger.info("签到之后插件抽奖次数:"+limitCount);
//插件工具抽奖
this.plug(uid,"1154");
//抽奖之后插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","抽奖之后插件抽奖次数不正确");
logger.info("抽奖之后插件抽奖次数:"+limitCount);
}
@Test(description = "活动id:83,规则:累计签到2天,加一次抽奖机会,加10积分")
public void 周期_累计奖励() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//开发者修改周期
String data = this.getTime_data(-30);
logger.info("设置周期起始日期为:"+data);
signactivityService.configEdit("83",data);
Thread.sleep(3000);
//签到信息查询
Response response = signactivityService.getSignInfo(map,"83");
//获取当前用户积分(没补签之前的,getSignInfo接口中的返回字段)
String credits = response.jsonPath().getString("credits");
logger.info("没签之前查询签到的积分为:"+credits);
credits = String.valueOf(Integer.valueOf(credits)+10);
//今日奖励抽奖次数
String activityCount = response.jsonPath().getString("signInfoVO.activityCount");
//明日奖励抽奖次数
String activityCountTomorrow = response.jsonPath().getString("signInfoVO.activityCountTomorrow");
//今日奖励积分
String creditsInfo = response.jsonPath().getString("signInfoVO.credits");
//明日奖励积分
String creditsTomorrow = response.jsonPath().getString("signInfoVO.creditsTomorrow");
//今日是否签到
String todaySigned = response.jsonPath().getString("signInfoVO.todaySigned");
//连续签到天数
String continueDay = response.jsonPath().getString("signInfoVO.continueDay");
Assert.assertEquals(activityCount,"0","今日签到增加抽奖次数不正确");
Assert.assertEquals(activityCountTomorrow,"1","明日签到增加抽奖次数不正确");
Assert.assertEquals(creditsInfo,"0","今日签到增加积分不正确");
Assert.assertEquals(creditsTomorrow,"10","明日签到增加积分不正确");
Assert.assertEquals(todaySigned,"false","今日是否签到不正确");
Assert.assertEquals(continueDay,"0","连续签到天数不正确");
//当日签到之前插件信息查询
Response response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
String limitCount = response_plug.jsonPath().getString("limitCount");
int num = Integer.valueOf(limitCount);
//消耗抽奖次数
while(num>0){
this.plug(uid,"1154");
num--;
}
//签到之前插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","签到之前插件抽奖次数不正确");
logger.info("签到之前插件抽奖次数:"+limitCount);
//签到当日
response = this.sign(map,"83");
//补签前天,凑足累计签到2天
response = this.resign(map,"83",-2);
//加活动次数
String addActivityCount = response.jsonPath().getString("addActivityCount");
//加积分
String addCredits = response.jsonPath().getString("addCredits");
//加活动次数状态,0:处理中,1:失败,2:成功
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
//加积分状态,0:处理中,1:失败,2:成功
String creditsStatus = response.jsonPath().getString("creditsStatus");
Assert.assertEquals(activityCountStatus,"2","签到增加抽奖状态失败");
Assert.assertEquals(addActivityCount,"1","签到增加抽奖次数不正确");
Assert.assertEquals(addCredits,"10","签到增加积分不正确");
Assert.assertEquals(creditsStatus,"2","签到增加积分状态失败");
//签到信息查询
Response response2 = signactivityService.getSignInfo(map,"83");
//今日是否签到
todaySigned = response2.jsonPath().getString("signInfoVO.todaySigned");
Assert.assertEquals(todaySigned,"true","当日是否签到显示不正确");
//历史累计签到数
String acmDay = response2.jsonPath().getString("signInfoVO.acmDay");
Assert.assertEquals(acmDay,"2","历史累积签到次数不正确");
//获取当前用户积分
String creditsNew = response2.jsonPath().getString("credits");
logger.info("签到之后查询签到的积分为:"+creditsNew);
Assert.assertEquals(creditsNew,credits,"签到之后积分未增加");
//签到之后插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
limitCount = response_plug.jsonPath().getString("limitCount");
String limitScope = response_plug.jsonPath().getString("limitScope");
Assert.assertEquals(limitCount,"1","签到之后未增加插件抽奖次数");
Assert.assertEquals(limitScope,"1","签到之后未增加插件抽奖次数的类型不对");
logger.info("签到之后插件抽奖次数:"+limitCount);
//插件工具抽奖
this.plug(uid,"1154");
//抽奖之后插件信息查询
Thread.sleep(1000);
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","抽奖之后插件抽奖次数不正确");
logger.info("抽奖之后插件抽奖次数:"+limitCount);
}
@Test(description = "活动id:,规则:首次签到加1积分,3次抽奖机会,叠加连续奖励、连续周期奖励、累签奖励")
public void 首签奖励() throws Exception{
logger.info("Current Thread Id: " + Thread.currentThread().getId());
String act_id = "91";
String plug_id = "2165";
//签到前查询用户积分
Response signInfo_res = signactivityService.getSignInfo(map, act_id);
int consumerCredits = Integer.valueOf(signInfo_res.jsonPath().getString("credits"));
logger.info("今日签到前用户积分为: " + consumerCredits);
//签到前查询插件抽奖次数
Response plug_res = activityPlugDrawInfoService.getPrizeInfo(map, plug_id);
int limitCount = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
logger.info("今日签到前插件抽奖次数为: " + limitCount);
//签到今日, doSign接口校验
Response sign_res = this.sign(map, act_id);
String addActivityCount = sign_res.jsonPath().getString("addActivityCount");
Assert.assertEquals(addActivityCount, "4", "加抽奖次数不正确");
String activityCountStatus = sign_res.jsonPath().getString("activityCountStatus");
Assert.assertEquals(activityCountStatus, "2", "签到加抽奖状态不正确");
String addCredits = sign_res.jsonPath().getString("addCredits");
Assert.assertEquals(addCredits, "12", "签到加积分不正确");
String creditsStatus = sign_res.jsonPath().getString("creditsStatus");
Assert.assertEquals(creditsStatus, "2", "签到加积分状态不正确");
String rwType = sign_res.jsonPath().getString("rewardMap.FIRST_SIGN.rwType");
Assert.assertEquals(rwType, "FIRST_SIGN", "接口没有首签奖励字段");
//getSignInfo接口信息校验
signInfo_res = signactivityService.getSignInfo(map, act_id);
String todaySigned = signInfo_res.jsonPath().getString("signInfoVO.todaySigned");
Assert.assertEquals(todaySigned, "true", "今日签到状态不正确");
String credits = signInfo_res.jsonPath().getString("signInfoVO.credits");
Assert.assertEquals(credits, "12", "今日签到奖励积分不正确");
String activityCount = signInfo_res.jsonPath().getString("signInfoVO.activityCount");
Assert.assertEquals(activityCount, "4", "今日签到加抽奖次数不正确");
int consumerCreditsNew = Integer.valueOf(signInfo_res.jsonPath().getString("credits"));
logger.info("今日签到后用户积分为: " + consumerCreditsNew);
Assert.assertEquals(consumerCreditsNew, consumerCredits + 12, "签到后用户增加积分不正确");
//getPrizeInfo接口信息校验
plug_res = activityPlugDrawInfoService.getPrizeInfo(map, plug_id);
int limitCountNew = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
logger.info("今日签到后插件抽奖次数为:" + limitCountNew);
Assert.assertEquals(limitCountNew, limitCount + 4, "今日签到加抽奖次数不正确");
}
// 获取时间方法
public String getTime(int amount){
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy", Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, amount);
date = calendar.getTime();
// System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
// System.out.println(time);
return time;
}
//获取日期
public String getTime_data(int amount){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, amount);
date = calendar.getTime();
String time = dateFormat.format(date);
return time;
}
//签到
public Response sign(Map cookies,String activityId) throws Exception {
//签到
Response response = signactivityService.doSign(cookies,activityId);
//获取签到logId
String logId = response.jsonPath().getString("logId");
response = signactivityService.getSignResult(cookies,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0") || activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
//补签
public Response resign(Map cookies,String activityId,int data) throws Exception {
//补签昨天,凑足累计签到2天
Response response = signactivityService.reSign(cookies,activityId,null,getTime(data));
//补签加抽奖次数
String activityCount = response.jsonPath().getString("data.activityCount");
//补签加积分
String creditsSecond = response.jsonPath().getString("data.credits");
//是否有补签消耗
String hasConsume = response.jsonPath().getString("data.hasConsume");
Assert.assertEquals(activityCount,"1","今日补签增加抽奖次数不正确");
Assert.assertEquals(creditsSecond,"10","今日补签增加积分不正确");
Assert.assertEquals(hasConsume,"false","今日补签消耗不正确");
//补签logid
String logId = response.jsonPath().getString("data.logId");
response = signactivityService.getSignResult(cookies,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0") || activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
//插件抽奖
public void plug(int uid,String id) throws Exception {
Response response = activityPlugDrawInfoService.doJoinPlugdraw(uid,id);
String orderId = response.jsonPath().getString("orderId");
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
int i = 30;
while ("成功-等待".equals(response.jsonPath().getString("message")) && i > 0) {
Thread.sleep(1000);
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
i--;
}
}
//@Test
public void plug2() throws Exception {
Response response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"1154");
response_plug.prettyPrint();
Response response = activityPlugDrawInfoService.doJoinPlugdraw(uid,"1154");
String orderId = response.jsonPath().getString("orderId");
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
int i = 10;
while ("成功-等待".equals(response.jsonPath().getString("message")) && i > 0) {
Thread.sleep(500);
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
i--;
}
response.prettyPrint();
}
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy",Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 0);
date = calendar.getTime();
System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
System.out.println(time);
}
}
package http.cases.SignTest;
import com.alibaba.fastjson.JSONObject;
import common.DuibaLog;
import common.DuibaTestBase;
import http.service.Activity.ManagerService;
import http.service.Activity.SignactivityService;
import http.service.Authorization;
import http.service.hd.SigninService;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
/**
* Created by humengxin on 2018/5/9.
*/
//@ContextConfiguration(classes = DuibaConfig.class)
public class 补签测试_signTest extends DuibaTestBase {
@Autowired
SigninService signinService;
@Autowired
Authorization authorization;
@Autowired
SignactivityService signactivityService;
@Autowired
ManagerService managerService;
// MysqlUtils jdbc = null;
private static DuibaLog logger = DuibaLog.getLogger();
//指定用户
private int uid = 3746;
private String consumer_id = "100085132";
private String tag = "0396";
private Map<String,Object> cookies ;
@BeforeClass
public void beforeclass() {
// jdbc = new MysqlUtils("");
cookies = authorization.dafuwengLogin(uid);
try {
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=70");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=70");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=71");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=71");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=80");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=80");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=82");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=82");
jdbc.update("UPDATE consumer_accounts.tb_consumer_account_"+tag+" SET balance_amount = '100' WHERE id = '4'");
} catch (SQLException e) {
logger.info("数据库更新异常");
}
}
// @AfterClass
// public void afterclass() {
// jdbc.releaseConn();
// }
@Test(description = "虚拟卡补签")
public void 虚拟卡补签() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//获取目前虚拟卡数量
Map map = jdbc.findSimpleResult("select * from consumer_accounts.tb_consumer_account_"+tag+" where id = 4");
String amount = String.valueOf(map.get("balance_amount"));
logger.info("补签之前虚拟卡数量为:"+amount);
amount = String.valueOf(Integer.valueOf(amount)-10);
//签到信息查询(没补之前的,没签到今天的,此用例都不自动签到当天的,只补过去的)
Response response = signactivityService.getSignInfo(cookies,"70");
//获取当前用户积分(没补签之前的,getSignInfo接口中的返回字段)
String credits = response.jsonPath().getString("credits");
logger.info("没签之前查询签到的积分为——————————————"+credits+"-------------------------------------");
//补签前一天(前2天-2,当天0,后一天+1)
response = signactivityService.reSign(cookies,"70","255",getTime(-1));
//补签加抽奖次数
String activityCount = response.jsonPath().getString("data.activityCount");
//补签加积分
String creditsFirst = response.jsonPath().getString("data.credits");
//是否有补签消耗
String hasConsume = response.jsonPath().getString("data.hasConsume");
//补签消耗数量
String reSignConsumeCount = response.jsonPath().getString("data.reSignConsumeCount");
//补签消耗类型
String reSignConsumeTypeStr = response.jsonPath().getString("data.reSignConsumeTypeStr");
//补签logid
String logId = response.jsonPath().getString("data.logId");
//补签结果走连续签到奖励,当天没签,所以补签第一天是连续签到1天
Assert.assertEquals(activityCount,"1","补签加抽奖次数不正确");
Assert.assertEquals(creditsFirst,"1","补签加积分不正确");
Assert.assertEquals(hasConsume,"true","补签消耗与否不正确");
Assert.assertEquals(reSignConsumeCount,"10","虚拟卡补签消耗数量不正确");
Assert.assertEquals(reSignConsumeTypeStr,"补签卡","补签消耗类型不正确");
Thread.sleep(2000);
response = signactivityService.getSignResult(cookies,logId);
//签到状态(补签之后查询签到结果,2为成功)
String status = response.jsonPath().getString("status");
//接口异步处理
int i=10;
while(status.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
i--;
}
// response.prettyPrint();
//加积分数量(补签后查询签到结果中的字段)
String addCredits = response.jsonPath().getString("addCredits");
Assert.assertEquals(addCredits,"1","补签加积分不正确");
//更新补签之后的最新积分(补签后查询签到结果中的字段,即getSignResult中的返回字段)
String totalCredits = response.jsonPath().getString("totalCredits");
logger.info("totalCredits");
logger.info("补签之后更新的积分为---------------------"+totalCredits+"-------------------------------------");
//校验积分前后对比
int act = Integer.valueOf(totalCredits);
int exp = Integer.valueOf(credits)+Integer.valueOf(creditsFirst);
Assert.assertEquals(act,exp,"积分与预期不符");
//校验consumer和user表的积分
Thread.sleep(2000);
Map consumerCredits= jdbc.findSimpleResult("select * from consumer.consumer_0010 where id="+consumer_id+"");
Map userCredits = jdbc.findSimpleResult("select * from dafuweng.user where id ="+uid);
Assert.assertEquals(consumerCredits.get("credits").toString().trim(),String.valueOf(exp),"consumer积分与预期不符");
Assert.assertEquals(userCredits.get("credits").toString().trim(),String.valueOf(exp),"user积分与预期不符");
//获取补签后虚拟卡数量
map = jdbc.findSimpleResult("select * from consumer_accounts.tb_consumer_account_"+tag+" where id = 4");
String amountNew = String.valueOf(map.get("balance_amount"));
logger.info("补签之后虚拟卡数量为:"+amountNew);
Assert.assertEquals(amount,amountNew);
logger.info("校验虚拟卡补签前后库存正确");
}
//@Test(description = "补签失败场景——扣积分失败")
public void 补签_扣积分失败() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
managerService.index();
try{
//修改活动扣积分模板 consumeTemplateId: 1-扣积分成功;2-扣积分失败
Response HdResponse = managerService.doEdit2("2");
//补签前一天(前2天-2,当天0,后一天+1)
Response response = signactivityService.reSign(authorization.dafuwengLogin(3268), "71", null, getTime(-1));
String hasConsume = response.jsonPath().getString("data.hasConsume");
//补签消耗数量
String reSignConsumeCount = response.jsonPath().getString("data.reSignConsumeCount");
//补签消耗类型
String reSignConsumeTypeStr = response.jsonPath().getString("data.reSignConsumeTypeStr");
Assert.assertEquals(hasConsume, "true", "补签是否消耗");
Assert.assertEquals(reSignConsumeCount, "1", "补签消耗数量不正确");
Assert.assertEquals(reSignConsumeTypeStr,"积分","补签消耗类型是否为积分");
//补签logid
String logId = response.jsonPath().getString("data.logId");
response = signactivityService.getSignResult(authorization.dafuwengLogin(3268), logId);
//签到状态
String status = response.jsonPath().getString("status");
//接口异步处理
int i=10;
while(status.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(authorization.dafuwengLogin(3268),logId);
status = response.jsonPath().getString("status");
i--;
}
//判断结果
Assert.assertEquals(status,"1","补签失败,原因——扣积分失败");
logger.info("补签失败,原因——扣积分失败,测试扣积分失败验证成功");
}catch (Exception e){
throw new Exception("扣积分失败补签测试!");
}finally {
//还原活动扣积分模板 consumeTemplateId: 1-扣积分成功;2-扣积分失败
Response HdResponse = managerService.doEdit2("1");
}
}
@Test(description = "补签失败场景——积分不足")
public void 补签_积分不足() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//补签前一天(前2天-2,当天0,后一天+1)
Response response = signactivityService.reSign(cookies, "80", null, getTime(-1));
//response.prettyPrint();
String hasConsume = response.jsonPath().getString("data.hasConsume");
//补签消耗数量
String reSignConsumeCount = response.jsonPath().getString("data.reSignConsumeCount");
//补签消耗类型
String reSignConsumeTypeStr = response.jsonPath().getString("data.reSignConsumeTypeStr");
Assert.assertEquals(hasConsume, "true", "补签是否消耗");
Assert.assertEquals(reSignConsumeCount, "999999999", "补签消耗数量不正确");
Assert.assertEquals(reSignConsumeTypeStr,"积分","补签消耗类型是否为积分");
//补签logid
String logId = response.jsonPath().getString("data.logId");
response = signactivityService.getSignResult(cookies, logId);
//签到状态
String status = response.jsonPath().getString("status");
//接口异步处理
int i=10;
while(status.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
i--;
}
String message = response.jsonPath().getString("message");
//response.prettyPrint();
//判断结果
Assert.assertEquals(status,"1","补签失败状态不正确");
Assert.assertEquals(message,"签到失败,用户积分余额不足","签到失败,用户积分余额不足");
logger.info("补签失败用例成功,原因——积分不足");
}
@Test(description = "补签失败场景——超过补签期限,只支持最近7天内的补签")
public void 补签_超过补签期限() throws Exception {
//补签前一天(前2天-2,当天0,后一天+1)
Response response = signactivityService.reSign(cookies, "82", null, getTime(-8));
response.prettyPrint();
String success = response.jsonPath().getString("success");
String message = response.jsonPath().getString("message");
//判断结果
Assert.assertEquals(success,"false","补签结果不正确,应补签失败");
Assert.assertEquals(message,"补签失败,当前日期不支持补签 ","补签失败返回信息不对");
logger.info("补签失败用例成功,原因——超过补签期限");
}
// 获取时间方法
public String getTime(int amount){
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy", Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, amount);
date = calendar.getTime();
// System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
// System.out.println(time);
return time;
}
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy",Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 0);
date = calendar.getTime();
System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
System.out.println(time);
}
}
package http.cases.SignTest;
import com.alibaba.fastjson.JSONObject;
import common.DuibaLog;
import common.DuibaTestBase;
import http.service.Activity.ActivityPlugDrawInfoService;
import http.service.Activity.SignactivityService;
import http.service.Authorization;
import http.service.hd.SigninService;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
/**
* Created by zhaoran on 2018/6/5.
*/
//@ContextConfiguration(classes = DuibaConfig.class)
public class 连续签到测试_signTest extends DuibaTestBase {
@Autowired
SigninService signinService;
@Autowired
Authorization authorization;
@Autowired
SignactivityService signactivityService;
@Autowired
ActivityPlugDrawInfoService activityPlugDrawInfoService;
// MysqlUtils jdbc = null;
private static DuibaLog logger = DuibaLog.getLogger();
//指定用户
private int uid = 3747;
private String consumer_id = "100085133";
private Map<String,Object> map ;
@BeforeClass
public void beforeclass() {
// jdbc = new MysqlUtils("");
map = authorization.dafuwengLogin(uid);
try {
jdbc.update("delete from sign_record.tb_sign_log where consumer_id = "+consumer_id+" and source_relation_id = 89");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id = "+consumer_id+" and source_relation_id = 89");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=74");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=74");
jdbc.update("delete from sign_record.tb_sign_log where consumer_id="+consumer_id+" and source_relation_id=81");
jdbc.update("delete from sign_record.tb_sign_statics where consumer_id="+consumer_id+" and source_relation_id=81");
} catch (SQLException e) {
logger.info("数据库更新异常");
}
}
// @AfterClass
// public void afterclass() {
// jdbc.releaseConn();
// }
@Test(description = "活动id:74,规则:连续签到1天,加一次抽奖机会,加10积分")
public void 连续签到测试() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//签到信息查询
Response response = signactivityService.getSignInfo(map,"74");
//获取当前用户积分(没补签之前的,getSignInfo接口中的返回字段)
String credits = response.jsonPath().getString("credits");
logger.info("没签之前查询签到的积分为:"+credits);
credits = String.valueOf(Integer.valueOf(credits)+10);
//今日奖励抽奖次数
String activityCount = response.jsonPath().getString("signInfoVO.activityCount");
//今日奖励积分
String creditsInfo = response.jsonPath().getString("signInfoVO.credits");
//今日是否签到
String todaySigned = response.jsonPath().getString("signInfoVO.todaySigned");
//连续签到天数
String continueDay = response.jsonPath().getString("signInfoVO.continueDay");
Assert.assertEquals(activityCount,"1","今日签到增加抽奖次数不正确");
Assert.assertEquals(creditsInfo,"10","今日签到增加积分不正确");
Assert.assertEquals(todaySigned,"false","今日是否签到不正确");
Assert.assertEquals(continueDay,"0","连续签到天数不正确");
//当日签到之前插件信息查询
Response response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"873");
String limitCount = response_plug.jsonPath().getString("limitCount");
int num = Integer.valueOf(limitCount);
//消耗抽奖次数
while(num>0){
this.plug(uid,"873");
num--;
}
//签到之前插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"873");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","签到之前插件抽奖次数不正确");
logger.info("签到之前插件抽奖次数:"+limitCount);
//签到
response = this.sign(map,"74");
//加活动次数
String addActivityCount = response.jsonPath().getString("addActivityCount");
//加活动次数状态,0:处理中,1:失败,2:成功
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
//加积分
String addCredits = response.jsonPath().getString("addCredits");
//加积分状态,0:处理中,1:失败,2:成功
String creditsStatus = response.jsonPath().getString("creditsStatus");
Assert.assertEquals(activityCountStatus,"2","签到增加抽奖状态失败");
Assert.assertEquals(addActivityCount,"1","签到增加抽奖次数不正确");
Assert.assertEquals(addCredits,"10","签到增加积分不正确");
Assert.assertEquals(creditsStatus,"2","签到增加积分状态失败");
//签到信息查询
Response response2 = signactivityService.getSignInfo(map,"74");
//今日是否签到
todaySigned = response2.jsonPath().getString("signInfoVO.todaySigned");
Assert.assertEquals(todaySigned,"true","当日是否签到显示不正确");
//获取当前用户积分
String creditsNew = response2.jsonPath().getString("credits");
logger.info("签到之后查询签到的积分为:"+creditsNew);
Assert.assertEquals(creditsNew,credits,"签到之后积分未增加");
//签到之后插件信息查询
Thread.sleep(1000);
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"873");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"1","签到之后未增加插件抽奖次数");
logger.info("签到之后插件抽奖次数:"+limitCount);
//插件工具抽奖
this.plug(uid,"873");
//抽奖之后插件信息查询
Thread.sleep(1000);
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"873");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","抽奖之后插件抽奖次数不正确");
logger.info("抽奖之后插件抽奖次数:"+limitCount);
}
@Test(description = "活动id:81,规则:连续签到2天,加一次抽奖机会,加10积分")
public void 断签测试() throws Exception {
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//补签前天
Response response_2 = this.resign(map,"81",-2);
//签到信息查询
Response response = signactivityService.getSignInfo(map,"81");
//获取当前用户积分(没补签之前的,getSignInfo接口中的返回字段)
String credits = response.jsonPath().getString("credits");
logger.info("没签之前查询签到的积分为:"+credits);
//response.prettyPrint();
String activityCount = response.jsonPath().getString("signInfoVO.activityCount"); //今日奖励抽奖次数
String activityCountTomorrow = response.jsonPath().getString("signInfoVO.activityCountTomorrow"); //明日奖励抽奖次数
String creditsInfo = response.jsonPath().getString("signInfoVO.credits"); //今日奖励积分
String creditsTomorrow = response.jsonPath().getString("signInfoVO.creditsTomorrow"); //明日奖励积分
String todaySigned = response.jsonPath().getString("signInfoVO.todaySigned"); //今日是否签到
String continueDay = response.jsonPath().getString("signInfoVO.continueDay"); //连续签到天数
Assert.assertEquals(activityCount,"0","今日签到增加抽奖次数不正确");
Assert.assertEquals(activityCountTomorrow,"1","明日签到增加抽奖次数不正确");
Assert.assertEquals(creditsInfo,"0","今日签到增加积分不正确");
Assert.assertEquals(creditsTomorrow,"10","明日签到增加积分不正确");
Assert.assertEquals(todaySigned,"false","今日是否签到不正确");
Assert.assertEquals(continueDay,"0","连续签到天数不正确");
//当日签到之前插件信息查询
Response response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"873");
String limitCount = response_plug.jsonPath().getString("limitCount");
int num = Integer.valueOf(limitCount);
//消耗抽奖次数
while(num>0){
this.plug(uid,"873");
num--;
}
//签到之前插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"873");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","签到之前插件抽奖次数不正确");
logger.info("签到之前插件抽奖次数:"+limitCount);
//签到
response = this.sign(map,"81");
// response.prettyPrint();
//加活动次数
String addActivityCount = response.jsonPath().getString("addActivityCount");
//加活动次数状态,0:处理中,1:失败,2:成功
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
//加积分
String addCredits = response.jsonPath().getString("addCredits");
//加积分状态,0:处理中,1:失败,2:成功
String creditsStatus = response.jsonPath().getString("creditsStatus");
Assert.assertEquals(activityCountStatus,"2","签到增加抽奖状态失败");
Assert.assertEquals(addActivityCount,"0","签到增加抽奖次数不正确");
Assert.assertEquals(addCredits,"0","签到增加积分不正确");
Assert.assertEquals(creditsStatus,"2","签到增加积分状态失败");
//签到信息查询
Response response2 = signactivityService.getSignInfo(map,"81");
//今日是否签到
todaySigned = response2.jsonPath().getString("signInfoVO.todaySigned");
Assert.assertEquals(todaySigned,"true","当日是否签到显示不正确");
//获取当前用户积分
String creditsNew = response2.jsonPath().getString("credits");
logger.info("签到之后查询签到的积分为:"+creditsNew);
Assert.assertEquals(creditsNew,credits,"签到之后积分未增加");
//签到之后插件信息查询
response_plug = activityPlugDrawInfoService.getPrizeInfo(map,"873");
limitCount = response_plug.jsonPath().getString("limitCount");
Assert.assertEquals(limitCount,"0","签到之后增加插件抽奖次数失败");
logger.info("签到之后插件抽奖次数:"+limitCount);
}
@Test(description = "活动id:87,连续签到第4天,加3次抽奖机会,加3积分(超出后以最高天计算)")
public void 连续奖励() throws Exception{
logger.info("Current Thread Id: " + Thread.currentThread().getId());
//今日签到前查询插件信息
Response plug_res = activityPlugDrawInfoService.getPrizeInfo(map,"2165");
int limitCount = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
//消耗插件抽奖次数
while (limitCount>0) {
this.plug(uid,"2165");
limitCount--;
}
Assert.assertEquals(limitCount,0,"补签前插件次数未消耗完");
Response signInfo_init = signactivityService.getSignInfo(map,"89");
int consumer_creditsInit = Integer.valueOf(signInfo_init.jsonPath().getString("credits"));
//补签前面3天,有补签奖励
logger.info("补签前查询签到积分为:" + consumer_creditsInit);
for(int i = 0 ; i < 3; i++){
this.resign(map,"89",i-3);
Thread.sleep(500);
}
//查询签到信息
Response signInfo_res = signactivityService.getSignInfo(map,"89");
int consumer_credits = Integer.valueOf(signInfo_res.jsonPath().getString("credits"));
String activityCount = signInfo_res.jsonPath().getString("signInfoVO.activityCount");
String creditsTomorrow = signInfo_res.jsonPath().getString("signInfoVO.creditsTomorrow");
String continueDay = signInfo_res.jsonPath().getString("signInfoVO.continueDay");
String todaySigned = signInfo_res.jsonPath().getString("signInfoVO.todaySigned");
Assert.assertEquals(continueDay,"3","补签3天失败");
Assert.assertEquals(activityCount,"3","今日签到抽奖次数不正确");
Assert.assertEquals(creditsTomorrow,"3","明日签到奖励积分不正确");
Assert.assertEquals(todaySigned,"false","今日签到状态不正确");
Assert.assertEquals(consumer_credits,consumer_creditsInit + 6,"补签增加积分数量不正确");
logger.info("补签3天后查询签到积分为:" + consumer_credits);
//今日签到前查询插件信息
plug_res = activityPlugDrawInfoService.getPrizeInfo(map,"2165");
limitCount = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
Assert.assertEquals(limitCount,6,"补签奖励的抽奖次数不正确");
logger.info("补签3天后的抽奖次数为:" + limitCount);
/*
//消耗抽奖次数
while (limitCount>0) {
this.plug("873");
limitCount--;
}
plug_res = activityPlugDrawInfoService.getPrizeInfo(map, "873");
limitCount = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
Assert.assertEquals(limitCount,0, "签到之前插件抽奖次数未消耗完");
logger.info("签到之前插件抽奖次数:" + limitCount);
*/
//今日签到,doSign接口校验
Response sign_res = this.sign(map, "89");
String addActivityCount = sign_res.jsonPath().getString("addActivityCount");
String activityCountStatus = sign_res.jsonPath().getString("activityCountStatus");
String addCredits = sign_res.jsonPath().getString("addCredits");
String creditsStatus = sign_res.jsonPath().getString("creditsStatus");
Assert.assertEquals(addActivityCount, "3", "加抽奖次数不正确");
Assert.assertEquals(activityCountStatus, "2", "签到加抽奖状态失败");
Assert.assertEquals(addCredits, "3", "签到加积分不正确");
Assert.assertEquals(creditsStatus, "2", "签到加积分状态失败");
//getSignInfo接口信息校验
signInfo_res = signactivityService.getSignInfo(map, "89");
todaySigned = signInfo_res.jsonPath().getString("signInfoVO.todaySigned");
int consumer_creditsNew = Integer.valueOf(signInfo_res.jsonPath().getString("credits"));
logger.info("今日签到后的积分为:" + consumer_creditsNew);
Assert.assertEquals(consumer_creditsNew, consumer_credits+ 3, "签到后积分增加不正确");
Assert.assertEquals(todaySigned, "true", "今日签到状态不正确");
//getPrizeInfo接口校验
plug_res = activityPlugDrawInfoService.getPrizeInfo(map,"2165");
int limitCountNew = Integer.valueOf(plug_res.jsonPath().getString("limitCount"));
Assert.assertEquals(limitCountNew, limitCount + 3, "今日签到抽奖奖励次数不正确");
}
// 获取时间方法
public String getTime(int amount){
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy", Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, amount);
date = calendar.getTime();
// System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
// System.out.println(time);
return time;
}
//签到
public Response sign(Map cookies,String activityId) throws Exception {
//签到
Response response = signactivityService.doSign(cookies,activityId);
//获取签到logId
String logId = response.jsonPath().getString("logId");
response = signactivityService.getSignResult(cookies,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0") || activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
//插件抽奖
public void plug(int uid,String id) throws Exception {
Response response = activityPlugDrawInfoService.doJoinPlugdraw(uid,id);
String orderId = response.jsonPath().getString("orderId");
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
int i = 30;
while ("成功-等待".equals(response.jsonPath().getString("message")) && i > 0) {
Thread.sleep(1000);
response = activityPlugDrawInfoService.getOrderStatusPlugdraw(uid,orderId);
i--;
}
}
//补签
public Response resign(Map cookies,String activityId,int data) throws Exception {
//补签前天,凑足累计签到2天
Response response = signactivityService.reSign(cookies,activityId,null,getTime(data));
//补签logid
String logId = response.jsonPath().getString("data.logId");
response = signactivityService.getSignResult(cookies,logId);
//签到状态
String status = response.jsonPath().getString("status");
String activityCountStatus = response.jsonPath().getString("activityCountStatus");
String creditsStatus = response.jsonPath().getString("creditsStatus");
//接口异步处理
int i=10;
while(status.equals("0") || activityCountStatus.equals("0") || creditsStatus.equals("0")&&i>0){
Thread.sleep(1000);
response = signactivityService.getSignResult(cookies,logId);
status = response.jsonPath().getString("status");
activityCountStatus = response.jsonPath().getString("activityCountStatus");
creditsStatus = response.jsonPath().getString("creditsStatus");
i--;
}
return response;
}
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy",Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 0);
date = calendar.getTime();
System.out.println(dateFormat.format(date));
String time = dateFormat.format(date)+" 08:00:00 GMT+0800 (CST)";
System.out.println(time);
}
}
package http.cases;
import common.DuibaBase;
import common.DuibaLog;
import common.DuibaTestBase;
import common.MysqlUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.testng.annotations.Test;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mabo on 2018/9/30
*/
public class http1_Test extends DuibaBase {
@Value("${pluginTest.project}")
String ManagerHost;
@Value("${db.driver}")
String DRIVER;
public DuibaLog log = DuibaLog.getLogger();
@Test
public void test1() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(5);
System.out.println(ManagerHost);
System.out.println(DRIVER);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
}
@Test
public void test2() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(6);
log.info(" log test ");
log.info(" log test1 ");
log.info(" log test2 ");
log.info(" log test3 ");
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
}
@Test
public void test3() throws InterruptedException, SQLException {
Thread.sleep(1000);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
System.out.println(7);
}
@Test
public void test4() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(8);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
}
public static void main(String[] args) throws SQLException {
// BasicDataSource bds = new BasicDataSource();
// bds.setDriverClassName("com.mysql.jdbc.Driver");
// bds.setUrl("jdbc:mysql://rdswy2b9wy53044250u1o.mysql.rds.aliyuncs.com:3306/");
// bds.setUsername("duiba_test");
// bds.setPassword("svbP3KUw2PurAnBb2rbs3vohF");
// bds.setMaxTotal(3);
//
// Connection conn = bds.getConnection();
// System.out.println(conn);
// conn = bds.getConnection();
// System.out.println(conn);
// conn = bds.getConnection();
// System.out.println(conn);
// conn.close();
// conn = bds.getConnection();
// System.out.println(conn);
// MysqlUtils sql = new MysqlUtils();
// Map<String,Object> map = sql.findSimpleResultBybds("select * from dafuweng.user where id=2709");
// System.out.println("hello");
}
}
package http.cases;
import common.DuibaBase;
import common.DuibaTestBase;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.util.Map;
/**
* Created by mabo on 2018/9/30
*/
public class http2_Test extends DuibaBase {
@Test
public void test1() throws InterruptedException, SQLException {
Thread.sleep(1000);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
System.out.println(9);
}
@Test
public void test2() throws InterruptedException, SQLException {
Thread.sleep(1000);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
System.out.println(10);
}
@Test
public void test3() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(11);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
}
@Test
public void test4() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(12);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
}
}
package http.cases;
import common.DuibaBase;
import common.DuibaTestBase;
import common.MysqlConnPool;
import http.service.testservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.util.Map;
import java.util.Random;
/**
* Created by mabo on 2018/9/30
*/
public class http_Test extends DuibaBase{
@Autowired
testservice test;
@Test
public void test1() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(1);
System.out.println("run");
test.test();
// Map<String,Object> map = jdbc1.findSimpleResult("select * from dafuweng.user where id=2709");
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
System.out.println("run111");
}
@Test
public void test2() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(2);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
Random rand = new Random();
Assert.assertEquals(1,rand.nextInt(2));
}
@Test
public void test3() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(3);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
Assert.assertEquals(1,2);
}
@Test
public void test4() throws InterruptedException, SQLException {
Thread.sleep(1000);
System.out.println(4);
Map<String,Object> map = jdbc.findSimpleResult("select * from dafuweng.user where id=2709");
}
}
package http.service.Activity;
import common.DuibaLog;
import http.service.Authorization;
import io.restassured.http.Cookies;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.testng.Assert;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
@Service
public class ActivityPlugDrawInfoService {
@Autowired
Authorization authorization;
@Value("${activity.host}")
String activityHost;
private DuibaLog logger = DuibaLog.getLogger();
/**
* 插件皮肤请求接口
* @param cookies
* @param plActSkinId
* @return
* @throws Exception
*/
public Response getPlActSkin(Cookies cookies,String plActSkinId) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("plActSkinId",plActSkinId);
Response response = given().cookies(cookies).params(map).get(activityHost+"/activityPlugDrawInfo/getPlActSkin");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/activityPlugDrawInfo/getPlActSkin接口失败");
} catch (Exception e) {
throw new Exception("/activityPlugDrawInfo/getPlActSkin接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/activityPlugDrawInfo/getPlActSkin接口失败,返回信息:" + response.asString());
}
return response;
}
/**
* 获取插件活动奖品接口
* @param cookies
* @param activityId 插件活动id
* @return
* @throws Exception
*/
public Response getPrizeInfo(Map cookies,String activityId) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("activityId",activityId);
Response response = given().cookies(cookies).params(map).post(activityHost+"/activityPlugDrawInfo/getPrizeInfo");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/activityPlugDrawInfo/getPrizeInfo接口失败");
} catch (Exception e) {
throw new Exception("/activityPlugDrawInfo/getPrizeInfo接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/activityPlugDrawInfo/getPrizeInfo接口失败,返回信息:" + response.asString());
}
return response;
}
public Response doJoinPlugdraw(int uid,String id) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("activityId",id);
map.put("token","n42agd4");
logger.info("请求doJoinPlugdraw接口,id="+id);
Response response = given().cookies(authorization.dafuwengLogin(uid)).params(map).post(activityHost+"/activityPlugDrawInfo/doJoinPlugdraw");
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/activityPlugDrawInfo/doJoinPlugdraw接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/activityPlugDrawInfo/doJoinPlugdraw接口失败,返回信息:"+response.asString());
}
return response;
}
public Response doJoinPlugdraw_false(int uid,String id) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("activityId",id);
map.put("token","n42agd4");
logger.info("请求doJoinPlugdraw接口,id="+id);
Response response = given().cookies(authorization.dafuwengLogin(uid)).params(map).post(activityHost+"/activityPlugDrawInfo/doJoinPlugdraw");
return response;
}
public Response doJoinPlugdraw_credits(int uid,String id) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("activityId",id);
map.put("deductCredits","true");
map.put("token","n42agd4");
logger.info("请求doJoinPlugdraw接口,id="+id);
Response response = given().cookies(authorization.dafuwengLogin(uid)).params(map).post(activityHost+"/activityPlugDrawInfo/doJoinPlugdraw");
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/activityPlugDrawInfo/doJoinPlugdraw接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/activityPlugDrawInfo/doJoinPlugdraw接口失败,返回信息:"+response.asString());
}
return response;
}
public Response getOrderStatusPlugdraw(int uid,String orderId) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("orderId",orderId);
logger.info("请求getOrderStatusPlugdraw接口,orderId="+orderId);
Response response = given().cookies(authorization.dafuwengLogin(uid)).params(map).post(activityHost+"/activityPlugDrawInfo/getOrderStatusPlugdraw");
Assert.assertEquals(response.jsonPath().getString("success"),"true");
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/activityPlugDrawInfo/getOrderStatusPlugdraw接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/activityPlugDrawInfo/getOrderStatusPlugdraw接口失败,返回信息:"+response.asString());
}
return response;
}
}
package http.service.Activity;
import common.DuibaLog;
import http.service.Authorization;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.testng.Assert;
import utils.MatcherString;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
/**
* Created by 赵然 on 2018/1/13.
*/
@Service
public class ManagerService {
@Value("${manager.host}")
String ManagerHost; //ManagerHost = mng.duibatest.com.cn
@Value("${dafuweng.host}")
String dafuwengHost;
@Value("${dafuweng.port}")
int dafuwengPort;
private DuibaLog logger = DuibaLog.getLogger();
@Autowired
Authorization authorization;
//获取自定义活动列表
public Response list() throws Exception {
String url = ManagerHost + "/newmanager/hdTool/list";
Map<String, String> map = new HashMap<>();
map.put("max", "20");
map.put("offset", "0");
Response response = given().cookies(authorization.ssoLogin()).params(map).get("http://" + url);
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("/newmanager/hdTool/list接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/newmanager/hdTool/list接口失败,返回信息:" + response.asString());
}
return response;
}
public Response list(String title) throws Exception {
String url = ManagerHost + "/newmanager/hdTool/list";
Map<String, String> map = new HashMap<>();
map.put("max", "20");
map.put("offset", "0");
map.put("title", title);
Response response = given().cookies(authorization.ssoLogin()).params(map).get("http://" + url);
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("/newmanager/hdTool/list接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/newmanager/hdTool/list接口失败,返回信息:" + response.asString());
}
return response;
}
//打开活动,获取活动配置
public Response getDataEditConfig(String actId) throws Exception {
String url = ManagerHost + "/AdminNewDuibaHdtool/getDataEditConfig";
logger.info("请求编辑新活动工具url:" + url);
Response response = given().cookies(authorization.ssoLogin()).param("actId", actId).get("http://" + url);
// response.prettyPrint();
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("/AdminNewDuibaHdtool/getDataEditConfig接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/AdminNewDuibaHdtool/getDataEditConfig接口失败,返回信息:" + response.asString());
}
return response;
}
//打开活动,获取活动配置
public Response edit(String id) throws Exception {
String url = ManagerHost + "/newmanager/customHdTool/edit";
logger.info("请求编辑新活动工具url:" + url);
Response response = given().cookies(authorization.ssoLogin()).param("id", id).get("http://" + url);
// response.prettyPrint();
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("/newmanager/customHdTool/edit接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/newmanager/customHdTool/edit接口失败,返回信息:" + response.asString());
}
return response;
}
//编辑商品,获取商品配置
public Response CouponConfig(String CouponId) throws Exception {
String url = ManagerHost + "/AItem/edit/" + CouponId;
Map<String, String> headMap = new HashMap<>();
headMap.put("Accept-Encoding", "gzip, deflate");
headMap.put("Accept-Language", "zh-CN,zh;q=0.8");
logger.info("请求编辑兑换项url:" + url);
Response response = given().headers(headMap).cookies(authorization.ssoLogin()).get("http://" + url);
//response.prettyPrint();
try {
// Assert.assertEquals(MatcherString.getString(response.asString(),"<span>(.*?)</span>",1),"兑吧","管理后台打开异常!");
Assert.assertEquals(String.valueOf(response.getStatusCode()), "200", "管理后台兑换项请求异常");
} catch (Exception e) {
throw new Exception("/AItem/edit/接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/AItem/edit/接口失败,返回信息:" + response.asString());
}
return response;
}
//查看优惠券码,获取链接券链接
public Response ShowCoupons(String CouponId) throws Exception {
String url = ManagerHost + "/AItem/showCoupons/" + CouponId;
Map<String, String> headMap = new HashMap<>();
headMap.put("Accept-Encoding", "gzip, deflate");
headMap.put("Accept-Language", "zh-CN,zh;q=0.8");
logger.info("请求查看优惠券码url:" + url);
Response response = given().headers(headMap).cookies(authorization.ssoLogin()).get("http://" + url);
//response.prettyPrint();
try {
// Assert.assertEquals(MatcherString.getString(response.asString(),"<span>(.*?)</span>",1),"兑吧","管理后台打开异常!");
Assert.assertEquals(String.valueOf(response.getStatusCode()), "200", "管理后台查看优惠券码异常");
} catch (Exception e) {
throw new Exception("/AItem/showCoupons/接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/AItem/showCoupons/接口失败,返回信息:" + response.asString());
}
return response;
}
//创建随机活动
public Response save_random() throws Exception {
// SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
// String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳
String url=ManagerHost+"/AdminNewDuibaHdtool/save";
Map<String,String> map = new HashMap<>();
map.put("mode","credits");
map.put("actionType","0");
map.put("type","smashg_move");
map.put("title","【推荐位测试数据】");
map.put("facePrice","1");
map.put("limitScope","forever");
map.put("freeCount","999");
map.put("freeScope","everyday");
map.put("endDate","2018-12-31 19:00");
map.put("banner","//yun.duiba.com.cn/upload/uGlwJ1472642112981.png");
map.put("bannerImgNew","//yun.duiba.com.cn/upload/newHdTool/hitEgg/banner_750x220.png");
map.put("smallImgNew","//yun.duiba.com.cn/upload/newHdTool/hitEgg/thumbnail_370x370.png");
map.put("awards","[{\"type\":\"thanks\",\"img\":\"//yun.duiba.com.cn/upload/uP99F1462438316972.png\",\"title\":\"谢谢参与\",\"show\":true,\"canEdit\":false},{\"type\":\"lucky\",\"img\":\"//yun.duiba.com.cn/webapp/img/luckynewn.png\",\"title\":\"幸运福袋\",\"show\":true,\"canEdit\":false}]");
map.put("recommendSkinStatus","OPEN");
map.put("recommendSkinId","2");
map.put("thumbnail_white","//yun.duiba.com.cn/upload/dXKC91472642113003.jpg");
map.put("recommend","//yun.dui88.com/images/201801/pj2076h0tz.jpg");
map.put("anticheatExchangeLimit","false");
map.put("hiddenForDeveloper","false");
map.put("tag","null");
map.put("openMutliPrizeLimit","false");
map.put("openMutliPrizeLimit","false");
map.put("directSendCoupon","FALSE");
map.put("channelType","0");
logger.info("请求编辑新活动工具url:"+url);
Response response=given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+url);
response.prettyPrint();
try{
Assert.assertEquals(response.jsonPath().getString("message"),"修改保存成功");
}catch(Exception e){
throw new Exception("创建活动接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("创建活动接口失败,返回信息:"+response.asString());
}
return response;
}
public Response save_random(String title) throws Exception {
// SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
// String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳
String url=ManagerHost+"/AdminNewDuibaHdtool/save";
Map<String,String> map = new HashMap<>();
map.put("mode","credits");
map.put("actionType","0");
map.put("type","smashg_move");
map.put("title",title);
map.put("facePrice","1");
map.put("limitScope","forever");
map.put("freeCount","999");
map.put("freeScope","everyday");
map.put("endDate","2018-12-31 19:00");
map.put("banner","//yun.duiba.com.cn/upload/uGlwJ1472642112981.png");
map.put("bannerImgNew","//yun.duiba.com.cn/upload/newHdTool/hitEgg/banner_750x220.png");
map.put("smallImgNew","//yun.duiba.com.cn/upload/newHdTool/hitEgg/thumbnail_370x370.png");
map.put("awards","[{\"type\":\"thanks\",\"img\":\"//yun.duiba.com.cn/upload/uP99F1462438316972.png\",\"title\":\"谢谢参与\",\"show\":true,\"canEdit\":false},{\"type\":\"lucky\",\"img\":\"//yun.duiba.com.cn/webapp/img/luckynewn.png\",\"title\":\"幸运福袋\",\"show\":true,\"canEdit\":false}]");
map.put("recommendSkinStatus","OPEN");
map.put("recommendSkinId","2");
map.put("thumbnail_white","//yun.duiba.com.cn/upload/dXKC91472642113003.jpg");
map.put("recommend","//yun.dui88.com/images/201801/pj2076h0tz.jpg");
map.put("anticheatExchangeLimit","false");
map.put("hiddenForDeveloper","false");
map.put("tag","null");
map.put("openMutliPrizeLimit","false");
map.put("openMutliPrizeLimit","false");
map.put("directSendCoupon","FALSE");
map.put("channelType","0");
logger.info("请求编辑新活动工具url:"+url);
Response response=given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+url);
response.prettyPrint();
try{
Assert.assertEquals(response.jsonPath().getString("message"),"修改保存成功");
}catch(Exception e){
throw new Exception("创建活动接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("创建活动接口失败,返回信息:"+response.asString());
}
return response;
}
public Response common(String mactId,String title,String facePrice,String actstatus,String low,String probability) throws Exception {
String url=ManagerHost+"/AdminNewDuibaHdtool/save";
Map<String,String> map = new HashMap<>();
map.put("mode","credits");
map.put("actionType","0");
map.put("type","drawLot");
map.put("title",title);
map.put("facePrice",facePrice);
map.put("limitScope","forever");
map.put("freeCount","999");
map.put("freeScope","everyday");
map.put("endDate","2020-12-31 23:00");
map.put("banner","//yun.duiba.com.cn/upload/uGlwJ1472642112981.png");
map.put("bannerImgNew","//yun.duiba.com.cn/upload/newHdTool/hitEgg/banner_750x220.png");
map.put("smallImgNew","//yun.duiba.com.cn/upload/newHdTool/hitEgg/thumbnail_370x370.png");
map.put("awards","[{\"id\":12595,\"appItemId\":null,\"img\":\"//yun.duiba.com.cn/upload/uP99F1462438316972.png\",\"title\":\"谢谢参与\",\"type\":\"thanks\",\"show\":true,\"remaind\":null,\"oldRemaind\":null,\"probability\":null,\"limit\":null,\"facePrice\":null,\"low\":null,\"description\":null,\"valid\":true,\"isMutliPrizeLimit\":false,\"prizesGrantLimitNum\":null,\"rolling\":false,\"canEdit\":false},{\"id\":12596,\"appItemId\":27131,\"img\":\"//yun.duiba.com.cn/upload/1uF0l1462438316968.png\",\"title\":\"实物\",\"type\":\"object\",\"show\":true,\"remaind\":\"100000\",\"oldRemaind\":\"100000\",\"probability\":\""+probability+"\",\"limit\":null,\"facePrice\":null,\"low\":"+low+",\"description\":null,\"valid\":true,\"isMutliPrizeLimit\":false,\"prizesGrantLimitNum\":null,\"rolling\":false,\"canEdit\":false}]");
map.put("recommendSkinStatus",actstatus);
if(actstatus.equals("OPEN")) {
map.put("recommendSkinId", "2");
map.put("recommend","//yun.dui88.com/images/201801/pj2076h0tz.jpg");
}
map.put("thumbnail_white","//yun.duiba.com.cn/upload/dXKC91472642113003.jpg");
map.put("anticheatExchangeLimit","false");
map.put("hiddenForDeveloper","false");
map.put("tag","null");
map.put("openMutliPrizeLimit","false");
map.put("openMutliPrizeLimit","false");
map.put("actId",mactId);
map.put("channelType","0");
logger.info("请求编辑新活动工具url:"+url);
Response response=given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+url);
//response.prettyPrint();
try{
Assert.assertEquals(response.jsonPath().getString("message"),"修改保存成功");
}catch(Exception e){
throw new Exception("编辑活动接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("编辑活动接口失败,返回信息:"+response.asString());
}
return response;
}
public Response save(String mactId,String title,String actstatus) throws Exception{
Response response = this.common(mactId,title,"0.1",actstatus,null,"100");
return response;
}
public Response save(String mactId,String title,String low,String probability) throws Exception{
Response response = this.common(mactId,title,"0.1","CLOSED",low,probability);
return response;
}
//设置活动开启或关闭
/**
*@Params val (1:开启且可见;2:关闭且不可见)
*@Params actId 活动id
*/
public void switchSpecifyAndBlack(String val,String actId) throws Exception {
String url=ManagerHost+"/newmanager/hdTool/switchSpecifyAndBlack";
Map<String,String> map = new HashMap<>();
map.put("switchType","false");
map.put("type","status");
map.put("val",val);
map.put("id",actId);
Response response=given().cookies(authorization.ssoLogin()).params(map).post("http://"+url);
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/hdTool/switchSpecifyAndBlack接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/hdTool/switchSpecifyAndBlack接口失败,返回信息:"+response.asString());
}
}
public void saveSpecify(String id,String sellOut) throws Exception {
String url=ManagerHost+"/AdminNewDuibaHdtool/saveSpecify";
Map<String,String> map = new HashMap<>();
map.put("name","hmx");
map.put("id",id);
map.put("sellOut",sellOut);
Response response=given().cookies(authorization.ssoLogin()).params(map).post("http://"+url);
try{
Assert.assertEquals(String.valueOf(response.getStatusCode()), "302", "管理后台定向开发者请求异常");
}catch(Exception e){
throw new Exception("/AdminNewDuibaHdtool/saveSpecify接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/AdminNewDuibaHdtool/saveSpecify接口失败,返回信息:"+response.asString());
}
}
//定向开发者配置
public void switchSpecify(String type,String id,String switchsType) throws Exception {
String url=ManagerHost+"/AdminNewDuibaHdtool/switchSpecify";
Map<String,String> map = new HashMap<>();
map.put("type",type);
map.put("id",id);
map.put("switchsType",switchsType);
Response response=given().cookies(authorization.ssoLogin()).params(map).get("http://"+url);
try{
Assert.assertEquals(String.valueOf(response.getStatusCode()), "200", "管理后台取消定向开发者请求异常");
}catch(Exception e){
throw new Exception("/AdminNewDuibaHdtool/switchSpecify接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/AdminNewDuibaHdtool/switchSpecify接口失败,返回信息:"+response.asString());
}
}
//删除活动e
public void delet(String actId) throws Exception {
String url=ManagerHost+"/newmanager/hdTool/delete";
Response response=given().cookies(authorization.ssoLogin()).param("id",actId).post("http://"+url);
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/newmanager/hdTool/delete接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/newmanager/hdTool/delete接口失败,返回信息:"+response.asString());
}
}
//开发者应用管理
public void updateAppConfig(String appstatus,String appType) throws Exception {
String url=ManagerHost+"/AAppManage/updateAppConfig";
Map<String,String> map = new HashMap<>();
map.put("appId","2239");
map.put("token","qivvki6");
if(appType.equals("on")){
map.put("appType","on");
}else{
map.put("appType","");
}
map.put("tradeBackHome","on");
map.put("exchangeCreditsType","on");
map.put("addVisterTime","on");
map.put("useloginCode","on");
map.put("callLoginProgram","<script>\n" +
"window.requirelogin=function(){\n" +
"alert('唤起登陆')\n" +
"}\n" +
"</script>");
if(appstatus.equals("on")){
map.put("recommendOpen","on");
}
map.put("turnLuck","on");
map.put("exchangeValidation","1");
map.put("secKillValidation","1");
map.put("googleToken","1");
Response response=given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+url);
//map.clear();
try{
Assert.assertEquals(String.valueOf(response.getStatusCode()),"302","app应用设置异常");
}catch(Exception e){
throw new Exception("/AAppManage/updateAppConfig接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/AAppManage/updateAppConfig接口失败,返回信息:"+response.asString());
}
}
public void appConfig() {
String url=ManagerHost+"/AAppManage/appConfig";
Response response=given().cookies(authorization.ssoLogin()).param("id","2239").get("http://"+url);
}
//创建自定义活动工具
public Response save_customHdtool() throws Exception {
String configUrl = ManagerHost+"/newmanager/customHdTool/editConfig";
String saveUrl = ManagerHost+"/newmanager/customHdTool/save";
//获取创建活动的token
Response response=given().contentType("application/json;charset=UTF-8").cookies(authorization.ssoLogin()).get("http://"+configUrl);
String token = response.jsonPath().getString("data.token");
logger.info(token);
Map<String,String> map = new HashMap<>();
map.put("title","自动化测试自定义活动");
map.put("facePrice","0.1");
map.put("limitScope","forever");
map.put("freeScope","forever");
map.put("anticheatExchangeLimit","false");
map.put("openMutliPrizeLimit","false");
map.put("openPrizesGrantLimit","false");
map.put("prizesGrantLimitDays","1");
map.put("brickId","105");
map.put("triggerType","1");
map.put("addTimeLimit","10");
map.put("rule","测试");
map.put("awards","[{\"type\":\"thanks\",\"description\":\"\",\"title\":\"谢谢参与\",\"logo\":\"//yun.duiba.com.cn/upload/uP99F1462438316972.png\",\"valid\":true,\"rate\":\"\",\"arealimit\":false,\"stockBeforeChange\":0,\"remaind\":0,\"show\":true,\"stockAfterChange\":0},{\"type\":\"lucky\",\"description\":\"\",\"title\":\"幸运福袋\",\"logo\":\"http://yun.duiba.com.cn/webapp/img/luckynewn.png\",\"valid\":true,\"rate\":\"\",\"arealimit\":false,\"stockBeforeChange\":0,\"remaind\":0,\"show\":true,\"stockAfterChange\":0}]");
map.put("banner","//yun.duiba.com.cn/h5/managerNew/images/customDefault640-280.jpg");
map.put("bannerImgNew","//yun.duiba.com.cn/h5/managerNew/images/customDefault750-220.png");
map.put("thumbnailWhite","//yun.duiba.com.cn/h5/managerNew/images/customDefault225-140.jpg");
map.put("recommend","//yun.duiba.com.cn/h5/managerNew/images/customDefault620-160.jpg");
map.put("factoryKey","hdtool");
map.put("ext[recommendSkinStatus]","OPEN");
map.put("recommendSkinStatus","OPEN");
map.put("token",token);
map.put("directSendCoupon","FALSE");
map.put("anticheatExchangeType","1");
map.put("invitationCodeRule","false");
map.put("gameStarting","true");
map.put("channelType","0");
logger.info("请求保存自定义活动工具接口:"+saveUrl);
Response saveResponse=given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+saveUrl);
saveResponse.prettyPrint();
try{
Assert.assertEquals(saveResponse.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("创建活动接口失败,返回信息:"+saveResponse.asString());
}catch(Error er){
throw new Exception("创建活动接口失败,返回信息:"+saveResponse.asString());
}
return saveResponse;
}
//修改自定义活动工具奖品概率
public Response save_customHdtool_edit(String id,String p1,String p2,String p3,String p4,String p5) throws Exception {
String configUrl = ManagerHost+"/newmanager/customHdTool/editConfig";
String saveUrl = ManagerHost+"/newmanager/customHdTool/save";
//获取创建活动的token
Response response=given().contentType("application/json;charset=UTF-8").cookies(authorization.ssoLogin()).get("http://"+configUrl);
String token = response.jsonPath().getString("data.token");
logger.info(token);
Map<String,String> map = new HashMap<>();
map.put("id",id);
map.put("actId",id);
map.put("title","【勿动】自动化—集卡");
map.put("facePrice","0.1");
map.put("limitScope","forever");
map.put("freeScope","forever");
map.put("anticheatExchangeLimit","false");
map.put("anticheatExchangeType","1");
map.put("openMutliPrizeLimit","false");
map.put("openPrizesGrantLimit","false");
map.put("prizesGrantLimitDays","1");
map.put("brickId","106");
map.put("triggerType","1");
map.put("addTimeLimit","10");
map.put("rule","测试");
map.put("awards","[\n" +
" {\n" +
" \"appItemId\":null,\n" +
" \"oldRemaind\":0,\n" +
" \"probability\":null,\n" +
" \"autoOpen\":null,\n" +
" \"show\":true,\n" +
" \"description\":null,\n" +
" \"title\":\"谢谢参与\",\n" +
" \"type\":\"thanks\",\n" +
" \"isMutliPrizeLimit\":false,\n" +
" \"valid\":true,\n" +
" \"rolling\":false,\n" +
" \"prizesGrantLimitNum\":null,\n" +
" \"addrlimit\":false,\n" +
" \"low\":null,\n" +
" \"remaind\":0,\n" +
" \"limit\":null,\n" +
" \"name\":\"\",\n" +
" \"logo\":\"//yun.duiba.com.cn/upload/uP99F1462438316972.png\",\n" +
" \"facePrice\":null,\n" +
" \"id\":12197,\n" +
" \"stockAfterChange\":0,\n" +
" \"stockBeforeChange\":0,\n" +
" \"index\":1\n" +
" },\n" +
" {\n" +
" \"appItemId\":27138,\n" +
" \"oldRemaind\":999998,\n" +
" \"probability\":\""+p1+"\",\n" +
" \"autoOpen\":null,\n" +
" \"show\":true,\n" +
" \"description\":null,\n" +
" \"title\":\"扭\",\n" +
" \"type\":\"collectGoods\",\n" +
" \"isMutliPrizeLimit\":false,\n" +
" \"valid\":true,\n" +
" \"rolling\":false,\n" +
" \"prizesGrantLimitNum\":null,\n" +
" \"addrlimit\":false,\n" +
" \"low\":null,\n" +
" \"remaind\":999998,\n" +
" \"limit\":null,\n" +
" \"name\":\"【勿动】自动化—扭\",\n" +
" \"logo\":\"//yun.duiba.com.cn/webapp/img/collect_goods.png\",\n" +
" \"facePrice\":null,\n" +
" \"id\":12200,\n" +
" \"stockAfterChange\":999998,\n" +
" \"stockBeforeChange\":999998,\n" +
" \"index\":2\n" +
" },\n" +
" {\n" +
" \"appItemId\":27139,\n" +
" \"oldRemaind\":1000000,\n" +
" \"probability\":\""+p2+"\",\n" +
" \"autoOpen\":null,\n" +
" \"show\":true,\n" +
" \"description\":null,\n" +
" \"title\":\"蛋\",\n" +
" \"type\":\"collectGoods\",\n" +
" \"isMutliPrizeLimit\":false,\n" +
" \"valid\":true,\n" +
" \"rolling\":false,\n" +
" \"prizesGrantLimitNum\":null,\n" +
" \"addrlimit\":false,\n" +
" \"low\":null,\n" +
" \"remaind\":1000000,\n" +
" \"limit\":null,\n" +
" \"name\":\"【勿动】自动化—蛋\",\n" +
" \"logo\":\"//yun.duiba.com.cn/webapp/img/collect_goods.png\",\n" +
" \"facePrice\":null,\n" +
" \"id\":12201,\n" +
" \"stockAfterChange\":1000000,\n" +
" \"stockBeforeChange\":1000000,\n" +
" \"index\":3\n" +
" },\n" +
" {\n" +
" \"appItemId\":27140,\n" +
" \"oldRemaind\":1000000,\n" +
" \"probability\":\""+p3+"\",\n" +
" \"autoOpen\":null,\n" +
" \"show\":true,\n" +
" \"description\":null,\n" +
" \"title\":\"分\",\n" +
" \"type\":\"collectGoods\",\n" +
" \"isMutliPrizeLimit\":false,\n" +
" \"valid\":true,\n" +
" \"rolling\":false,\n" +
" \"prizesGrantLimitNum\":null,\n" +
" \"addrlimit\":false,\n" +
" \"low\":null,\n" +
" \"remaind\":1000000,\n" +
" \"limit\":null,\n" +
" \"name\":\"【勿动】自动化—分\",\n" +
" \"logo\":\"//yun.duiba.com.cn/webapp/img/collect_goods.png\",\n" +
" \"facePrice\":null,\n" +
" \"id\":12202,\n" +
" \"stockAfterChange\":1000000,\n" +
" \"stockBeforeChange\":1000000,\n" +
" \"index\":4\n" +
" },\n" +
" {\n" +
" \"appItemId\":27141,\n" +
" \"oldRemaind\":1000000,\n" +
" \"probability\":\""+p4+"\",\n" +
" \"autoOpen\":null,\n" +
" \"show\":true,\n" +
" \"description\":null,\n" +
" \"title\":\"红\",\n" +
" \"type\":\"collectGoods\",\n" +
" \"isMutliPrizeLimit\":false,\n" +
" \"valid\":true,\n" +
" \"rolling\":false,\n" +
" \"prizesGrantLimitNum\":null,\n" +
" \"addrlimit\":false,\n" +
" \"low\":null,\n" +
" \"remaind\":1000000,\n" +
" \"limit\":null,\n" +
" \"name\":\"【勿动】自动化—红\",\n" +
" \"logo\":\"//yun.duiba.com.cn/webapp/img/collect_goods.png\",\n" +
" \"facePrice\":null,\n" +
" \"id\":12203,\n" +
" \"stockAfterChange\":1000000,\n" +
" \"stockBeforeChange\":1000000,\n" +
" \"index\":5\n" +
" },\n" +
" {\n" +
" \"appItemId\":27142,\n" +
" \"oldRemaind\":1000000,\n" +
" \"probability\":\""+p5+"\",\n" +
" \"autoOpen\":null,\n" +
" \"show\":true,\n" +
" \"description\":null,\n" +
" \"title\":\"包\",\n" +
" \"type\":\"collectGoods\",\n" +
" \"isMutliPrizeLimit\":false,\n" +
" \"valid\":true,\n" +
" \"rolling\":false,\n" +
" \"prizesGrantLimitNum\":null,\n" +
" \"addrlimit\":false,\n" +
" \"low\":null,\n" +
" \"remaind\":1000000,\n" +
" \"limit\":null,\n" +
" \"name\":\"【勿动】自动化—包\",\n" +
" \"logo\":\"//yun.duiba.com.cn/webapp/img/collect_goods.png\",\n" +
" \"facePrice\":null,\n" +
" \"id\":12204,\n" +
" \"stockAfterChange\":1000000,\n" +
" \"stockBeforeChange\":1000000,\n" +
" \"index\":6\n" +
" }\n" +
"]");
map.put("banner","//yun.duiba.com.cn/h5/managerNew/images/customDefault640-280.jpg");
map.put("bannerImgNew","//yun.duiba.com.cn/h5/managerNew/images/customDefault750-220.png");
map.put("thumbnailWhite","//yun.duiba.com.cn/h5/managerNew/images/customDefault225-140.jpg");
map.put("recommend","//yun.duiba.com.cn/h5/managerNew/images/customDefault620-160.jpg");
map.put("factoryKey","hdtool");
map.put("status","1");
map.put("success","true");
map.put("actionType","0");
map.put("gameStarting","true");
map.put("mode","credits");
map.put("ext[recommendSkinStatus]","FALSE");
map.put("recommendSkinStatus","FALSE");
map.put("token",token);
map.put("directSendCoupon","FALSE");
map.put("channelType","0");
Response saveResponse=given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+saveUrl);
saveResponse.prettyPrint();
try{
Assert.assertEquals(saveResponse.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("创建活动接口失败,返回信息:"+saveResponse.asString());
}catch(Error er){
throw new Exception("创建活动接口失败,返回信息:"+saveResponse.asString());
}
return saveResponse;
}
//获取兑吧余额
public Response adminDuibaBalance() throws Exception {
String url = ManagerHost + "/adminDuibaBalance/index";
logger.info("请求兑吧管理后台余额url:" + url);
Response response = given().cookies(authorization.ssoLogin()).get("http://" + url);
//response.prettyPrint();
try {
Assert.assertEquals(String.valueOf(response.getStatusCode()), "200", "管理后台兑换项请求异常");
} catch (Exception e) {
throw new Exception("/AItem/edit/接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/AItem/edit/接口失败,返回信息:" + response.asString());
}
return response;
}
//获取插件中奖奖品
public Response editData(String pluginId) throws Exception {
String url = ManagerHost + "/plugin/editData";
logger.info("请求编辑插件活动url:" + url);
Map<String,String> map = new HashMap<>();
map.put("id",pluginId);
map.put("copy","false");
Response response = given().cookies(authorization.ssoLogin()).params(map).post("http://" + url);
// response.prettyPrint();
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("/plugin/editData接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/plugin/editData接口失败,返回信息:" + response.asString());
}
return response;
}
//活动黑名单开关
public Response switchBlack(String activityId,String status) throws Exception {
String url = ManagerHost + "/BlackListAdmin/switchBlack";
Map<String,String> map = new HashMap<>();
map.put("activityId",activityId);
map.put("activityType","12");
map.put("type",status);
Response response = given().cookies(authorization.ssoLogin()).params(map).post("http://" + url);
response.prettyPrint();
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("/BlackListAdmin/switchBlack接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/BlackListAdmin/switchBlack接口失败,返回信息:" + response.asString());
}
return response;
}
//活动扣积分模板 consumeTemplateId: 1-扣积分成功;2-扣积分失败
public Response doEdit(String consumeTemplateId) throws Exception {
String url = "http://"+dafuwengHost + ":" + dafuwengPort+"/app/doEdit";
Map<String,String> map = new HashMap<>();
map.put("id","57");
map.put("name","(阿里云)hmx积分商城");
map.put("appKey","2wGQc3MZaQsqYFWcX4gguya5PnnS");
map.put("appSecret","2D6y9SNdVSSkk7eBkoBYnvFGFGv9");
map.put("consumeTemplateId",consumeTemplateId);
Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").params(map).post(url);
// response.prettyPrint();
return response;
}
public Response doEdit2(String consumeTemplateId) throws Exception {
String url = "http://"+dafuwengHost + ":" + dafuwengPort+"/app/doEdit";
Map<String,String> map = new HashMap<>();
map.put("id","67");
map.put("name","自动化测试");
map.put("appKey","3erv8LvBxKBSyuGK5i8FSGyYoFD1");
map.put("appSecret","3NXy3w3qrRtA3Ewya3perRbdpucA");
map.put("consumeTemplateId",consumeTemplateId);
Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").params(map).post(url);
// response.prettyPrint();
return response;
}
//获取开发者扣积分模板信息
public void index() throws Exception{
String url = "http://"+dafuwengHost + ":" + dafuwengPort+"/app/index";
Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").get(url);
String status = MatcherString.getString(response.asString(), "3erv8LvBxKBSyuGK5i8FSGyYoFD1</td>\n" +
"\t\t\t\t<td>(.*?)</td>", 1);
logger.info("自动化测试 扣积分模板为:"+status);
int i=30;
while(!status.equals("扣积分-成功")&&i>0){
Thread.sleep(1000);
response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").get(url);
status = MatcherString.getString(response.asString(), "3erv8LvBxKBSyuGK5i8FSGyYoFD1</td>\n" +
"\t\t\t\t<td>(.*?)</td>", 1);
logger.info("自动化测试 扣积分模板为:"+status);
i--;
}
}
//修改开发者积分
public void update(int uid,String credits) {
String url = "http://"+dafuwengHost + ":" + dafuwengPort+"/user/update";
Map<String,String> map = new HashMap<>();
map.put("id",String.valueOf(uid));
map.put("name","自动化_普兑");
map.put("credits",credits);
Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").params(map).post(url);
// response.prettyPrint();
}
//大富翁上游兑换修改模板 上游不稳定,暂时去掉
// public Response use(String id) throws Exception {
// String url = "http://"+dafuwengHost + ":" + dafuwengPort+"/supplierExchangeTemplate/use";
//
// Map<String,String> map = new HashMap<>();
// map.put("id",id);
//
// Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").params(map).get(url);
// //response.prettyPrint();
// try {
// Assert.assertEquals(String.valueOf(response.getStatusCode()), "200", "修改上游模板请求异常");
// } catch (Exception e) {
// throw new Exception("/supplierExchangeTemplate/use接口失败,返回信息:" + response.asString());
// } catch (Error er) {
// throw new Exception("/supplierExchangeTemplate/use接口失败,返回信息:" + response.asString());
// }
//
// return response;
// }
//兑吧订单发货
public Response expressSend(String orderId) throws Exception{
String url = ManagerHost + "/aorder/expressSend";
Map<String,String> map = new HashMap<>();
map.put("expressId","123123213213");
map.put("expressName","圆通速递");
map.put("orderId",orderId);
Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+url);
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("/aorder/expressSend接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/aorder/expressSend接口失败,返回信息:" + response.asString());
}
return response;
}
//兑吧订单撤销发货
public Response cancelOrder(String orderId) throws Exception{
String url = ManagerHost + "/aorder/cancelOrder";
logger.info("请求兑吧订单发货撤销接口:" + url);
Map<String,String> map = new HashMap<>();
map.put("orderId",orderId);
map.put("massage","测试订单发货撤销");
Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://"+url);
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true");
} catch (Exception e) {
throw new Exception("兑吧订单发货撤销接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("兑吧订单发货撤销接口失败,返回信息:" + response.asString());
}
return response;
}
//管理后台加款
public Response doAddMoney(String money) throws Exception {
String url_token = ManagerHost + "/adminDuibaBalance/addMoney";
String url = ManagerHost + "/adminDuibaBalance/doAddMoney";
Response response = given().cookies(authorization.ssoLogin()).get("http://" + url_token);
String chargeToken = response.jsonPath().getString("chargeToken");
String adminId = response.jsonPath().getString("adminId");
Map<String, String> map = new HashMap<>();
map.put("adminId", adminId);
map.put("chargeToken", chargeToken);
map.put("money", money);
map.put("memo", "自动化加款");
map.put("token", "1");
logger.info("请求管理后台加款url:" + url);
response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://" + url);
//response.prettyPrint();
try {
Assert.assertEquals(String.valueOf(response.getStatusCode()), "200", "管理后台加款请求异常");
} catch (Exception e) {
throw new Exception("/adminDuibaBalance/doAddMoney接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/adminDuibaBalance/doAddMoney接口失败,返回信息:" + response.asString());
}
return response;
}
//管理后台减款
public Response doCutMoney(String money) throws Exception {
String url_token = ManagerHost + "/adminDuibaBalance/cutMoney";
String url = ManagerHost + "/adminDuibaBalance/doCutMoney";
Response response = given().cookies(authorization.ssoLogin()).get("http://" + url_token);
String chargeToken = response.jsonPath().getString("chargeToken");
String adminId = response.jsonPath().getString("adminId");
Map<String, String> map = new HashMap<>();
map.put("adminId", adminId);
map.put("chargeToken", chargeToken);
map.put("money", money);
map.put("memo", "自动化减款");
map.put("token", "1");
logger.info("请求管理后台减款url:" + url);
response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.ssoLogin()).params(map).post("http://" + url);
//response.prettyPrint();
try {
Assert.assertEquals(String.valueOf(response.getStatusCode()), "200", "管理后台加款请求异常");
} catch (Exception e) {
throw new Exception("/adminDuibaBalance/doCutMoney接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/adminDuibaBalance/doCutMoney接口失败,返回信息:" + response.asString());
}
return response;
}
}
package http.service.Activity;
import common.DuibaLog;
import http.service.Authorization;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.testng.Assert;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
/**
* @author mabo 签到
*/
@Service
public class SignactivityService {
@Value("${activity.host}")
String activityHost;
@Value("${hdserver.host}")
String hdHost;
@Autowired
Authorization authorization;
private DuibaLog logger = DuibaLog.getLogger();
/**
* 当前签到信息查询接口
* @param cookies
* @param signActivityId 签到活动id
* @return
* @throws Exception
*/
public Response getSignInfo(Map cookies,String signActivityId) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("signActivityId",signActivityId);
logger.info("请求getSignInfo接口,signActivityId="+signActivityId);
Response response = given().cookies(cookies).params(map).post(activityHost+"/signactivity/getSignInfo");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/signactivity/getSignInfo接口失败");
} catch (Exception e) {
throw new Exception("/signactivity/getSignInfo接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/signactivity/getSignInfo接口失败,返回信息:" + response.asString());
}
return response;
}
public Response getSignInfo(int uid,String signActivityId) throws Exception {
Map<String,String> map = new HashMap<>();
map.put("signActivityId",signActivityId);
logger.info("请求getSignInfo接口,signActivityId="+signActivityId);
Response response = given().cookies(authorization.dafuwengLogin(uid,true)).params(map).post(activityHost+"/signactivity/getSignInfo");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/signactivity/getSignInfo接口失败");
} catch (Exception e) {
throw new Exception("/signactivity/getSignInfo接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/signactivity/getSignInfo接口失败,返回信息:" + response.asString());
}
return response;
}
/**
* 签到
* @param cookies
* @param id 签到活动id
* @return
* @throws Exception
*/
public Response doSign(Map cookies,String id) throws Exception{
Map<String,String> map = new HashMap<>();
map.put("id",id);
logger.info("请求doSign接口,签到活动id="+id);
Response response = given().cookies(cookies).params(map).post(activityHost+"/signactivity/doSign");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/signactivity/doSign接口失败");
} catch (Exception e) {
throw new Exception("/signactivity/doSign接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/signactivity/doSign接口失败,返回信息:" + response.asString());
}
return response;
}
/**
* 补签
* @param cookies
* @param id 签到活动id
* @param activityId 插件活动id
* @param signDate 补签日期
* @return
* @throws Exception
*/
public Response reSign(Map cookies,String id,String activityId,String signDate) throws Exception{
Map<String,String> map = new HashMap<>();
map.put("id",id);
map.put("activityId",activityId);
map.put("signDate",signDate);
logger.info("请求reSign接口,签到活动id="+id+"插件活动activityId="+activityId);
Response response = given().cookies(cookies).params(map).post(activityHost+"/signactivity/reSign");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/signactivity/reSign接口失败");
} catch (Exception e) {
return response;
} catch (Error er) {
return response;
}
return response;
}
/**
* 签到结果查询接口
* @param cookies
* @param logId 签到流水id dosign接口返回数据
* @return
* @throws Exception
*/
public Response getSignResult(Map cookies,String logId) throws Exception{
Map<String,String> map = new HashMap<>();
map.put("logId",logId);
logger.info("请求getSignResult接口,logid="+logId);
Response response = given().cookies(cookies).params(map).post(activityHost+"/signactivity/getSignResult");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/signactivity/getSignResult接口失败");
} catch (Exception e) {
throw new Exception("/signactivity/getSignResult接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/signactivity/getSignResult接口失败,返回信息:" + response.asString());
}
return response;
}
/**
* 开发者后台编辑签到配置接口
* @param id 活动id
* @param data 签到周期开始时间
* @return
* @throws Exception
*/
public void configEdit(String id,String data) throws Exception{
Map<String,String> map = new HashMap<>();
map.put("appId","2239");
map.put("title","ceshi");
map.put("description","");
map.put("id",id);
map.put("signRule","{\"acValidityType\":\"EVER\",\"cusCirType\":\"FIXED_DAYS\",\"cusCirStart\":\""+data+"\",\"cusCirDays\":365,\"type\":\"CUSTOM_CIRCLE\"}");
map.put("reSignRule","{\"open\":true,\"dateUnit\":\"WEEK\",\"days\":31,\"conType\":\"NO\",\"credits\":null,\"card\":null,\"awardType\":\"CONTINUE\",\"countLimit\":null}");
map.put("cntReward","{\"rwType\":\"CONTINUE\",\"plActSkinId\":null,\"plActId\":null,\"items\":[{\"days\":null,\"credits\":0,\"activityCount\":1}],\"plSkinOpen2Dev\":false,\"open\":false}");
map.put("cirReward","{\"rwType\":\"CIRCLE\",\"plActSkinId\":null,\"plActId\":null,\"items\":[{\"days\":null,\"credits\":0,\"activityCount\":1}],\"plSkinOpen2Dev\":false,\"open\":false}");
map.put("acmReward","{\"rwType\":\"ACCUMULATE\",\"plActSkinId\":100,\"plActId\":1154,\"items\":[{\"days\":2,\"credits\":10,\"activityCount\":1}],\"plSkinOpen2Dev\":false,\"open\":true}");
map.put("firstSignReward","{\"rwType\":\"FIRST_SIGN\",\"plActSkinId\":null,\"plActId\":null,\"items\":[{\"days\":1,\"credits\":0,\"activityCount\":1}],\"plSkinOpen2Dev\":null,\"open\":false}");
map.put("operatingPositions","[]");
logger.info("请求configEdit接口");
Response response = given().contentType("application/x-www-form-urlencoded;charset=UTF-8").cookies(authorization.hdLogin()).params(map).post("http://"+hdHost+"/signin/configEdit");
try {
Assert.assertEquals(response.jsonPath().getString("success"), "true", "/signin/configEdit接口失败");
} catch (Exception e) {
throw new Exception("/signin/configEdit接口失败,返回信息:" + response.asString());
} catch (Error er) {
throw new Exception("/signin/configEdit接口失败,返回信息:" + response.asString());
}
}
}
package http.service;
import cn.com.duiba.credits.sdk.CreditTool;
import com.alibaba.fastjson.JSONObject;
import common.DuibaLog;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import utils.SecurityUtils;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static io.restassured.RestAssured.given;
import static io.restassured.path.json.JsonPath.from;
/**
* Created by hanzhanli on 2017/9/21.
*/
@Service
public class Authorization {
private DuibaLog logger = DuibaLog.getLogger();
@Value("${dafuweng.host}")
String dafuwengHost;
@Value("${dafuweng.port}")
int dafuwengPort;
@Value("${manager.host}")
String ManagerHost;
@Value("${hdserver.host}")
String hdHost;
@Value("${hdserver.name}")
String hdName;
@Value("${hdserver.password}")
String hdPassword;
@Value("${sso.loginurl}")
private String ssoLoginUrl;
@Value("${sso.loginname}")
private String ssoName;
@Value("${sso.loginpassword}")
private String ssoPassword;
final static String dafuwengLoginPath="/user/loginDuiba";
final static String hdLoginPath="/doLogin";
final static String hdGetToken="/getToken";
final static String PROTOCOL="http://";
final static String mangerLoginPath="/AItem/index.htm";
public static Map<Integer,Map> dafuwengCookiesMap = new ConcurrentHashMap();
private static Map<String,String> hdCookies;
private static Map<String,String> hdCookiesMabo;
private static Map<String,String> hdCookiesSaas;
private static Map<String,String> hdCookiesCommon;
private static Map<String,String> openbsCookies;
private Map<String,String> ssoCookies =null;
//大富翁登录
public Map dafuwengLogin(int uid){
int i=10;
Map<String,String> dafuwengCookies = null;
while((dafuwengCookiesMap.get(uid)==null||dafuwengCookiesMap.get(uid).size()==0)&&i>0) {
String url = PROTOCOL + dafuwengHost + ":" + dafuwengPort + dafuwengLoginPath;
Response response=given().redirects().follow(false).param("uid",uid).get(url);
String location = response.getHeader("location");
dafuwengCookies =response.getCookies();
//logger.info(location);
URL url1=null;
try {
url1= new URL(location);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if(url1!=null&&url1.getProtocol().equals("http")) {
response=given().cookies(dafuwengCookies).redirects().follow(false).get(location);
}else if(url1!=null&&url1.getProtocol().equals("https")){
response=given().cookies(dafuwengCookies).relaxedHTTPSValidation().redirects().follow(false).get(location);
}
dafuwengCookies=response.getCookies();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dafuwengCookiesMap.put(uid,dafuwengCookies);
i--;
}
if(dafuwengCookies==null || i==0){
logger.info("dafuweng登陆app失败,cookies为null");
}
return dafuwengCookiesMap.get(uid);
}
/**
* 大富翁登陆
* @param uid
* @param flag true则每次先清除cookiess
* @return
*/
public Map dafuwengLogin(int uid,boolean flag){
int i=10;
Map<String,String> dafuwengCookies = dafuwengCookiesMap.get(uid);
if(flag)dafuwengCookies=null;
while((dafuwengCookies==null||dafuwengCookies.size()==0)&&i>0) {
String url = PROTOCOL + dafuwengHost + ":" + dafuwengPort + dafuwengLoginPath;
Response response=given().redirects().follow(false).param("uid",uid).get(url);
String location = response.getHeader("location");
dafuwengCookies=response.getCookies();
//logger.info(location);
URL url1=null;
try {
url1= new URL(location);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if(url1!=null&&url1.getProtocol().equals("http")) {
response=given().cookies(dafuwengCookies).redirects().follow(false).get(location);
}else if(url1!=null&&url1.getProtocol().equals("https")){
response=given().cookies(dafuwengCookies).relaxedHTTPSValidation().redirects().follow(false).get(location);
}
dafuwengCookies=response.getCookies();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i--;
}
if(i==0&&dafuwengCookies==null){
logger.info("dafuweng登陆app失败,cookies为null");
}
return dafuwengCookies;
}
//openbs-自动化测试 app
//https://activity.m.duibatest.com.cn/ngame/index?id=20190&appKey=2wGQc3MZaQsqYFWcX4gguya5PnnS&openBs=openbs
public Map openbs(boolean flag){
int i=10;
if (flag) openbsCookies = null;
while((openbsCookies==null||openbsCookies.size()==0)&&i>0) {
String url = "http://activity.m.duibatest.com.cn/ngame/index?id=32075&appKey=3erv8LvBxKBSyuGK5i8FSGyYoFD1&openBs=openbs";
Response response=given().redirects().follow(false).get(url);
openbsCookies=response.getCookies();
logger.info("openbsCookies的信息为"+ JSONObject.toJSONString(openbsCookies));
i--;
}
if(i==0&&openbsCookies==null){
logger.info("dafuweng登陆app失败,cookies为null");
}
return openbsCookies;
}
//大富翁未登录
public Response autoLogin(){
CreditTool tool=new CreditTool("2wGQc3MZaQsqYFWcX4gguya5PnnS", "2D6y9SNdVSSkk7eBkoBYnvFGFGv9");
Map params=new HashMap();
params.put("uid","not_login");
params.put("credits","0");
String url=tool.buildUrlWithSign("http://home.m.duibatest.com.cn/autoLogin/autologin?",params);
logger.info("dafuweng免登陆url为:"+url);
Response response=given().redirects().follow(false).get(url);
return response;
}
public Map generateSignAutoLogin(String appKey, int uid){
String url = "http://activity.m.duibatest.com.cn/test/generateSign?appKey=" + appKey + "&uid=" + uid + "&vip=5";
Response response = given().get(url);
url = response.jsonPath().get("url");
response = given().redirects().follow(false).get(url);
return response.getCookies();
}
//开发者后台登录
public Map hdLogin(){
int i=10;
while((hdCookies==null||hdCookies.size()==0)&&i>0) {
Response token=this.hdGetToken();
String url = PROTOCOL + hdHost + hdLoginPath;
Map<String,String> cookies=token.getCookies();
Map<String, String> paras = new HashMap<>();
paras.put("email", hdName);
paras.put("password", SecurityUtils.getMD5(hdPassword+from(token.asString()).getString("data.loginsToken")));
paras.put("redirect", "/redirectApp");
paras.put("isAutoLogin", "true");
Response response = given().cookies(cookies).params(paras).post(url);
hdCookies=new HashMap<>(response.getCookies());
i--;
}
//取消安全校验
hdCookies.remove("csrf_token");
return hdCookies;
}
public Map hdLoginmabo(){
int i=10;
while((hdCookiesMabo==null||hdCookiesMabo.size()==0)&&i>0) {
Response token=this.hdGetToken();
String url = PROTOCOL + hdHost + hdLoginPath;
Map<String,String> cookies=token.getCookies();
Map<String, String> paras = new HashMap<>();
paras.put("email", "mabo@duiba.com.cn");
paras.put("password", SecurityUtils.getMD5("C47RYxxOfHr/EEajsMgIo8kdvZ8="+from(token.asString()).getString("data.loginsToken")));
paras.put("redirect", "/redirectApp");
paras.put("isAutoLogin", "true");
Response response = given().cookies(cookies).params(paras).post(url);
hdCookiesMabo=new HashMap<>(response.getCookies());
i--;
}
//取消安全校验
hdCookiesMabo.remove("csrf_token");
// logger.info(hdCookies);
return hdCookiesMabo;
}
public Map hdLoginSaas(){
int i=10;
while((hdCookiesSaas==null||hdCookiesSaas.size()==0)&&i>0) {
Response token=this.hdGetToken();
String url = PROTOCOL + hdHost + hdLoginPath;
Map<String,String> cookies=token.getCookies();
Map<String, String> paras = new HashMap<>();
paras.put("email", "wxs@duiba.com.cn");
paras.put("password", SecurityUtils.getMD5("dbZcFiIc5yMHcee/o/PJEfyZjug="+from(token.asString()).getString("data.loginsToken")));
paras.put("redirect", "/redirectApp");
paras.put("isAutoLogin", "true");
Response response = given().cookies(cookies).params(paras).post(url);
hdCookiesSaas=new HashMap<>(response.getCookies());
i--;
}
//取消安全校验
hdCookiesSaas.remove("csrf_token");
return hdCookiesSaas;
}
//密码为duibaduiba123
public Map hdLoginCommon(String email){
int i=10;
while((hdCookiesCommon==null||hdCookiesCommon.size()==0)&&i>0) {
Response token=this.hdGetToken();
String url = PROTOCOL + hdHost + hdLoginPath;
Map<String,String> cookies=token.getCookies();
Map<String, String> paras = new HashMap<>();
paras.put("email", email);
paras.put("password", SecurityUtils.getMD5("Dct7xTdGPvbUL1eOtSWoB9ySZNY="+from(token.asString()).getString("data.loginsToken")));
paras.put("redirect", "/redirectApp");
paras.put("isAutoLogin", "true");
Response response = given().cookies(cookies).params(paras).post(url);
hdCookiesCommon=new HashMap<>(response.getCookies());
i--;
}
//取消安全校验
hdCookiesCommon.remove("csrf_token");
// logger.info(hdCookies);
return hdCookiesCommon;
}
public Response hdGetToken(){
String url=PROTOCOL+hdHost+hdGetToken;
Map<String, String> paras = new HashMap<>();
paras.put("message","");
paras.put("redirectUrl","/redirectApp");
Response response=given().contentType(ContentType.JSON).body(paras).post(url);
//return from(response.asString()).getString("data.loginsToken");
return response;
}
//sso登录
public Map ssoLogin(){
if(ssoCookies ==null) {
Map<String, String> paras = new HashMap<>();
paras.put("email", ssoName);
paras.put("password", ssoPassword);
paras.put("systemId", "1");
paras.put("redirect", "http://mng.duibatest.com.cn/AItem/index.htm");
String url = "https://" + ssoLoginUrl;
Response response = given().relaxedHTTPSValidation().contentType(ContentType.JSON).body(paras).post(url);
ssoCookies =response.getCookies();
}
return ssoCookies;
}
public static void main(String[] args) {
// Map<Integer,Map> map = new HashMap<>();
// Map<String,String> map1 = new HashMap<>();
// map1.put("1","1");
//
// map.put(1,map1);
//
// map.get(1);
// map.get(2);
// String url = "http://home.m.duibatest.com.cn/test/generateSign?appKey=2wGQc3MZaQsqYFWcX4gguya5PnnS&uid=3402&vip=5";
String url = "http://activity.m.duibatest.com.cn/ngame/index?id=32075&appKey=3erv8LvBxKBSyuGK5i8FSGyYoFD1&openBs=openbs";
Response response=given().get(url);
response.prettyPrint();
// url = response.jsonPath().get("url");
// System.out.println(url);
// response=given().redirects().follow(false).get(url);
System.out.println(response.getCookies());
System.out.println("Set-Cookie的信息为"+response.getHeader("Set-Cookie"));
}
}
package http.service.hd;
import common.DuibaLog;
import http.service.Authorization;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.testng.Assert;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
@Service
public class SigninService {
@Value("${hdserver.host}")
String hdHost;
@Autowired
Authorization authorization;
private DuibaLog logger = DuibaLog.getLogger();
private String url = "http://activity.m.duibatest.com.cn";
public Response getSignActivityUrl(String appId,String id) {
Map<String,String> map = new HashMap<>();
map.put("appId",appId);
map.put("id",id);
Response response = given().cookies(authorization.hdLogin()).params(map).get("http://"+hdHost+"/signin/getSignActivityUrl");
response.prettyPrint();
return response;
}
//开发者自有弹层签到
public Response ajaxBanners() throws Exception{
Map<String,String> map = new HashMap<>();
map.put("activityId","");
map.put("url","chome");
map.put("preview","false");
Response response = given().cookies(authorization.dafuwengLogin(2720)).params(map).get(url+"/activityPlugin/ajaxBanners");
response.prettyPrint();
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/activityPlugin/ajaxBanners接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/activityPlugin/ajaxBanners接口失败,返回信息:"+response.asString());
}
return response;
}
//插件弹层抽奖
public Response doJoin(String activityId) throws Exception{
Map<String,String> map = new HashMap<>();
map.put("activityId",activityId);
map.put("url","chome");
Response response = given().cookies(authorization.dafuwengLogin(2720)).params(map).get(url+"/activitySign/doJoin");
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/activitySign/doJoin接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/activitySign/doJoin接口失败,返回信息:"+response.asString());
}
return response;
}
//插件弹层抽奖获取抽奖结果
public Response getOrderStatus(String orderId) throws Exception{
Map<String,String> map = new HashMap<>();
map.put("orderId",orderId);
Response response = given().cookies(authorization.dafuwengLogin(2720)).params(map).get(url+"/activitySign/getOrderStatus");
response.prettyPrint();
try{
Assert.assertEquals(response.jsonPath().getString("success"),"true");
}catch(Exception e){
throw new Exception("/activitySign/getOrderStatus接口失败,返回信息:"+response.asString());
}catch(Error er){
throw new Exception("/activitySign/getOrderStatus接口失败,返回信息:"+response.asString());
}
return response;
}
}
package http.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* Created by mabo on 2018/10/9
*/
@Service
public class testservice {
//数据库用户名
@Value("${db.name}")
String USERNAME;
public void test(){
System.out.println(USERNAME);
}
}
import common.DuibaBase;
import common.DuibaLog;
import http.Testhttp_Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.Test;
import ui.Testui;
import java.util.Random;
/**
* Created by mabo on 2018/9/20
*/
public class test extends DuibaBase{
@Autowired
Testhttp_Test test;
@Autowired
Testui testui;
public static int i=2;
public DuibaLog log = DuibaLog.getLogger();
@Test
public void test(){
test.test();
testui.test();
Random rand = new Random();
log.info("test log");
// Assert.assertEquals(1,rand.nextInt(2));
}
@Test
public void test1(){
i=i-1;
}
}
package ui;
import org.springframework.stereotype.Service;
/**
* Created by mabo on 2018/9/20
*/
@Service
public class Testui {
public void test(){
System.out.println("ui");
}
}
package utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherString {
public static String getString(String str,String reg,int index) {
String s;
try{
// 编译正则表达式
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(str);
matcher.find();
s = matcher.group(index);
}catch (IllegalStateException e){
s="";
System.out.println(e);
}
return s;
}
public static void main(String[] args) {
// String s ="{\"code\":\"0000000\",\"desc\":\"成功\",\"data\":{\"result\":2,\"activityId\":4215,\"orderId\":\"46657360240019\",\"lottery\":{\"imgurl\":\"//yun.yuyiya.com/mami-media/img/d7maz2jx30.png\",\"page2\":{\"st_info_exposure\":\"{\\\"dpm\\\":\\\"23251.109.2.0\\\",\\\"activityId\\\":4215,\\\"orderId\\\":\\\"46657360240019\\\",\\\"consumerId\\\":2610560019,\\\"domain\\\":\\\"//embedlog.pre.duiba.com.cn\\\",\\\"appId\\\":23251,\\\"device_type\\\":\\\"tuia\\\",\\\"slotId\\\":369}\",\"st_info_click_btn_close\":\"{\\\"dpm\\\":\\\"23251.109.2.4\\\",\\\"activityId\\\":4215,\\\"orderId\\\":\\\"46657360240019\\\",\\\"consumerId\\\":2610560019,\\\"appId\\\":23251,\\\"domain4Web\\\":\\\"//activity.yuyiya.com\\\",\\\"device_type\\\":\\\"tuia\\\",\\\"slotId\\\":369,\\\"url\\\":\\\"/statistics/click\\\"}\",\"st_info_click_btn_record\":\"{\\\"dpm\\\":\\\"23251.109.2.1\\\",\\\"activityId\\\":4215,\\\"orderId\\\":\\\"46657360240019\\\",\\\"consumerId\\\":2610560019,\\\"appId\\\":23251,\\\"domain4Web\\\":\\\"//activity.yuyiya.com\\\",\\\"device_type\\\":\\\"tuia\\\",\\\"slotId\\\":369,\\\"url\\\":\\\"/statistics/click\\\",\\\"dcm\\\":\\\"1010.0.0.0\\\"}\"},\"page1\":{\"st_info_click_btn_save\":\"{\\\"dpm\\\":\\\"23251.109.1.1\\\",\\\"activityId\\\":4215,\\\"orderId\\\":\\\"46657360240019\\\",\\\"consumerId\\\":2610560019,\\\"appId\\\":23251,\\\"domain4Web\\\":\\\"//activity.yuyiya.com\\\",\\\"device_type\\\":\\\"tuia\\\",\\\"slotId\\\":369,\\\"url\\\":\\\"/statistics/click\\\"}\",\"st_info_exposure\":\"{\\\"dpm\\\":\\\"23251.109.1.0\\\",\\\"activityId\\\":4215,\\\"orderId\\\":\\\"46657360240019\\\",\\\"consumerId\\\":2610560019,\\\"domain\\\":\\\"//embedlog.pre.duiba.com.cn\\\",\\\"appId\\\":23251,\\\"device_type\\\":\\\"tuia\\\",\\\"slotId\\\":369}\",\"st_info_click_btn_close\":\"{\\\"dpm\\\":\\\"23251.109.1.2\\\",\\\"activityId\\\":4215,\\\"orderId\\\":\\\"46657360240019\\\",\\\"consumerId\\\":2610560019,\\\"appId\\\":23251,\\\"domain4Web\\\":\\\"//activity.yuyiya.com\\\",\\\"device_type\\\":\\\"tuia\\\",\\\"slotId\\\":369,\\\"url\\\":\\\"/statistics/click\\\"}\"},\"id\":28290,\"layerImgUrl\":\"//yun.tuia.cn/mami-media/img/cm4ahxmpwl.png\",\"type\":\"physical\",\"title\":\"测试实物\"},\"status\":\"success\"},\"success\":true}";
String s = "{\"1\":{\"btnText\":\"马上兑换\",\"credits\":\"100\",\"limitCount\":\"\",\"limitScope\":\"forever\",\"tipText\":\"\",\"status\":true},\"2\":{\"btnText\":\"已兑换\",\"credits\":\"200\",\"limitCount\":\"1\",\"limitScope\":\"forever\",\"tipText\":\"此选项只能兑换1次\",\"status\":false},\"3\":{\"btnText\":\"马上兑换\",\"credits\":\"300\",\"limitCount\":\"1\",\"limitScope\":\"everyday\",\"tipText\":\"此选项每日只能兑换1次\",\"status\":true},\"4\":{\"btnText\":\"马上兑换\",\"credits\":\"400\",\"limitCount\":\"1\",\"limitScope\":\"month\",\"tipText\":\"此选项每月只能兑换1次\",\"status\":true},\"10\":{\"btnText\":\"马上兑换\",\"credits\":\"10\",\"limitCount\":\"\",\"limitScope\":\"forever\",\"tipText\":\"\",\"status\":true}};";
String reg = "\"2\":{\"btnText\":\"(.*?)\",";
System.out.println(getString(s,reg,1));
}
}
package utils;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
* Created by mabo on 2018/10/9
*/
public class SecurityUtils {
public static String getMD5(String str) {
String result=null;
try {
// 生成一个MD5加密计算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(str.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
result=new BigInteger(1, md.digest()).toString(16);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
tuiaHost=act.dui88.com
tuiaPort=80
proxyserver.ip=172.16.80.203
proxyserver.port=22
proxyserver.user=dev
proxyserver.prvkey=key/hzlId_rsa
dafuweng.host=47.97.214.108
dafuweng.port=9002
uid=2707
appId=2239
hdserver.host=hd.dlp.duibatest.com.cn
hdserver.name=humengxin@duiba.com.cn
hdserver.password=3Rq1TXSZuVQw3RxydD9K2IR/skk=
sso.loginurl=sso.duibatest.com.cn/doLogin
sso.loginname= zhaoran@duiba.com.cn
sso.loginpassword = 123456
goods.host = activity.m.duibatest.com.cn
activity.host = http://activity.m.duibatest.com.cn
seckill.host = activity.m.duibatest.com.cn
home.host = activity.m.duibatest.com.cn
manager.host = mng.duibatest.com.cn
trade.host = activity.m.duibatest.com.cn
db.name = duiba_test
db.password= svbP3KUw2PurAnBb2rbs3vohF
db.url = jdbc:mysql://rdswy2b9wy53044250u1o.mysql.rds.aliyuncs.com:3306/
db.driver= com.mysql.jdbc.Driver
db.maxtotal = 1
pluginTest.project=插件
pluginTest.names=zhaoran,qianwenjun
pluginTest.group=插件-接口自动化
pluginTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaPlugin_interface/HTML_Report/suite1_test1_results.html
signTest.project=签到
signTest.names=zhousongbo
signTest.group=签到-接口自动化
signTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaSign_interface/HTML_Report/suite1_test1_results.html
FloorTest.project=楼层
FloorTest.names=zhaoran,qianwenjun
FloorTest.group=楼层-接口自动化
FloorTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaFloor_interface/HTML_Report/suite1_test1_results.html
DuibaTest.project=活动工具
DuibaTest.names=zhaoran,qianwenjun
DuibaTest.group=活动工具-接口自动化
DuibaTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duiba_interface/HTML_Report/suite1_test1_results.html
AccessTest.project=综合业务(单品抽奖/秒杀/游戏)
AccessTest.names=zhaoran,qianwenjun
AccessTest.group=综合业务-接口自动化
AccessTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaAccess_interface/HTML_Report/suite1_test1_results.html
JenkinsTest.project=综合业务(单品抽奖/秒杀/游戏)
JenkinsTest.names=zhaoran,qianwenjun
JenkinsTest.group=综合业务-接口自动化
JenkinsTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaAccess_interface/HTML_Report/suite1_test1_results.html
ExchangeTest.project=普兑业务
ExchangeTest.names=panyuli
ExchangeTest.group=普兑业务-接口自动化
ExchangeTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaExchange_interface/HTML_Report/suite1_test1_results.html
\ No newline at end of file
tuiaHost=act.dui88.com
tuiaPort=80
proxyserver.ip=172.16.80.203
proxyserver.port=22
proxyserver.user=dev
proxyserver.prvkey=key/hzlId_rsa
dafuweng.host=47.97.214.108
dafuweng.port=9002
uid=2707
appId=2239
hdserver.host=hd.dlp.duibatest.com.cn
hdserver.name=humengxin@duiba.com.cn
hdserver.password=3Rq1TXSZuVQw3RxydD9K2IR/skk=
sso.loginurl=sso.duibatest.com.cn/doLogin
sso.loginname= zhaoran@duiba.com.cn
sso.loginpassword = 123456
goods.host = activity.m.duibatest.com.cn
activity.host = http://activity.m.duibatest.com.cn
seckill.host = activity.m.duibatest.com.cn
home.host = activity.m.duibatest.com.cn
manager.host = mng.duibatest.com.cn-test
trade.host = activity.m.duibatest.com.cn
pluginTest.project=插件
pluginTest.names=zhaoran,qianwenjun
pluginTest.group=插件-接口自动化
pluginTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaPlugin_interface/HTML_Report/suite1_test1_results.html
signTest.project=签到
signTest.names=zhousongbo
signTest.group=签到-接口自动化
signTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaSign_interface/HTML_Report/suite1_test1_results.html
FloorTest.project=楼层
FloorTest.names=zhaoran,qianwenjun
FloorTest.group=楼层-接口自动化
FloorTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaFloor_interface/HTML_Report/suite1_test1_results.html
DuibaTest.project=活动工具
DuibaTest.names=zhaoran,qianwenjun
DuibaTest.group=活动工具-接口自动化
DuibaTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duiba_interface/HTML_Report/suite1_test1_results.html
AccessTest.project=综合业务(单品抽奖/秒杀/游戏)
AccessTest.names=zhaoran,qianwenjun
AccessTest.group=综合业务-接口自动化
AccessTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaAccess_interface/HTML_Report/suite1_test1_results.html
JenkinsTest.project=综合业务(单品抽奖/秒杀/游戏)
JenkinsTest.names=zhaoran,qianwenjun
JenkinsTest.group=综合业务-接口自动化
JenkinsTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaAccess_interface/HTML_Report/suite1_test1_results.html
ExchangeTest.project=普兑业务
ExchangeTest.names=panyuli
ExchangeTest.group=普兑业务-接口自动化
ExchangeTest.resultUrl=http://tst.deploy.dui88.com/view/duibaTest/job/duibaExchange_interface/HTML_Report/suite1_test1_results.html
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?><configuration status="warn">
<appenders>
<Console name="Console" target="SYSTEM_OUT" follow="false">
<PatternLayout pattern="%5p:%d{yyyy-MM-dd HH:mm:ss.SSS} %logger{36} [%M] : %m %n"/>
</Console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
<File name="log" fileName="log/test.log" append="false">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
</File>
<!-- 这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="log/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
<SizeBasedTriggeringPolicy size="50MB"/>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
<DefaultRolloverStrategy max="20"/>
</RollingFile>
</appenders>
<loggers>
<!--
<logger name="name" level="warn" additivity="false">
<AppenderRef ref="Console"/>
</logger>
-->
<logger name="com.duiba" level="info" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="log"/>
</logger>
<root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="log"/>
</root>
</loggers>
</configuration>
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