Commit 506999c8 by shuai

20190318

parent 680319ac
......@@ -9,7 +9,7 @@
<property name="srcdir" location="src" />
<property name="libdir" location="lib" />
<property name="full-compile" value="true" />
<property name="basedir" value="D:/workspace/auto_test/" />
<property name="basedir" value="." />
<path id="classpath.test">
<fileset dir="${libdir}">
......@@ -62,9 +62,8 @@
</target>
<target name="testoutput" depends="runtest">
<java classname="com.offcn.TestUnti.Mail" classpath="${basedir}/bin">
<sysproperty key="file.encoding" value="UTF-8" />
<java classname="com.offcn.TestUnti.MyNewMail" classpath="${basedir}/bin" classpathref="classes">
<sysproperty key="file.encoding" value="UTF-8"/>
<classpath>
<pathelement location="lib/javax.mail.jar" />
</classpath>
......
......@@ -6,7 +6,7 @@
<classes>
<class name="com.puhui.test.RenMai_APITest">
<methods>
<include name="f" invocation-numbers=""/>
<include name="f" invocation-numbers="34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 "/>
</methods>
</class>
</classes>
......
......@@ -6,6 +6,7 @@ import com.offcn.TestUnti.ReadExcels;
import com.offcn.TestUnti.ReadProperties;
public class offcn_api_testData {
public static int Testcount=0;//总得用力数量
@DataProvider(name="renmai")
public static Object[][] dp(){
......
package com.offcn.TestUnti;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MYSQLConnection {
public static Connection coontSql(String url,String name,String pwd){
Connection ct=null;
try {
Class.forName("com.mysql.jdbc.Driver");
ct = DriverManager.getConnection(url, name,pwd);
} catch (ClassNotFoundException e) {
System.out.println("获取驱动失败");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("建立连接失败");
e.printStackTrace();
}
return ct;
}
public static Statement stmtSql(Connection ct){
Statement stmt = null;
try {
stmt = ct.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stmt;
}
}
......@@ -2,8 +2,12 @@ package com.offcn.TestUnti;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
......@@ -24,6 +28,48 @@ public class MapUtil {
HashMap<String, Object> newhm=Expect(hm);
System.out.println("@AfterClass_data_ext="+JSONObject.fromObject(newhm).toString());
}
//降序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map)
{
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
{
int compare = (o1.getValue()).compareTo(o2.getValue());
return -compare;
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
//升序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueAscending(Map<K, V> map)
{
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
{
int compare = (o1.getValue()).compareTo(o2.getValue());
return compare;
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
//马洪亮
// 生成数组格式的json串
public static String getArrayJson(String para) {
......
......@@ -12,17 +12,21 @@ import javax.mail.internet.MimeMultipart;
import org.testng.annotations.Test;
import com.offcn.listener.SkipIInvokedMethodListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
public class Mail {
public class MyNewMail {
public static void main(String[] args) {
try {
Mail.POP3();
MyNewMail.POP3();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
......@@ -32,7 +36,7 @@ public class Mail {
@Test
public static void mailToAll(){
try {
Mail.POP3();
MyNewMail.POP3();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
......@@ -162,15 +166,34 @@ public class Mail {
// System.out.println("isTrue="+isTrue);
String flowCase="";
if(isTrue){
TestTitle=" <font size='6' color='#00FF00'>本次测试通过率:"+Percentage+"</font></br></br> ";
}else{
TestTitle=" <font size='6' color='#FF0000'>本次测试通过率:"+Percentage+"</font> </br></br>";
TestResule=ReadHtml.readFile_("suite1_test1_results.html");
flowCase=flowCase+fileUntil.readFile_line("map.txt");
// Set<String> keySet = SkipIInvokedMethodListener.serviceUrlMap.keySet();
//
// //有了Set集合。就可以获取其迭代器。
// Iterator<String> it = keySet.iterator();
//
// while(it.hasNext()){
// String key = it.next();
// //有了键可以通过map集合的get方法获取其对应的值。
// Integer value = SkipIInvokedMethodListener.serviceUrlMap.get(key);
//
// flowCase=flowCase+" <font size='4' color='#FF0000'>流程案例:"+key+",错误了"+value+"次。</font> </br>";
// }
// flowCase=flowCase+"共跳过用例"+SkipIInvokedMethodListener.SkipTestnumber+"条";
}
// 这里添加图片的方式是将整个图片包含到邮件内容中, 实际上也可以以 http 链接的形式添加网络图片+ReadHtml.readFile_("suite1_test1_results.html")
text.setContent(TestTitle+"</br></br>"+ReadHtml.readFile_("overview.html")+"</br></br>"+TestResule, "text/html;charset=UTF-8");
text.setContent(TestTitle+"</br></br>"+ReadHtml.readFile_("overview.html")+flowCase+"</br>"+TestResule, "text/html;charset=UTF-8");
//
// // 7. (文本+图片)设置 文本 和 图片"节点"的关系(将 文本 和 图片"节点"合成一个混合"节点")
// MimeMultipart mm_text_image = new MimeMultipart();
......@@ -254,13 +277,15 @@ public class Mail {
public static InternetAddress[] parseAddress(String personnel){
String addr="";
if("all".equals(personnel)){
addr="mengrui60355@offcn.com;wufeifei66504@offcn.com;liyongyu@offcn.com;"
+"mazengli@offcn.com;wangzhipeng53655@offcn.com;liuchungang@offcn.com;"
+ "liyongyu@offcn.com;zhanghua54164@offcn.com;liwendong@offcn.com;"
+ "zhangshijie62302@offcn.com;baimanbin@offcn.com";
addr="wufeifei66504@offcn.com";
// addr="mengrui60355@offcn.com;wufeifei66504@offcn.com;liyongyu@offcn.com;"
// +"mazengli@offcn.com;wangzhipeng53655@offcn.com;liuchungang@offcn.com;"
// + "liyongyu@offcn.com;zhanghua54164@offcn.com;liwendong@offcn.com;"
// + "zhangshijie62302@offcn.com;baimanbin@offcn.com";
}else{
addr="mengrui60355@offcn.com;wufeifei66504@offcn.com;liyongyu@offcn.com";
addr="wufeifei66504@offcn.com";
// addr="mengrui60355@offcn.com;wufeifei66504@offcn.com;liyongyu@offcn.com";
}
StringTokenizer token = new StringTokenizer(addr, ";");
......
......@@ -45,4 +45,6 @@ public class MySqlUtil {
return list;
}
}
......@@ -15,6 +15,8 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.offcn.TestData.offcn_api_testData;
public class ReadExcels {
private String fileName;
private String SheetName;
......@@ -64,6 +66,9 @@ public class ReadExcels {
list.add(getCellValue(cell));
}
}
offcn_api_testData.Testcount=arrmap.length;//保存总体的用例数量
Log.logInfo("数据源读取记录:共有几列数据="+list.size());
Log.logInfo("数据源读取记录:共有几行数据="+arrmap.length);
for(int i = 1 ; i < sheet.getPhysicalNumberOfRows() ; i++){
......
......@@ -13,12 +13,10 @@ import com.offcn.interfaces.API;
*/
public class Reflect_api {
public API Reflections(HashMap<String, Object> data) {
public Class<?> ReflecClass(HashMap<String, Object> data) {
String ClassName = Reflect_api.getRefleserviceUrlxClassName(data);
API obj = null;
Class c = null;
Class<?> c = null;
int count=1;
while(true){
try {
c = Class.forName(ClassName);
......@@ -26,11 +24,8 @@ public class Reflect_api {
}catch (ClassNotFoundException e) {
String serviceUrl = data.get("serviceUrl").toString();
String CalssName_new = serviceUrl.split("/")[serviceUrl.split("/").length - 1];
String system = MapUtil.getValue("system", data);
String classRoute = ReadProperties.GetPropertyByKey(system);
ClassName=classRoute+"process."+CalssName_new;
// String system = MapUtil.getValue("system", data);
// String classRoute = ReadProperties.GetPropertyByKey(system);
......@@ -41,29 +36,24 @@ public class Reflect_api {
// String classRoute1 = ReadProperties.GetPropertyByKey("gmysx");
// ClassName=ClassName.replaceAll(classRoute, classRoute1);
// }
}
if(count==3){
Log.logError("Reflect_api,ReflexClass Error,Classname=" + ClassName);
break;
}
}
return c;
}
public Object ReflecObj(Class<?> c){
Object obj = null;
try{
obj = (API) c.newInstance();
obj = c.newInstance();
}catch (InstantiationException e) {
Log.logError("Reflect_api,instantiation Error,Classname="
+ ClassName);
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.logError("Reflect_api,Reflection class is not public Error,Classname="
+ ClassName);
e.printStackTrace();
}
return obj;
}
// 获得数据中serviceUrl所对应的类名
......
......@@ -11,11 +11,13 @@ import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.offcn.process.BasicsGM;
import com.offcn.process.XYZB;
import com.offcn.system.MyRequest;
import com.offcn.system.system;
import static io.restassured.http.ContentType.JSON;
......@@ -48,12 +50,287 @@ public class RequestDataUtils {
return ra;
}
public static Response RestAssuredApi(HashMap<String, Object> data,MyRequest myRequest){
if("get".equals(myRequest.getRequest())){
return Get(data,myRequest);
}else if("post".equals(myRequest.getRequest())){
return PostAll(data,myRequest);
}else if("put".equals(myRequest.getRequest())){
return Put(data,myRequest);
}else if("del".equals(myRequest.getRequest())){
return Del(data,myRequest);
}else{
return null;
}
}
public static Response PostAll(HashMap<String, Object> data,MyRequest myRequest){
if(myRequest.getFormParameter()!=null){
if(myRequest.getFile()!=null){
return Post_file(data,myRequest);
}else{
return Post_form_data(data,myRequest);
}
}else if(myRequest.getParameter()!=null){
return Post_JSON(data,myRequest);
}
return null;
}
public static Response Post_file(HashMap<String, Object> data,MyRequest myRequest) {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
String path=tem.getRM_URI()+tem.getRM_port()+tem.getRM_basePath()+myRequest.getUrl();
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString()+"," +path+ ",Parameter=" + Parameter);
int state = 0;
Response re = null;
RequestDataUtils rdu = new RequestDataUtils();
while (state < 5) {
try {
state++;
File filen=new File("out/"+myRequest.getFile());
re = rdu.getRMEnv(tem).given()
.headers(myRequest.getHeaders()!=null?myRequest.getHeaders():new HashMap<String, String>())
.cookies(myRequest.getCookies()!=null?myRequest.getCookies():new HashMap<String, String>())
.params(myRequest.getFormParameter()).when().multiPart("image", filen)
.post(myRequest.getUrl()).thenReturn();
if (!"200".equals(re.getStatusCode()+"")) {
Log.logError("请求返回:" +re.getStatusCode()+",第"+ state + "次。");
Thread.sleep(1000);
} else {
return re;
}
} catch (Exception e) {
e.printStackTrace();
Log.logError("请求超时," + state + "次。");
}
}
return re;
}
public static Response Post_form_data(HashMap<String, Object> data,MyRequest myRequest) {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
String path=tem.getRM_URI()+tem.getRM_port()+tem.getRM_basePath()+myRequest.getUrl();
parameter=parameter.substring(1, parameter.length()-1);
Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+","+path+",Parameter="+parameter);
// 设置参数格式
int state = 0;
Response re = null;
RequestDataUtils rdu = new RequestDataUtils();
while (state < 5) {
try {
state++;
re = rdu.getRMEnv(tem).given()
.headers(myRequest.getHeaders()!=null?myRequest.getHeaders():new HashMap<String, String>())
.cookies(myRequest.getCookies()!=null?myRequest.getCookies():new HashMap<String, String>())
.params(myRequest.getFormParameter())
.when()
.post(myRequest.getUrl())
.thenReturn();
JsonPath jp = re.body().jsonPath();
if ("500".equals(jp.getString("status"))) {
Log.logError("请求返回500," + state + "次。");
Thread.sleep(1000);
} else {
return re;
}
} catch (Exception e) {
e.printStackTrace();
Log.logError("请求超时," + state + "次。");
}
}
return re;
}
//不带token的post请求
@SuppressWarnings("static-access")
public static Response Post_JSON(HashMap<String, Object> data,MyRequest myRequest) {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
String path=tem.getRM_URI()+tem.getRM_port()+tem.getRM_basePath()+myRequest.getUrl();
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() +","+path+ ",Parameter=" + Parameter);
int state = 0;
Response re = null;
RequestDataUtils rdu = new RequestDataUtils();
while (state < 5) {
try {
state++;
re = rdu.getRMEnv(tem).given()
.headers(myRequest.getHeaders()!=null?myRequest.getHeaders():new HashMap<String, String>())
.cookies(myRequest.getCookies()!=null?myRequest.getCookies():new HashMap<String, String>())
.contentType(JSON).body("{"+Parameter+"}").when()
.post(myRequest.getUrl()).thenReturn();
if (!"200".equals(re.getStatusCode()+"")) {
Log.logError("请求返回," + re.getStatusCode() + "次。");
Thread.sleep(1000);
} else {
return re;
}
} catch (Exception e) {
e.printStackTrace();
Log.logError("请求超时," + state + "次。");
}
}
return re;
}
@SuppressWarnings("deprecation")
public static Response Put(HashMap<String, Object> data,MyRequest myRequest) {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
String path=tem.getRM_URI()+tem.getRM_port()+tem.getRM_basePath()+myRequest.getUrl();
parameter=parameter.substring(1, parameter.length()-1);
Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+","+path+",Parameter="+parameter);
// 设置参数格式
int state = 0;
Response re = null;
RequestDataUtils rdu = new RequestDataUtils();
while (state < 5) {
try {
state++;
re = rdu.getRMEnv(tem).given().config(RestAssured.config()
.encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("x-www-form-urlencoded", ContentType.ANY)
.defaultContentCharset("utf-8")))
.headers(myRequest.getHeaders()!=null?myRequest.getHeaders():new HashMap<String, String>())
.cookies(myRequest.getCookies()!=null?myRequest.getCookies():new HashMap<String, String>())
.formParameters(myRequest.getFormParameter())
.when().put(myRequest.getUrl()).thenReturn();
JsonPath jp = re.body().jsonPath();
if ("500".equals(jp.getString("status"))) {
Log.logError("请求返回500," + state + "次。");
Thread.sleep(1000);
} else {
return re;
}
} catch (Exception e) {
e.printStackTrace();
Log.logError("请求超时," + state + "次。");
}
}
return re;
}
public static Response Del(HashMap<String, Object> data,MyRequest myRequest) {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
String path=tem.getRM_URI()+tem.getRM_port()+tem.getRM_basePath()+myRequest.getUrl();
parameter=parameter.substring(1, parameter.length()-1);
Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+","+path+",Parameter="+parameter);
// 设置参数格式
Log.logInfo("serviceURL=" + myRequest.getUrl() + ",Parameter=" + myRequest.getParameter());
int state = 0;
Response re = null;
RequestDataUtils rdu = new RequestDataUtils();
while (state < 5) {
try {
state++;
re = rdu.getRMEnv(tem).given()
.headers(myRequest.getHeaders()!=null?myRequest.getHeaders():new HashMap<String, String>())
.cookies(myRequest.getCookies()!=null?myRequest.getCookies():new HashMap<String, String>())
.when().delete(myRequest.getUrl()).thenReturn();
JsonPath jp = re.body().jsonPath();
if ("500".equals(jp.getString("status"))) {
Log.logError("请求返回500," + state + "次。");
Thread.sleep(1000);
} else {
return re;
}
} catch (Exception e) {
Log.logError("请求超时," + state + "次。");
}
}
return re;
}
@SuppressWarnings("static-access")
public static Response Get(HashMap<String, Object> data,MyRequest myRequest) {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
String path=tem.getRM_URI()+tem.getRM_port()+tem.getRM_basePath()+myRequest.getUrl();
parameter=parameter.substring(1, parameter.length()-1);
Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+","+path+",Parameter="+parameter);
int state=0;
Response re=null;
RequestDataUtils rdu=new RequestDataUtils();
while(state<3){
try {
state++;
if(parameter != null && !"".equals(parameter)) {
re = rdu.getRMEnv(tem).given()
.headers(myRequest.getHeaders()!=null?myRequest.getHeaders():new HashMap<String, String>())
.cookies(myRequest.getCookies()!=null?myRequest.getCookies():new HashMap<String, String>())
.get(myRequest.getUrl() + "?" + parameter).andReturn();
}else {
re = rdu.getRMEnv(tem).given()
.headers(myRequest.getHeaders()!=null?myRequest.getHeaders():new HashMap<String, String>())
.cookies(myRequest.getCookies()!=null?myRequest.getCookies():new HashMap<String, String>())
.get(myRequest.getUrl()).andReturn();
}
if(!"200".equals(re.statusCode()+"")){
Log.logError("请求返回"+re.statusCode()+"次。");
}else{
return re;
}
} catch (Exception e) {
Log.logError("请求超时,"+state+"次。");
}
}
return re;
}
//不带token的post请求
public static Response Post_headers(HashMap<String, Object> data, String serviceURL,String zgl_clienttype) {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -91,7 +368,7 @@ public class RequestDataUtils {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -158,7 +435,7 @@ public class RequestDataUtils {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -193,7 +470,7 @@ public class RequestDataUtils {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -228,7 +505,7 @@ public class RequestDataUtils {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -264,7 +541,7 @@ public class RequestDataUtils {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -301,7 +578,7 @@ public class RequestDataUtils {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -338,7 +615,7 @@ public class RequestDataUtils {
// 设置参数格式
String Parameter = (String) data.get("parameter");
String system = MapUtil.getValue("system", data);
String system = MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));
Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);
......@@ -376,7 +653,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -414,7 +691,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -452,7 +729,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -490,7 +767,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -528,7 +805,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -566,7 +843,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -601,7 +878,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -635,7 +912,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -675,7 +952,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -713,7 +990,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -751,7 +1028,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -793,7 +1070,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -840,7 +1117,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -876,7 +1153,7 @@ public class RequestDataUtils {
//设置参数格式
String parameter= MapUtil.getParameter(data);
String system= MapUtil.getValue("system", data);
String system= MapUtil.getValue("system", data);system = replaceString(system);
com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));
......@@ -909,4 +1186,10 @@ public class RequestDataUtils {
}
return re;
}
public static String replaceString(String SystemName){
if(SystemName.contains("_")){
SystemName=SystemName.split("_")[0];
}
return SystemName;
}
}
......@@ -37,7 +37,7 @@ public class XMLread {
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(new File("src/resources/system.xml")); // 读取XML文件,获得document对象
document = saxReader.read(new File("src/resources/system.xml")); // 读取XML文件,获得document对象DatabaseSql.xml
// 获取根节点
Element root = document.getRootElement();
// 获取根节点下的子节点
......@@ -61,6 +61,40 @@ public class XMLread {
}
return map;
}
public Map<String, Object> getDatabaseSql(){
Document document = null;
Object obj=null;
Method met=null;
Map<String,Object> map=new HashMap<String,Object>();
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(new File("src/resources/DatabaseSql.xml")); // 读取XML文件,获得document对象DatabaseSql.xml
// 获取根节点
Element root = document.getRootElement();
// 获取根节点下的子节点
for (Iterator i = root.elementIterator(); i.hasNext();) {
// 将每个子节点赋给el
Element el = (Element) i.next();
// 如果节点的名称为“system”,system元素属性name=参数// && systemName.equals(el.attribute("name").getValue())
if ("Database".equals(el.getName())) {// 获取节点元素的名称
Class c=Class.forName("com.offcn.system.sql");
obj=(Object) c.newInstance();
for (Iterator it = el.elementIterator(); it.hasNext();) {
Element elchild = (Element) it.next();
met=c.getDeclaredMethod(getMethodName(elchild.getName()), String.class);
met.invoke(obj, elchild.getText());
map.put(el.attribute("name").getValue(), obj);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
//获取注入得方法名
private String getMethodName(String str){
String s="set"+str.substring(0,1).toUpperCase()+str.substring(1,str.length());
......
......@@ -17,7 +17,7 @@ import java.util.zip.ZipOutputStream;
* @author ZENG.XIAO.YAN
* @date 2017年11月19日 下午7:16:08
* @date 2017年11月19日 下午7:16:0811
* @version v1.0
......@@ -292,7 +292,7 @@ public class ZipUtils {
deleteFile(mailpath+"测试报告详细资料.zip");//删除文件
List<File> fileList = new ArrayList<>();
// fileList.add(new File(mailpath));
fileList.add(new File(mailpath+"index.html"));
fileList.add(new File(mailpath+"overview.html"));
fileList.add(new File(mailpath+"reportng.css"));
......
package com.offcn.TestUnti;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
public class cmdUtil {
......@@ -16,7 +28,7 @@ public class cmdUtil {
while ((line=br.readLine())!=null) {
b.append(line+"\n");
}
// System.out.println(b.toString());
System.out.println(b.toString());
} catch (Exception e) {
e.printStackTrace();
}
......@@ -24,11 +36,99 @@ public class cmdUtil {
}
public static void main(String[] args) {
cmdUtil delp = new cmdUtil();
System.out.println(delp.run("nslookup www.qq.com").contains("Address: 192.168.10.222"));
// delp.run("nslookup www.qq.com");
// delp.run("netsh interface ip set dns \"无线网络连接\" static 192.168.10.222");
public static void main(String[] args) throws IOException {
Properties properties = System.getProperties();
System.setProperty("path", "C:\\Program Files (x86)\\PICT\\;");
Iterator it = properties.entrySet().iterator();
while(it.hasNext())
{
Entry entry = (Entry)it.next();
System.out.print(entry.getKey()+"=");
System.out.println(entry.getValue());
}
// String batName = "C:/Users/ibm/git/tiku_app/tiku_App/src/resources/abc.bat";
// Runtime rt = Runtime.getRuntime();
// Process ps = null;
// try {
//// ps = rt.exec("cmd.exe /C start /b " + batName);
// ps = rt.exec("cmd.exe /c " + "copy C:/Users/ibm/git/tiku_app/tiku_App/src/resources/abc.bat C:/Users/ibm/git/tiku_app/tiku_App/src/resources/abc.bat111");
// System.out.println(ps.waitFor());
//// FileInputStream fis = null;
//// fis=(FileInputStream) ps.getErrorStream();
////
//// byte[] buf = new byte[1024];
//// int len = 0;
//// while((len=fis.read(buf))!=-1)
//// {
//// System.out.println(new String(buf,0,len));
//// }
////
//// fis.close();
// } catch (IOException e1) {
// e1.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// int i = ps.exitValue();
// if (i == 0) {
// System.out.println("执行完成.");
// } else {
// System.out.println("执行失败.");
// }
// try {
// File directory = new File(".");
// String sourceFile;
// String sourceFile1;
// sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"case.txt";
// sourceFile1 = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator;
// String cmd = "pict "+sourceFile+">"+sourceFile1+"caseOut.txt";
// String cmd2 = "cmd /c " + "\"\" " + cmd ;
// String cmd3 = "cmd.exe /c " + "copy C:/Users/ibm/git/tiku_app/tiku_App/src/resources/abc.bat C:/Users/ibm/git/tiku_app/tiku_App/src/resources/abc.bat111";
// System.out.println(cmd3);
// run(cmd3);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
public static void processBuilderCommand() throws Exception {
File directory = new File(".");
String sourceFile;
String sourceFile1;
sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"case.txt";
sourceFile1 = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator;
// List<String> commands = new ArrayList<>();
// commands.add("cmd.exe");
// commands.add("cd C:\\Program Files (x86)\\PICT");
// commands.add("pict "+sourceFile+">"+sourceFile+"caseOut.txt");
// commands.add("\r\n");
// ProcessBuilder pb =new ProcessBuilder(commands);
//可以修改进程环境变量
// pb.environment().put("DAXIN_HOME", "/home/daxin");
// System.out.println(pb.directory());
String cmd = "pict "+sourceFile+">"+sourceFile1+"caseOut.txt";
String cmd2 = "cmd /c start " + "\"\" " + cmd ;
System.out.println(cmd2);
// String []cmd1 = {"cd" , " C:\\Program Files (x86)\\PICT ","pict","case.txt>caseOut.txt"};
Process process = Runtime.getRuntime().exec(cmd2);
process.waitFor();
process.exitValue();
// System.out.println(pb.environment());
//
// System.out.println(status);
// InputStream in = process.getInputStream();
//
// BufferedReader br = new BufferedReader(new InputStreamReader(in));
// String line = br.readLine();
// while(line!=null) {
// System.out.println(line);
// line = br.readLine();
// }
//
}
}
package com.offcn.TestUnti;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.offcn.listener.SkipIInvokedMethodListener;
public class fileUntil {
public static void main(String[] args) {
try {
readFile_("caseOut.txt");
// WriterFile("12345");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String readFile_(String filename)throws IOException{
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+filename;
FileInputStream fis = new FileInputStream(sourceFile);
byte[] buf = new byte[1024];
int len = 0;
StringBuffer sb=new StringBuffer();
while((len=fis.read(buf))!=-1){
sb.append(new String(buf,0,len));
// System.out.println(new String(buf,0,len));
}
fis.close();
return sb.toString();
}
public boolean WriterFile(List<Set<String>> listt){
File directory = new File(".");
String sourceFile;
try {
sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"case.txt";
BufferedWriter bw=new BufferedWriter(new FileWriter(sourceFile));
String cases="";
for(int i=0;i<listt.size();i++){
Object[] obj=listt.get(i).toArray();
cases=Arrays.toString(obj).trim();
cases=cases.substring(1, cases.length()-1);
bw.write(cases);
bw.newLine();
}
bw.flush();
bw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static boolean WriterFile_map(Integer Percentage){
File directory = new File(".");
String sourceFile;
try {
sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"map.txt";
BufferedWriter bw=new BufferedWriter((new OutputStreamWriter(new FileOutputStream(sourceFile),"utf-8")));
String cases="";
SkipIInvokedMethodListener.serviceUrlMap=(HashMap<String,Integer>)MapUtil.sortByValueDescending(SkipIInvokedMethodListener.serviceUrlMap);
Set<String> keySet = SkipIInvokedMethodListener.serviceUrlMap.keySet();
//有了Set集合。就可以获取其迭代器。
Iterator<String> it = keySet.iterator();
boolean sm=true;
while(it.hasNext()){
String key = it.next();
if(sm){
cases="<font size='4' color='#FF0000'>流程错误列表</font><table border='1'><th>URL</th><th>错误次数</th>";
bw.write(cases);
bw.newLine();
sm=false;
}
//有了键可以通过map集合的get方法获取其对应的值。
Integer value = SkipIInvokedMethodListener.serviceUrlMap.get(key);
cases="<tr><td>"+key+"</td><td>错误了"+value+"次。</td></tr>";
bw.write(cases);
bw.newLine();
}
if(!sm){
cases="</table>";
bw.write(cases);
bw.newLine();
}
boolean asd=true;
Set<String> keySet1 = SkipIInvokedMethodListener.SkipMap.keySet();
//有了Set集合。就可以获取其迭代器。
Iterator<String> it1 = keySet1.iterator();
while(it1.hasNext()){
String key1 = it1.next();
//有了键可以通过map集合的get方法获取其对应的值。
String value1 = SkipIInvokedMethodListener.SkipMap.get(key1);
String[] valuearr=value1.split("____");
double v1=Double.valueOf(valuearr[0]);
value1=valuearr[1];
if(v1>Percentage){
if(asd){
cases="<font size='4' color='#FF0000'>场景错误列表</font><table border='1'><th>包含错误的场景名称</th><th>场景包含错误案例数量</th><th>错误占比</th>";
bw.write(cases);
bw.newLine();
asd=false;
}
cases="<tr><td><font size='3' color='#0000CD'>"+key1+"</font></td>"
+ "<td><font size='3' color='#0000CD'>"+value1+"</font></td>"
+ "<td><font size='3' color='#0000CD'>"+v1+"%</font></td></tr>";
bw.write(cases);
bw.newLine();
}
}
if(!asd){
cases="</table>";
bw.write(cases);
bw.newLine();
}
bw.flush();
bw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* BufferedReader bufr = new BufferedReader(fr);
String line = null;
while((line=bufr.readLine())!=null)
{
System.out.print(line);
}
bufr.close();
*/
public static String readFile_line(String filename)throws IOException{
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+filename;
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile),"utf-8"));
BufferedReader bufr = new BufferedReader(in);
String line = null;
StringBuffer sb=new StringBuffer();
while((line=bufr.readLine())!=null)
{
sb.append(line);
}
bufr.close();
in.close();
return sb.toString();
}
}
......@@ -2,13 +2,16 @@ package com.offcn.api.tk.app;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.RequestDataUtils;
......@@ -16,6 +19,7 @@ import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.TK;
import com.offcn.TestUnti.ListUtil;
import net.sf.json.JSONObject;
......@@ -104,38 +108,38 @@ public class checkUserPhoneIfExist extends TK implements API {
}
}
if("接口响应成功".equals(msg)){
if("该账号不存在".equals(msg)){
String if_exist=jp.getString("data.if_exist");
//是否验证数据库
if (!isProduct) {
try {
ResultSet rs_bankcard = this.selectFromDB(
" t_user u ",
" u.phone = '" + phone + "' ");
rs_bankcard.last();
String act_phone=rs_bankcard.getString("phone");
if("1".equals(if_exist)){//if_exist=1时代表改手机号已存在
if (!phone.equals(act_phone)) {
result = result && false;
failReason = failReason + "t_user info is not in DB;";
}
}else{
if (phone.equals(act_phone)) {
result = result && false;
failReason = failReason + "t_user info is in DB;";
}
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify t_user info in DB;";
e.printStackTrace();
}
}
// if (!isProduct) {
//
// try {
// ResultSet rs_bankcard = this.selectFromDB(
// " t_user u ",
// " u.phone = '" + phone + "' ");
// rs_bankcard.last();
//
// String act_phone=rs_bankcard.getString("phone");
//
//
// if("1".equals(if_exist)){//if_exist=1时代表改手机号已存在
// if (!phone.equals(act_phone)) {
// result = result && false;
// failReason = failReason + "t_user info is not in DB;";
// }
// }else{
// if (phone.equals(act_phone)) {
// result = result && false;
// failReason = failReason + "t_user info is in DB;";
// }
// }
// } catch (Exception e) {
// result = result && false;
// failReason = failReason + "cannot verify t_user info in DB;";
// e.printStackTrace();
// }
// }
}
......
......@@ -187,7 +187,6 @@ public class register extends TK implements API {
// String act_passwd=rs_bankcard.getString("passwd").equals("")?"null":rs_bankcard.getString("passwd");
String act_passwd=rs_bankcard.getString("passwd");
// System.out.println((dataPhone.equals(act_phone)));
// System.out.println((dataPhone.equals(phone)));
......
package com.offcn.listener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.fileUntil;
public class MyTestListener implements ITestListener{
public static Integer SkippedCount=0;
@Override
public void onFinish(ITestContext TestContext) {
String Percentage=ReadProperties.GetTestPropertyByKey("Percentage");
Integer Percentage_Integer=Integer.valueOf(Percentage);
fileUntil.WriterFile_map(Percentage_Integer);
}
@Override
public void onStart(ITestContext arg0) {
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
}
@Override
public void onTestFailure(ITestResult arg0) {
}
@Override
public void onTestSkipped(ITestResult arg0) {
}
@Override
public void onTestStart(ITestResult arg0) {
}
@Override
public void onTestSuccess(ITestResult arg0) {
}
}
......@@ -68,26 +68,27 @@ public class ProcessTestng implements IInvokedMethodListener {
}
//在parameter中查看,是否有(第二个参数)verifyCode的关键字,有的话返回他的字母值
public static String getParameter(String parameter,String Letter){
if(parameter==null){
return "";
}
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String[] str=strcomma[k].split("=");
String str_strcomma=Arrays.toString(str);
public static String getParameter(String parameter,String Letter){
if(parameter==null){
return "";
}
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String[] str=strcomma[k].split("=");
String str_strcomma=Arrays.toString(str);
// System.out.println("str="+Arrays.toString(str));
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf(',');
sb.append(str_strcomma.substring(start+2,str_strcomma.length()-1));
return sb.toString();
}
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf(',');
sb.append(str_strcomma.substring(start+2,str_strcomma.length()-1));
return sb.toString();
}
return sb.toString();
}
return sb.toString();
}
}
package com.offcn.listener;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import org.testng.SkipException;
import com.offcn.TestData.offcn_api_testData;
import com.offcn.TestUnti.Log;
public class SkipIInvokedMethodListener implements IInvokedMethodListener{
//需求1,流程错误案例
public static String Parameter_TCNO="";//当前场景名称
public static String Parameter_ServiceUrl="";//错误的流程url
public static HashMap<String,Integer> serviceUrlMap= new HashMap<String,Integer>();
public static boolean Success=true;//场景测试的状态,发生错误false,未发生错误true
//需求2,模块错误案例占比,数量
public static Integer Parameter_TCNO_count=0;//存在错误的场景总数
public static Integer SkipTestnumber=0;//错误用例次数
public static HashMap<String,String> SkipMap= new HashMap<String,String>();//错误比例
//测试结果是成功还是失败还是跳过
public static Integer resultStatus=0;
//运行之前
@Override
public void beforeInvocation(IInvokedMethod Method, ITestResult result) {
//获取方法名称
String MethodName=Method.getTestMethod().getMethodName();
Object s[]=result.getParameters();
if(s.length==1){//当可以获取到用例的时候
String Step=getParameter(Arrays.toString(s),"Step");
String TCNO=getParameter(Arrays.toString(s),"TCNO");
String []Parameters=TCNO.split("_");
TCNO=Parameters[0];
//查看是否上一条是错误的(错误场景名称和当前场景名称一致),并且当前用例Step不等于1,都满足就跳过当前即将要运行的这条
int IntegerStep=Integer.parseInt(Step.trim());
if(IntegerStep!=1 && !Success && "f".equals(MethodName)){
Log.logInfo("跳过");
if(resultStatus!=3){
recordTases(Parameter_ServiceUrl);//流程错误案例保存上一条的信息和次数
}
throw new SkipException("skip the test");
}else if(IntegerStep==1 && TCNO.equals(Parameter_TCNO) && "f".equals(MethodName)){//遇到1,场景状态清除
Success=true;
}else if(IntegerStep==1 && !TCNO.equals(Parameter_TCNO) && "f".equals(MethodName) && Parameter_TCNO_count!=0){//计算该场景错误用例比例和该场景的错误案例数量
Success=true;
double TCNO_double=SkipTestnumber/(Parameter_TCNO_count*1.0);
TCNO_double=m1(TCNO_double*100);
SkipMap.put(Parameter_TCNO, TCNO_double+"____"+SkipTestnumber);
SkipTestnumber=0;
Parameter_TCNO="";
}
}
}
@Override
public void afterInvocation(IInvokedMethod Method, ITestResult result) {
try {
resultStatus=result.getStatus();
//获取方法名称
String MethodName=Method.getTestMethod().getMethodName();
Object s111[]=result.getParameters();
String NO=getParameter(Arrays.toString(s111),"NO");
if(s111.length==1){//当可以获取到用例的时候
if(!result.isSuccess() && "f".equals(MethodName)){
SkipTestnumber++;
Success=false;//记录本条用例错误,在下条用例前调用查看
//只要有错误就记录,用例名称、url、步骤数
Object s[]=result.getParameters();
Parameter_ServiceUrl=getParameter(Arrays.toString(s),"serviceUrl");
// recordTases(Parameter_ServiceUrl);
String TCNO=getParameter(Arrays.toString(s),"TCNO");
String []Parameters=TCNO.split("_");
Parameter_TCNO=Parameters[0];
Parameter_TCNO_count=Integer.valueOf(Parameters[1]);
}
if(offcn_api_testData.Testcount==Integer.valueOf(NO) && !Success){
Success=true;
double TCNO_double=SkipTestnumber/(Parameter_TCNO_count*1.0);
TCNO_double=m1(TCNO_double*100);
SkipMap.put(Parameter_TCNO, TCNO_double+"____"+SkipTestnumber);
SkipTestnumber=0;
Parameter_TCNO="";
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//记录测试过程中流程用例的错误数量
public static void recordTases(String serviceUrlName){
Integer value = serviceUrlMap.get(serviceUrlName);
int count=1;
if(value==null){
serviceUrlMap.put(serviceUrlName, count);
}else{
serviceUrlMap.put(serviceUrlName, ++value);
}
}
//在parameter中查看,是否有(第二个参数)verifyCode的关键字,有的话返回他的字母值
public static String getParameter(String parameter,String Letter){
if(parameter==null){
return "";
}
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String[] str=strcomma[k].split("=");
String str_strcomma=Arrays.toString(str);
// System.out.println("str="+Arrays.toString(str));
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf(',');
sb.append(str_strcomma.substring(start+2,str_strcomma.length()-1));
return sb.toString();
}
}
return sb.toString();
}
public double m1(double f ) {
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
return f1;
}
}
......@@ -2,6 +2,7 @@ package com.offcn.process;
import io.restassured.response.Response;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
......@@ -11,6 +12,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
......@@ -18,38 +20,140 @@ import java.util.Map.Entry;
import java.util.Set;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MYSQLConnection;
import com.offcn.TestUnti.XMLread;
import com.offcn.system.sql;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public abstract class BasicsGM {
// //数据提取
// public static HashMap<String, Object> data_ext=new HashMap<String, Object>();
//
// //用户验证码<电话号码,验证码>
// public static HashMap<String, String> verifyCode=new HashMap<String, String>();
//
// public static List<String> cust_ids = new ArrayList<String>();//客户表id,
//
// public static List<String> contractId_dd = new ArrayList<String>();//任买合同id,
//
// public static List<String> prod_ids = new ArrayList<String>();//商品信息表id
//
// public static List<String> order_ids = new ArrayList<String>();//订单表id
//
// public static HashMap<String, String> thirdBusi = new HashMap<String, String>();//子商户表id
//
// public static List<String> rulesEngine_ids = new ArrayList<String>();//决策引擎customer表 id
//
public class BasicsGM {
public static Connection conn = null;
public static Statement stmt = null;
//
public static ResultSet rs=null;
public static Map<String,Object> map=new XMLread().getSystem();// 读取XML配置文件
//
// public static boolean isProduct = false;
//
public static Map<String,Connection> ConnectionsMap=new HashMap<String, Connection>();//数据库连接池
public static Map<String,Statement> StatementsMap=new HashMap<String, Statement>();//数据库连接池
public static HashMap<String,String> PublicParameter = new HashMap<String,String>();//静态公共参数
public static HashMap<String,String> DynamicParameter = new HashMap<String,String>();//动态公共参数
public static HashMap<Class<?>,Object> Delsql = new HashMap<Class<?>,Object>();//数据库信息源
public static Set<String> Delsqlset = new HashSet<String>();//数据库信息源
public static void setDelSystemSql(Class<?> c,Object object){
String SystemName=c.getSuperclass().getSimpleName();
int count=Delsqlset.size();
Delsqlset.add(SystemName);
if(Delsqlset.size()>count){
Delsql.put(c, object);
}
}
//setDynamicParameter动态代理
@SuppressWarnings("unchecked")
public HashMap<String, Object> setDynamicParameter(Class<?> c,Object object,HashMap<String, Object> data) {
try {
Class<?> printClass = c;
Method printMethod;
printMethod = printClass.getMethod("setDynamicParameter",HashMap.class);
return (HashMap<String, Object>) printMethod.invoke(object,data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//setPublicParameter动态代理
@SuppressWarnings("unchecked")
public HashMap<String, Object> setPublicParameter(Class<?> c,Object object,HashMap<String, Object> data) {
try {
Class<?> printClass = c;
Method printMethod;
printMethod = printClass.getMethod("setPublicParameter",HashMap.class);
return (HashMap<String, Object>) printMethod.invoke(object,data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//清除数据库的方法
public void cleanMysqlData(Class<?> c,Object obj){
try {
Class<?> printClass = c;
Method printMethod;
printMethod = printClass.getMethod("cleanMysqlData");
printMethod.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
}
};
//建立数据库连接池Connection对象集合
public Map<String,Connection> getConnections(String[] arr){
XMLread xml=new XMLread();
Map<String,Object> map=(Map<String, Object>) xml.getDatabaseSql();
for(int i=0;i<arr.length;i++){
String a=arr[i];
sql sys=(sql) map.get(a);
if(ConnectionsMap.get(arr[i])==null){
Connection Connection2=MYSQLConnection.coontSql(sys.getSqlurl(), sys.getSqlname(), sys.getSqlpwd());
ConnectionsMap.put(arr[i], Connection2);
}
}
return ConnectionsMap;
}
//建立数据库连接池Statements对象集合
public Map<String,Statement> getStatements(Map<String,Connection> Map){
Set<String> keySet = Map.keySet();
//有了Set集合。就可以获取其迭代器。
Iterator<String> it = keySet.iterator();
while(it.hasNext()){
String key = it.next();
//有了键可以通过map集合的get方法获取其对应的值。
Connection value = Map.get(key);
// System.out.println("key:"+key+",value:"+value);
Statement statement=MYSQLConnection.stmtSql(value);
StatementsMap.put(key, statement);
}
return StatementsMap;
}
//断开数据库连接
public void CloseMysql(){
try {
if(rs!=null){
rs.close();
}
} catch (Exception e2) {
Log.logError("关闭结果集失败");
}
try {
Set<String> keySet = ConnectionsMap.keySet();
//有了Set集合。就可以获取其迭代器。
Iterator<String> it = keySet.iterator();
while(it.hasNext()){
String key = it.next();
//有了键可以通过map集合的get方法获取其对应的值。
Log.logInfo("断开连接:"+key);
if(StatementsMap.get(key)!=null){
StatementsMap.get(key).close();
}
if (ConnectionsMap.get(key) != null){
ConnectionsMap.get(key).close();
}
}
} catch (SQLException e) {
Log.logError("断开连接失败");
e.printStackTrace();
}
}
//更改huimai.bestbuy_order表,条件是id=orderId,值该为orderStatus
public static Integer updateOrderStatus(String fromName,String setCondition, String whereCondition) {
Integer result=null;
......@@ -67,25 +171,25 @@ public abstract class BasicsGM {
}
return result;
}
//查询表名tableName的条件是condition的结果集
public ResultSet selectFromDB(String tableName, String condition) throws Exception {
String sql;
ResultSet rs = null;
sql = " select * from " + tableName + " where " + condition;
// System.out.println(sql);
// System.out.println(sql);
rs = stmt.executeQuery(sql);
return rs;
}
//查询表名tableName的条件是condition的结果集
public ResultSet sqlFromDB(String sql) throws Exception {
ResultSet rs = stmt.executeQuery(sql);
return rs;
//查询表名tableName的条件是condition的结果集
public ResultSet sqlFromDB(String sql) throws Exception {
ResultSet rs = stmt.executeQuery(sql);
return rs;
}
}
//查询表名tableName的条件是condition的结果集,返回数量
public ResultSet selectCountFromDB(String tableName, String condition) throws Exception {
String sql;
......@@ -96,7 +200,7 @@ public abstract class BasicsGM {
return rs;
}
//具体的删除动作,tableName=表名,key列,value值使用的like删除
public void deleteFromDB(String tableName, String key, String value) throws Exception {
String sql = "delete from " + tableName + " where " + key + " like '" + value + "'";
......@@ -106,278 +210,8 @@ public abstract class BasicsGM {
if (result == -1) {
Log.logError("Clean failed!");
}
}
// 如果cust_ids集合有值,则循环删除map_table集合内,表名=KEY,列名=value,值=cust_ids得遍历结果
public void cleanCustomerInfo() {
HashMap<String, String> map_table = new HashMap<String, String>();
//用户验证所需的表格
map_table.put("bestbuy_third_user", "cust_id");//任买外接第三方用户表
map_table.put("bestbuy_customer", "id");//用户表
//工作族基本信息
map_table.put("bestbuy_doc", "rela_id");//用户身份证照片
map_table.put("bestbuy_customer_info", "customer_id");//用户信息表
map_table.put("bestbuy_bankcard", "customer_id");//银行卡信息表
map_table.put("bestbuy_customer_book", "customer_id");//用户电话簿信息表
map_table.put("bestbuy_customer_licensesinfo", "customer_id");//用户第三方授权信息表
map_table.put("bestbuy_module_auth", "cust_id");//用户授权表
map_table.put("bestbuy_audit_record", "cust_id");//人工信审工单处理记录表
/*
map_table.put("bestbuy_customer_auth", "customer_id");//用户授权表 ---APP端
map_table.put("bestbuy_bank_record", "customer_id");//绑卡记录表
*/
map_table.put("bestbuy_customer_com", "customer_id");//客户公司信息表
map_table.put("bestbuy_customer_location", "customer_id");//客户地址信息
map_table.put("bestbuy_relationship", "customer_id");//用户关系表
map_table.put("bestbuy_order", "customer_id");//订单表
//合同表bestbuy_contract,暂时不清除,因为需要orderid,并且合同表关联到保理业务。。
// Iterator<String> it_cust = cust_ids.iterator();//客户表id
//
// while (it_cust.hasNext()) {
// Iterator<Entry<String, String>> it_table = map_table.entrySet().iterator();
// String cust = it_cust.next();
// while (it_table.hasNext()) {
// Map.Entry<String, String> entry = (Map.Entry<String, String>) it_table.next();
// try {
// this.deleteFromDB(entry.getKey(), entry.getValue(), cust);
// } catch (Exception e) {
// System.out.println("Fail to clean customer info!");
// }
// }
// }
// cust_ids.clear();
}
//
// //按照customer_id删除决策引擎中用户的数据-预授信模式
// public void cleanStreamingCustomerInfo(String customer_id) {
// HashMap<String, String> map_table = new HashMap<String, String>();
// map_table.put("streaming.customer", "id");//决策引擎用户表
// map_table.put("streaming.customer_info", "customer_id");//决策引擎用户表
// map_table.put("streaming.customer_data_info", "customer_id");//决策引擎用户数据表
// map_table.put("streaming.customer_limit_account_log", "customer_id");//用户身份证照片
// map_table.put("streaming.customer_limit_account", "customer_id");//客户额度账户表
// map_table.put("streaming.customer_merchant_info", "customer_id");//商户信息表
//
// Iterator<Entry<String, String>> it_table = map_table.entrySet().iterator();
// while (it_table.hasNext()) {
// Map.Entry<String, String> entry = (Map.Entry<String, String>) it_table.next();
// try {
// this.deleteFromDB(entry.getKey(), entry.getValue(), customer_id);
// } catch (Exception e) {
// System.out.println("Fail to clean customer info!");
// }
// }
// }
//
// //按照streaming_process_info_id删除决策引擎中用户的数据-订单模式
// public void cleanStreamingOrder(String id) {
// HashMap<String, String> map_table = new HashMap<String, String>();
// map_table.put("streaming.third_ylzc_advanced_data", "id");//决策引擎用户表
// map_table.put("streaming.third_ylzc_base_data", "id");//决策引擎用户数据表
// map_table.put("streaming.third_ylzc_basic_data_past_all_month", "id");//用户身份证照片
// map_table.put("streaming.third_ylzc_basic_data_recent_1_3_month", "id");//客户额度账户表
// map_table.put("streaming.third_ylzc_basic_data_recent_12_month", "id");//商户信息表
// map_table.put("streaming.third_ylzc_basic_data_recent_6_month", "id");//商户信息表
// map_table.put("streaming.third_ylzc_classical_data", "id");//商户信息表
// map_table.put("streaming.third_ylzc_customized_data", "id");//商户信息表
// map_table.put("streaming.streaming_customer_licensesinfo", "work_id");//用户授权信息表
// map_table.put("streaming.streaming_process_info", "id");//流程信息
//
// Iterator<Entry<String, String>> it_table = map_table.entrySet().iterator();
// while (it_table.hasNext()) {
// Map.Entry<String, String> entry = (Map.Entry<String, String>) it_table.next();
// try {
// this.deleteFromDB(entry.getKey(), entry.getValue(), id);
// } catch (Exception e) {
// System.out.println("Fail to clean customer info!");
// }
// }
// }
//
//
//
//
//
//
// //清除list集合prod_ids,表名"bestbuy_goods",列名id,值prod_ids得遍历结果
//
//
// public void cleanProductsFromDB() {
// Iterator<String> it_prod = prod_ids.iterator();
//
// while (it_prod.hasNext()) {
// try {
// this.deleteFromDB("bestbuy_goods", "id", it_prod.next());
// } catch (Exception e) {
// System.out.println("Fail to clean product info!");
// }
//
// }
// prod_ids.clear();
//
// }
//
// //清除list集合order_ids,表名"bestbuy_order",列名id,值order_ids得遍历结果
//
// public void cleanOrdersFromDB() {
// Iterator<String> it_order = order_ids.iterator();
//
// while (it_order.hasNext()) {
// try {
// this.deleteFromDB("bestbuy_order", "id", it_order.next());
// } catch (Exception e) {
// System.out.println("Fail to clean order info!");
// }
//
// }
// order_ids.clear();
//
// }
//
// //清除list集合order_ids,表名"bestbuy_order",列名id,值order_ids得遍历结果
//
// public void cleanRulesEngine_idsFromDB() {
// Iterator<String> it_rulesEngine = rulesEngine_ids.iterator();
//
// Statement stmt_RulesEngine =null;
//
// while (it_rulesEngine.hasNext()) {
// try {
// stmt_RulesEngine = conn.createStatement();
// String sql = "delete from " + "streaming.customer" + " where " + "id_no" + " like '" + it_rulesEngine.next() + "'";
// System.out.println("sql==="+sql);
// int result = stmt_RulesEngine.executeUpdate(sql);
// System.out.println("result==="+result);
// if (result == -1) {
// System.out.println("Clean failed!");
// }
// } catch (Exception e) {
// System.out.println("Fail to clean order info!");
// }finally{
// if (stmt_RulesEngine != null){
// try {
// stmt_RulesEngine.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
// rulesEngine_ids.clear();
//
// }
//
//
// //从thirdBusi这个map集合中,往huimai.bestbuy_sub_busi这个表添加信息
//
// public void addTestThirdBusiInfoFromDB() {
// Statement stmt;
// try {
// stmt = conn.createStatement();
//
// String sql = "insert into huimai.bestbuy_sub_busi (busi_id,sub_busi_name,busi_id_third,create_time) "
// + "values('999','" + thirdBusi.get("busiName") + "','" + thirdBusi.get("busiId") + "', NOW())";
// // System.out.println(sql);
// int result = stmt.executeUpdate(sql);//
// if (result == -1) {
// System.out.println("Insert failed!");
// }
// } catch (SQLException e) {
// System.out.println("Insert failed!");
// }
//
// }
//
// //从thirdBusi这个map集合中,在huimai.bestbuy_sub_busi这个表删除信息
//
// public void cleanTestThirdBusiInfoFromDB() {
// Statement stmt;
// try {
// stmt = conn.createStatement();
//
// String sql = "delete from huimai.bestbuy_sub_busi where " + "sub_busi_name ='"
// + thirdBusi.get("busiName") + "' and busi_id_third='" + thirdBusi.get("busiId") + "'";
// // System.out.println(sql);
// int result = stmt.executeUpdate(sql);//
// if (result == -1) {
// System.out.println("clean busi info failed!");
// }
// } catch (SQLException e) {
// System.out.println("clean busi info failed!");
// }
//
// }
//
//
// //更改
//
// public void updateTableValueWithCondition(String table, String setStatement, String whereStatement) {
// Statement stmt;
// try {
// stmt = conn.createStatement();
//
// String sql = "update "+table+" set "+setStatement+" where "+whereStatement;
//// System.out.println(sql);
// int result = stmt.executeUpdate(sql);//
// if (result == -1) {
// System.out.println("update table value failed!");
// }
// } catch (SQLException e) {
// System.out.println("update table value failed!");
// }
// }
//
//
// // 字符串转换成时间类型
//
// public Date convertStrToDate(String dateStr) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// Date date = null;
// try {
// date = sdf.parse(dateStr);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return date;
//
// }
//
// //时间转换成字符串类型
// public String convertDateToStr(Date date) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// String dateStr = null;
// try {
// dateStr = sdf.format(date);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return dateStr;
//
// }
//
// public String getContractId(){
// for(int i=0;i<contractId_dd.size();i++){
// if(contractId_dd.get(i)!=null){
// return contractId_dd.get(i);
// }
// }
// return null;
// }
//
//判断字符串是否是空或者是“”
public boolean StringIsNull(String str){
if(str==null || "".equals(str)){
......
......@@ -46,45 +46,93 @@ public class NWN extends BasicsGM{
public static String level_id_List = "";//层级的id
public static List<String> user_id_List = new ArrayList<String>();//user_id
// public static String phone_code = "";//手机号验证码
//
//
// public static List<String> t_exam_area = new ArrayList<String>();//t_exam_area_id
//
// public static String union_id_str = "" ;//t_user表union_id
// public static String open_id_str = "";//t_user表open_id
//
// public static String tk_token="";//登录token
public void Connectionsa(){
//================设置数据库连接池=====================
ConnectionsMap=getConnections(new String[]{"nwn"});
StatementsMap=getStatements(ConnectionsMap);
conn=ConnectionsMap.get("nwn");//设置默认的连接对象
stmt=StatementsMap.get("nwn");//设置默认的连接对象
//================设置公共参数========================
// PublicParameter.put("appid","tiku");//静态公共参数
// DynamicParameter.put("sign","code");//动态公共参数
}
static{
String mysql_local_Online=ReadProperties.GetTestPropertyByKey("mysql_local_Online");
//本地数据库连接
if(mysql_local_Online.equals("local")){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(((system)map.get("nwn")).getSqlurl(),
((system)map.get("nwn")).getSqlname(),
((system)map.get("nwn")).getSqlpwd());
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
public NWN(){
Connectionsa();
}
//动态公共参数
public HashMap<String, Object> setDynamicParameter(HashMap<String, Object> data) {
String parameter =null;
HashMap<String, Object> dataNew=data;
if(DynamicParameter.size()!=0){
parameter = MapUtil.getValue("parameter", data);
String Request = MapUtil.getValue("Request", data);
Set<Map.Entry<String,String>> entrySet = DynamicParameter.entrySet();
Iterator<Map.Entry<String,String>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
// Log.logInfo("公共动态参数:"+key+":"+value);
if(!parameter.contains("\""+key+"\"") && !parameter.contains(key+"=")){
if("get".equals(Request)){
if(parameter==null || parameter.length()==0){
parameter=key+"="+"ppp";
}else{
parameter=parameter+"&"+key+"="+"ppp";
}
}else{
if(parameter==null || parameter.length()==0){
parameter=key+"\":\""+"ppp"+"\"";
}else{
parameter=parameter+",\""+key+"\":\""+"ppp"+"\"";
}
}
}
}
dataNew.put("parameter", parameter);
}
return dataNew;
}
if(mysql_local_Online.equals("Online")){
//线上数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(((system)map.get("nwnxs")).getSqlurl(),
((system)map.get("nwnxs")).getSqlname(),
((system)map.get("nwnxs")).getSqlpwd());
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
public HashMap<String, Object> setPublicParameter(HashMap<String, Object> data) {
String parameter =null;
HashMap<String, Object> dataNew=data;
if(PublicParameter.size()!=0){
parameter = MapUtil.getValue("parameter", data);
String Request = MapUtil.getValue("Request", data);
Set<Map.Entry<String,String>> entrySet = PublicParameter.entrySet();
Iterator<Map.Entry<String,String>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
// Log.logInfo("公共静态参数:"+key+":"+value);
if(!parameter.contains("\""+key+"\"") && !parameter.contains(key+"=")){
if("get".equals(Request)){
if(parameter==null || parameter.length()==0){
parameter=key+"="+value;
}else{
parameter=parameter+"&"+key+"="+value;
}
}else{
if(parameter==null || parameter.length()==0){
parameter=key+"\":\""+value+"\"";
}else{
parameter=parameter+",\""+key+"\":\""+value+"\"";
}
}
}
}
dataNew.put("parameter", parameter);
}
return dataNew;
}
}
//清除注册数据根据n_admin_card_no_List
public void cleann_n_admin_card_no_List_FromDB() {
List<String> user_List = new ArrayList<String>();
......@@ -135,6 +183,18 @@ public class NWN extends BasicsGM{
user_id_List.removeAll(user_List);
// System.out.println(user_idList.toString());
}
public void cleanMysqlData() {
if (!isClearMysql) {
System.out.println("nwn=====cleanMysqlData");
conn=ConnectionsMap.get("nwn");//设置默认的连接对象
stmt=StatementsMap.get("nwn");//设置默认的连接对象
cleann_n_admin_card_no_List_FromDB();//清除注册数据根据n_admin_card_no_List
cleann_n_package_List_FromDB();//清除注册user_id,
cleann_user_id_List_FromDB();//清除用户地区操作表t_exam_area
}
}
//
......
......@@ -18,6 +18,7 @@ import java.util.Set;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MD5keyUtil;
import com.offcn.TestUnti.MYSQLConnection;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.cmdUtil;
......@@ -27,73 +28,115 @@ import com.offcn.system.system;
public class TK extends BasicsGM{
public static boolean isClearMysql =false;
public static boolean isProduct=Boolean.valueOf(((system)map.get("tk")).getIsProduct());
// public static HashMap<String, Object> phoneMap=new HashMap<String, Object>();//
public static String phoneNeb = "";//手机号
public static String phone_code = "";//手机号验证码
public static List<String> user_idList = new ArrayList<String>();//user_id
public static List<String> t_exam_area = new ArrayList<String>();//t_exam_area_id
public static String union_id_str = "" ;//t_user表union_id
public static String open_id_str = "";//t_user表open_id
public static String tk_token="";//登录token
public static String practice_id_L="";//21接口提供,练习册id
public static String cate_id_L="";//21接口提供,练习册里面的小类别
public static String paper_id_L="";//27.getExamPaperList 返回试卷id 27、88接口提供
public static String record_id_L="";//28.getpaperBlocks 返回做题记录id 28、47、88接口提供
public static String examine_paper_id_L="";//88接口提供
public static String examine_id_L="";//88接口提供
public static String image_id_L="";//100接口提供
public static String question_id_L="";//试题id
public static String question_id_list="";//试题id集合,47接口提供
public static String item_id_L="";//考试项目的id
public static String question_number_L="";//47练习册提交做准备
public static String is_hf_L="";//47
public static String type_L="";//47
public static String recordId_L="";//110申论,使用记录id 提交做题记录时需要用到
static{
String mysql_local_Online=ReadProperties.GetTestPropertyByKey("mysql_local_Online");
//本地数据库连接
if(mysql_local_Online.equals("local")){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(((system)map.get("tk")).getSqlurl(),
((system)map.get("tk")).getSqlname(),
((system)map.get("tk")).getSqlpwd());
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
public void Connectionsa(){
//================设置数据库连接池=====================
ConnectionsMap=getConnections(new String[]{"tk","xyzb"});
StatementsMap=getStatements(ConnectionsMap);
conn=ConnectionsMap.get("tk");//设置默认的连接对象
stmt=StatementsMap.get("tk");//设置默认的连接对象
//================设置公共参数========================
PublicParameter.put("appid","tiku");//静态公共参数
DynamicParameter.put("sign","code");//动态公共参数
}
public TK(){
Connectionsa();
}
//动态公共参数
public HashMap<String, Object> setDynamicParameter(HashMap<String, Object> data) {
String parameter =null;
HashMap<String, Object> dataNew=data;
if(DynamicParameter.size()!=0){
parameter = MapUtil.getValue("parameter", data);
String Request = MapUtil.getValue("Request", data);
Set<Map.Entry<String,String>> entrySet = DynamicParameter.entrySet();
Iterator<Map.Entry<String,String>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
// Log.logInfo("公共动态参数:"+key+":"+value);
if(!parameter.contains("\""+key+"\"") && !parameter.contains(key+"=")){
if("get".equals(Request)){
if(parameter==null || parameter.length()==0){
parameter=key+"="+GetSignValue(parameter);
}else{
parameter=parameter+"&"+key+"="+GetSignValue(parameter);
}
}else{
if(parameter==null || parameter.length()==0){
parameter=key+"\":\""+GetSignValue(parameter)+"\"";
}else{
parameter=parameter+",\""+key+"\":\""+GetSignValue(parameter)+"\"";
}
}
}
}
dataNew.put("parameter", parameter);
}
if(mysql_local_Online.equals("Online")){
//线上数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(((system)map.get("tkxs")).getSqlurl(),
((system)map.get("tkxs")).getSqlname(),
((system)map.get("tkxs")).getSqlpwd());
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
return dataNew;
}
public HashMap<String, Object> setPublicParameter(HashMap<String, Object> data) {
String parameter =null;
HashMap<String, Object> dataNew=data;
if(PublicParameter.size()!=0){
parameter = MapUtil.getValue("parameter", data);
String Request = MapUtil.getValue("Request", data);
Set<Map.Entry<String,String>> entrySet = PublicParameter.entrySet();
Iterator<Map.Entry<String,String>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
// Log.logInfo("公共静态参数:"+key+":"+value);
if(!parameter.contains("\""+key+"\"") && !parameter.contains(key+"=")){
if("get".equals(Request)){
if(parameter==null || parameter.length()==0){
parameter=key+"="+value;
}else{
parameter=parameter+"&"+key+"="+value;
}
}else{
if(parameter==null || parameter.length()==0){
parameter=key+"\":\""+value+"\"";
}else{
parameter=parameter+",\""+key+"\":\""+value+"\"";
}
}
}
}
dataNew.put("parameter", parameter);
}
return dataNew;
}
//验签值
public static String GetSign(String parameter){
parameter=parameter+",\"sign\":\""+GetSignValue(parameter)+"\"";
......@@ -113,7 +156,15 @@ public class TK extends BasicsGM{
return MD5keyUtil.getMD5Str(parameter);
}
public void cleanMysqlData() {
if (!isClearMysql) {
System.out.println("tk=====cleanMysqlData");
conn=ConnectionsMap.get("tk");//设置默认的连接对象
stmt=StatementsMap.get("tk");//设置默认的连接对象
cleanUser_FromDB();//清除注册user_id,
cleanexam_FromDB();//清除用户地区操作表t_exam_area
}
}
//清除注册数据根据user_idList
public void cleanUser_FromDB() {
......@@ -129,7 +180,7 @@ public class TK extends BasicsGM{
}
user_idList.removeAll(user_List);
// System.out.println(user_idList.toString());
// System.out.println(user_idList.toString());
}
......@@ -147,6 +198,7 @@ public class TK extends BasicsGM{
}
t_exam_area.removeAll(user_List);
// System.out.println(user_idList.toString());
// System.out.println(user_idList.toString());
}
}
......@@ -186,4 +186,9 @@ public class XYZB extends BasicsGM{
e.printStackTrace();
}
}
public void cleanMysqlData() {
// TODO Auto-generated method stub
}
}
package com.offcn.system;
/**
* 测试报告邮件中的流程错误对象
* @author ibm
*
*/
public class FlowBean {
private String testTCNO;
private String testName;
private String testUrl;
private String errorCount;
public String getTestTCNO() {
return testTCNO;
}
public void setTestTCNO(String testTCNO) {
this.testTCNO = testTCNO;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestUrl() {
return testUrl;
}
public void setTestUrl(String testUrl) {
this.testUrl = testUrl;
}
public String getErrorCount() {
return errorCount;
}
public void setErrorCount(String errorCount) {
this.errorCount = errorCount;
}
public FlowBean(String testTCNO, String testName, String testUrl,
String errorCount) {
super();
this.testTCNO = testTCNO;
this.testName = testName;
this.testUrl = testUrl;
this.errorCount = errorCount;
}
public FlowBean() {
super();
}
}
package com.offcn.system;
import java.util.Map;
public class MyRequest {
private String Request;
private String Url;
private Map<String, String> Cookies;
private Map<String,String> headers;
private String Parameter; //json请求方式的参数
private Map<String, String> formParameter;//form_data请求方式的参数、或file请求方式的参数
private String file;
public String getRequest() {
return Request;
}
public void setRequest(String request) {
Request = request;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
public Map<String, String> getCookies() {
return Cookies;
}
public void setCookies(Map<String, String> cookies) {
Cookies = cookies;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public String getParameter() {
return Parameter;
}
public void setParameter(String parameter) {
Parameter = parameter;
}
public Map<String, String> getFormParameter() {
return formParameter;
}
public void setFormParameter(Map<String, String> formParameter) {
this.formParameter = formParameter;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public MyRequest(String request, String url, Map<String, String> cookies,
Map<String, String> headers, String parameter,
Map<String, String> formParameter, String file) {
super();
Request = request;
Url = url;
Cookies = cookies;
this.headers = headers;
Parameter = parameter;
this.formParameter = formParameter;
this.file = file;
}
public MyRequest() {
}
}
package com.offcn.system;
public class sql {
private String sqlurl;
private String sqlname;
private String sqlpwd;
public String getSqlurl() {
return sqlurl;
}
public void setSqlurl(String sqlurl) {
this.sqlurl = sqlurl;
}
public String getSqlname() {
return sqlname;
}
public void setSqlname(String sqlname) {
this.sqlname = sqlname;
}
public String getSqlpwd() {
return sqlpwd;
}
public void setSqlpwd(String sqlpwd) {
this.sqlpwd = sqlpwd;
}
public sql(String sqlurl, String sqlname, String sqlpwd) {
super();
this.sqlurl = sqlurl;
this.sqlname = sqlname;
this.sqlpwd = sqlpwd;
}
public sql() {
}
}
package com.offcn.test;
import io.restassured.response.Response;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import com.offcn.TestData.offcn_api_testData;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.Mail;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.OAuthTokenUnti;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.Reflect_api;
import com.offcn.TestUnti.SheetUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.TestUnti.XMLread;
import com.offcn.interfaces.API;
import com.offcn.listener.ProcessTestng;
import com.offcn.listener.ResultTestng;
import com.offcn.process.BasicsGM;
import com.offcn.process.NWN;
import com.offcn.process.TK;
import com.offcn.process.XYZB;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners({ ProcessTestng.class ,ResultTestng.class })
public class APITest_nwn extends NWN{
@Test(dataProvider = "renmai", dataProviderClass = offcn_api_testData.class)
public void f(HashMap<String, Object> data) {
Log.logInfo(data.get("TCNO").toString() + " Step " + data.get("Description").toString() + " is running......");
API obj = new Reflect_api().Reflections(data);
BasicsGM.map=new XMLread().getSystem();
obj.initialize(data);
data = obj.handleInput(data);
String parameter = MapUtil.getValue("parameter", data);
Long startTime=System.currentTimeMillis();
Response re = obj.SendRequest(data, data.get("serviceUrl").toString(), data.get("Request").toString());
Long endTime=System.currentTimeMillis();
String time=(endTime-startTime)+"毫秒";
String codeORerrcode="";
String msgORerrmsy="";
String result = "";
String body = "";
if(re!=null){
body=re.asString();
if(body.contains("<title>")){
int Alength="<title>".length();
int start=body.indexOf("<title>");
int end=body.indexOf("</title>")+1;
body="页面标题:"+body.substring(start+Alength, end-1);
result=body;
if(data.get("Description").toString().contains("流程")){
result = obj.handleOutput(re, data);
}
}else if(body.contains("<html>")){
body="返回html页面,状态码:"+re.getStatusCode();
}else{
result = obj.handleOutput(re, data);
}
codeORerrcode=getCode(re);
msgORerrmsy=getMsg(re);
}
Log.logInfo("返回结果="+StringUtils.decodeUnicode(body));
System.out.println();
//数据回写
// HashMap<String, Object> ExpectResult=MapUtil.Expect(data);
SheetUtils sheet = new SheetUtils("DataAll.xls", "Output");
sheet.writeExcel(
data.get("NO").toString(),
data.get("TCNO").toString() + "_Step" + data.get("Step").toString(),
data.get("Description").toString(),
parameter,
// JSONObject.fromObject(ExpectResult).toString(),
re.getStatusCode()+"",
// StringUtils.decodeUnicode(re==null?"":re.asString()),
StringUtils.decodeUnicode(body),
codeORerrcode,
msgORerrmsy,
result,
time
);
if(result.indexOf("Fail")!=-1){
String Expect1=data.get("code")==null?"":data.get("code").toString();
String Expect2=data.get("msg")==null?"":data.get("msg").toString();
String Expect3=data.get("custom")==null?"":data.get("custom").toString();
if(body.contains("HTML")){
body="异常页面信息";
}
Assert.assertEquals(StringUtils.decodeUnicode(body),Expect1+","+Expect2+","+Expect3);
}else{
Assert.assertTrue(true);
}
}
@AfterClass
public void afterClass() {
//测试结束删除测试所用的数据
if (!isClearMysql) {
this.cleann_n_admin_card_no_List_FromDB();
this.cleann_n_package_List_FromDB();
this.cleann_user_id_List_FromDB();
try {
if(stmt!=null){
stmt.close();
}
if (conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Log.logInfo("========测试结束========");
}
}
......@@ -4,69 +4,64 @@ import io.restassured.response.Response;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.json.JSONObject;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import com.offcn.TestData.offcn_api_testData;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.Mail;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.OAuthTokenUnti;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.Reflect_api;
import com.offcn.TestUnti.SheetUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.TestUnti.XMLread;
import com.offcn.interfaces.API;
import com.offcn.listener.ProcessTestng;
import com.offcn.listener.ResultTestng;
import com.offcn.listener.MyTestListener;
import com.offcn.listener.SkipIInvokedMethodListener;
import com.offcn.process.BasicsGM;
import com.offcn.process.TK;
import com.offcn.process.XYZB;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners({ ProcessTestng.class ,ResultTestng.class })
public class APITest_tk extends TK{
@Listeners({ SkipIInvokedMethodListener.class,MyTestListener.class})//
public class APITest_tk extends BasicsGM{
@Test(dataProvider = "renmai", dataProviderClass = offcn_api_testData.class)
public void f(HashMap<String, Object> data) {
Log.logInfo(data.get("serviceUrl").toString() + data.get("Description").toString() + " is running......");
API obj = new Reflect_api().Reflections(data);
Reflect_api Reflect=new Reflect_api();
Class<?> c=Reflect.ReflecClass(data);
Object object = Reflect.ReflecObj(c);
API obj = (API)object;
setDelSystemSql(c, object);//保存曾经操作过的系统
BasicsGM.map=new XMLread().getSystem();
obj.initialize(data);
data = obj.handleInput(data);
String parameter = MapUtil.getValue("parameter", data);
//tk验签
if(!data.get("Request").toString().contains("get") && data.get("system").toString().equals("tk") ){
parameter=TK.GetSign(parameter);
data.put("parameter", parameter);
}
data=setPublicParameter(c,object,data);//静态公共参数
data=setDynamicParameter(c,object,data);//动态公共参数
Long startTime=System.currentTimeMillis();
Response re = obj.SendRequest(data, data.get("serviceUrl").toString(), data.get("Request").toString());
Long endTime=System.currentTimeMillis();
String time=(endTime-startTime)+"毫秒";
String body=re.asString();
String codeORerrcode="";
String msgORerrmsy="";
String result = "";
if(re!=null){
body=re.asString();
if(body.contains("<html>")){
body="返回html页面,状态码:"+re.getStatusCode();
......@@ -85,7 +80,6 @@ public class APITest_tk extends TK{
}
codeORerrcode=getCode(re);
msgORerrmsy=getMsg(re);
}
Log.logInfo("返回结果="+StringUtils.decodeUnicode(body));
......@@ -109,6 +103,7 @@ public class APITest_tk extends TK{
// time
// );
if(result.indexOf("Fail")!=-1){
String Expect1=data.get("code")==null?"":data.get("code").toString();
String Expect2=data.get("msg")==null?"":data.get("msg").toString();
......@@ -124,22 +119,15 @@ public class APITest_tk extends TK{
@AfterClass
public void afterClass() {
//测试结束删除测试所用的数据
if (!isClearMysql) {
cleanUser_FromDB();//清除注册user_id,
cleanexam_FromDB();//清除用户地区操作表t_exam_area
try {
if(stmt!=null){
stmt.close();
}
if (conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
Set<Map.Entry<Class<?>,Object>> set=Delsql.entrySet();
Iterator<Entry<Class<?>,Object>> it=set.iterator();
while(it.hasNext()){
Map.Entry<Class<?>,Object> me=it.next();
Class<?> c=me.getKey();
Object object=me.getValue();
this.cleanMysqlData(c,object);
}
this.CloseMysql();
Log.logInfo("========测试结束========");
}
......
package makeTestCase;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.offcn.TestUnti.SheetUtils;
import net.sf.json.JSONObject;
public class NewMakeTestCases {
public static int state=0;//代表有其他页面没有,0标示没有,1表示有一个,2表示有两个
public static List<String> SheetList=new ArrayList<String>();//sheet页面的名称,里面存的是sheet2,sheet3之类的sheet页名称
public static List<String> nameList=new ArrayList<String>();//包含sheet页面对应的字段名称
public static List<String> List_1=new ArrayList<String>();//List_1
public static List<String> List_4=new ArrayList<String>();//List_4
public static List<String> List_5=new ArrayList<String>();//List_5
public static List<List<String>> list_all=new ArrayList<List<String>>();//缺失字段,最后判断是否应该算正向还是反向
public static String CaseKeLiDu=null;//设置用例颗粒度,2元祖测试为null,其他自行设置3,4,5,6,看参数数量而定
public static void main(String[] args) {
make("TestData/CaseMake.xls","Sheet1","post","tk");
}
public static void make(String FilePath,String SheetName,String getOrPost,String qudao){
//获取用例
List<String> listSum=TestCase(FilePath,SheetName);
Set<String> set=new HashSet<String>();
set.addAll(listSum);
listSum.clear();
listSum.addAll(set);
// for (String string : listSum) {
// System.out.println(string);
// }
List<String> TeseName= TestCaseName(listSum);
// System.out.println("用例数"+listSum.size());
// System.out.println("用例名字数"+TeseName.size());
//获取接口全信息
String AllPath="";
try {
AllPath=new readExcels().readExcels_path(FilePath,SheetName);
} catch (Exception e) {
e.printStackTrace();
}
String[] apipath=AllPath.split("/");
//获取接口类名
String leiming=apipath[apipath.length-1];
//获取接口路径
int w=AllPath.indexOf("/");
String path=AllPath.substring(w);
String name=FilePath.split("/")[1];
//获取接口名
String jieKouMing=apipath[0];
//生成测试用例
for(int i=0;i<listSum.size();i++){
String cases=listSum.get(i);
if("get".equals(getOrPost)){
cases=cases.replace(":", "=");
cases=cases.replace("\"", "");
cases=cases.replace(",", "&");
}
System.out.println(cases);
outCase(i,leiming,jieKouMing,TeseName.get(i),path,cases,name,"OutPage",getOrPost,qudao);
}
}
//第一个参数是数量,第二个参数是接口类名,第三个参数是中文名
public static void outCase(int i,String leiming,String jieKouMing,String TeseName,
String path,String cases,String wenjianming,String Sheet,String getOrPost,String qudao){
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = sdf.format(d);
//数据回写
SheetUtils sheet = new SheetUtils(wenjianming,Sheet);
sheet.writeExcel(
// s,
(i+1)+"",
leiming + "_" + (i+1),
(i+1)+"",
jieKouMing+"-"+TeseName,
qudao,
path,
"N",
getOrPost,
"200",
cases
);
}
//所有测试集合的用例名称
public static List<String> TestCaseName(List<String> list){
//所有测试集合的用例名称
List<String> listt=new ArrayList<String>();
List<String> list1_4=zhengxiang(List_1,List_4);
List<String> list1_5=zhengxiang(List_1,List_5);
//先把测试用例遍历
for (int i=0;i<list.size();i++) {
String name="";
// System.out.println("用例名称:"+listt.toString());
// System.out.println();
// System.out.println("测试用例:"+list.get(i));
// System.out.println("字段:"+List_1.toString());
// System.out.println("反向:"+list1_5.toString());
//每一条测试用例
//查看是否缺少字段
List<String> list_true=zhengxiang(list.get(i));
name=baohan(List_1,list_true);
if(!"未缺失".equals(name)){
listt.add(name);
continue;
}
name=list1_5(list1_5,list.get(i));
if(!"正向用例".equals(name)){
listt.add(name);
continue;
}
name=list1_4(list1_4,list.get(i));
listt.add(name);
}
return listt;
}
//获取正向所有精确字段
public static List<String> zhengxiang(String stra){
//预返回的集合
List<String> listt=new ArrayList<String>();
//循环获取到每一个字段的正确集合
String ziduan []=stra.split(",");
String zuo="";
for(int i=0;i<ziduan.length;i++){
zuo=ziduan[i];
String zhong []=zuo.split(":");
// 获取到每一个字段的正确中的一个2,3,4,5,6,
if(zhong[0]!=null && zhong[0].length()>2){
String a1=zhong[0].substring(1,zhong[0].length()-1);
listt.add(a1);
}
}
return listt;
}
//两个集合:list——1,list——4拼接成正向集合
public static List<String> zhengxiang(List<String> list_1,List<String> list_4){
//预返回的集合
List<String> listt=new ArrayList<String>();
String str="";
//循环获取到每一个字段的正确集合
for(int i=0;i<list_1.size();i++){
// 获取到每一个字段的正确中的一个2,3,4,5,6,
String zhengxiangfenjie []=list_4.get(i).split(",");
for(int j=0;j<zhengxiangfenjie.length;j++){
str="\""+list_1.get(i)+"\":"+zhengxiangfenjie[j];
listt.add(str);
}
}
return listt;
}
//用例中是否包含list——5中的信息,如果包含返回"反向用例-XXX"
public static String list1_5(List<String> list1_5,String str){
String queshideziduan="";
for(int i=0;i<list1_5.size();i++){
if(str.contains(list1_5.get(i))){
queshideziduan=list1_5.get(i);
}
}
if("".equals(queshideziduan)){
return "正向用例";
}else{
return "反向用例-"+queshideziduan;
}
}
//用例中是否包含list——4中的信息,如果包含返回"正向用例"
public static String list1_4(List<String> list1_4,String str){
String fenjie[] =str.split(",");
//测试用例集合
List<String> listSum=new ArrayList<String>();
for(int i=0;i<fenjie.length;i++){
listSum.add(fenjie[i]);
}
listSum.removeAll(list1_4);
// System.out.println(listSum.toString());
if(listSum.isEmpty()){
return "正向用例";
}else{
return "反向用例-"+listSum.toString();
}
}
//用例中是否包含list——1中的信息,如果没有返回XXXX字段缺失
public static String baohan(List<String> list_1,List<String> list_true){
//测试用例集合
List<String> listSum=new ArrayList<String>();
listSum.addAll(list_1);
String queshideziduan="";
// System.out.println(listSum.size());
// System.out.println(list_true.size());list_all
if(listSum.size()!=list_true.size()){
listSum.removeAll(list_true);
queshideziduan=listSum.toString();
}
if("".equals(queshideziduan)){
return "未缺失";
}else{
queshideziduan=queshideziduan.substring(1, queshideziduan.length()-1);
for(int i=0;i<list_all.size();i++){
String NorY=list_all.get(i).toString();
// System.out.println(NorY);
// System.out.println((", "+queshideziduan+","));
// System.out.println(NorY.contains(", "+queshideziduan+","));
// System.out.println(NorY.contains(", N,"));
if(NorY.contains(", "+queshideziduan+",") && NorY.contains(", N,")){
return "正向用例-"+queshideziduan+"非必输项缺失";
}
}
return "反向用例-"+queshideziduan+"缺失";
}
}
@SuppressWarnings({ "unused", "rawtypes" })
public static List<String> TestCase(String path,String Sheet){
//测试用例集合
List<String> listSum=new ArrayList<String>();
readExcels readExcels= new readExcels();
List<List<String>> list=null;
try {
list=readExcels.readExcels_return(path,Sheet);
list_all.addAll(list);
} catch (Exception e) {
e.printStackTrace();
}
List<Set<String>> listt=new ArrayList<Set<String>>();
List<Set<String>> listf=new ArrayList<Set<String>>();
for (int i=0;i<list.size();i++) {
List<String> li=list.get(i);
Set<String> sett=new HashSet<String>();
Set<String> setf=new HashSet<String>();
String name="";
Object [] objt=null;
Object [] objf=null;
for (int j=0;j<li.size();j++) {
if(j==1){
name=li.get(j).trim();
List_1.add(name);
}
if(j==4){
// if("N".equals(li.get(j-1).trim())){
// String str=(li.get(j).trim()+",null");
// objt=str.split(",");
// List_4.add(li.get(j).trim());
// List_4.add(null);
// }else{
objt=li.get(j).trim().split(",");
List_4.add(li.get(j).trim());
// }
}
if(j==5){
String s="";
if("".equals(li.get(j).trim()) || li.get(j).trim()==null){
s=""+li.get(2).trim()+","+li.get(3).trim();
List_5.add(s);
}else{
s=""+li.get(j).trim()+","+li.get(2).trim()+","+li.get(3).trim();
List_5.add(s);
}
objf=s.split(",");
}
}
// sett=getObject(name,objt,objt[0]+"");//老的正向用例生成方式
sett=getTrue(name,objt);
setf=getObject(name,objf,objt[0]+"");
listt.add(sett);
listf.add(setf);
}
// System.out.println("正向用例"+listt.toString());
// System.out.println("反向用例"+listf.toString());
//如果random_String.state不等于0说明存在其他sheet页面,如果是2就说明有其他两个sheet页
// System.out.println(state);
// System.out.println(SheetList);
// System.out.println(nameList);
for(int i=0;i<NewMakeTestCases.state;i++){
List<Set<String>> a=TestCase_N("TestData/CaseMake.xls",SheetList.get(i),nameList.get(i));
listt.add(a.get(0));
listf.add(a.get(1));
}
SheetList.clear();
nameList.clear();
// System.out.println(listt);
// System.out.println(listf);
//产生正向的用例
// Set<String> sum1=getZReslut(listt);//老的正向用例生成方式
Set<String> sum1=new Pict().GenerateCases(listt,CaseKeLiDu);
// System.out.println(sum1.size());
if(sum1==null){
System.out.println("正向用例生成失败,结果集为null");
return null;
}
Iterator it1 = sum1.iterator();
String yongli="";
while(it1.hasNext()){
// System.out.println(qudouhao(it1.next()+""));
yongli=(qudouhao(it1.next()+""));
yongli=yongli.replace("~", ",");//将用例所有的波浪线替换回来,替换成逗号
listSum.add(yongli);
}
// System.out.println(listSum.toString());
//产生反向的用例,第一个参数是正确的参数集合支取一个,第二个参数集合是错误的集合
for(int i=0;i<listf.size();i++){
Set<String> sum2=getFReslut(sum1,listf.get(i));
// System.out.println("sum2="+sum2);
Iterator it2 = sum2.iterator();
while(it2.hasNext()){
// System.out.println(qudouhao(it2.next()+""));
String ssss=(String) it2.next();
// System.out.println(ssss);
yongli=qudouhao(ssss+"");
yongli=yongli.replace("~", ",");//将用例所有的波浪线替换回来,替换成逗号
// System.out.println("yongli="+yongli);
listSum.add(yongli);
// System.out.println("listSum="+listSum);
}
}
// System.out.println(listSum.toString());
return listSum;
}
public static List<Set<String>> TestCase_N(String path,String Sheet,String ziduanname){
//测试用例集合
List<Set<String>> listSum=new ArrayList<Set<String>>();
readExcels readExcels= new readExcels();
List<List<String>> list=null;
try {
list=readExcels.readExcels_return(path,Sheet);
} catch (Exception e) {
e.printStackTrace();
}
List<Set<String>> listt=new ArrayList<Set<String>>();
List<Set<String>> listf=new ArrayList<Set<String>>();
for (int i=0;i<list.size();i++) {
List<String> li=list.get(i);
Set<String> sett=new HashSet<String>();
Set<String> setf=new HashSet<String>();
String name="";
Object [] objt=null;
Object [] objf=null;
for (int j=0;j<li.size();j++) {
if(j==1){
name=li.get(j).trim();
}
if(j==4){
objt=li.get(j).trim().split(",");
}
if(j==5){
String s="";
if("".equals(li.get(j).trim()) || li.get(j).trim()==null){
s=""+li.get(2).trim()+","+li.get(3).trim();
}else{
s=""+li.get(j).trim()+","+li.get(2).trim()+","+li.get(3).trim();
}
objf=s.split(",");
}
// System.out.println(objf.toString());
}
sett=getObject(name,objt,objt[0]+"");
setf=getObject(name,objf,objt[0]+"");
listt.add(sett);
listf.add(setf);
}
System.out.println("正向用例"+listt.toString());
System.out.println("反向用例"+listf.toString());
//正确和错误的集合
Set<String> set_n_t=new HashSet<String>();
Set<String> set_n_f=new HashSet<String>();
//产生正向的用例
Set<String> sum1=getZReslut(listt);
Iterator it1 = sum1.iterator();
String linshiyongli="";
while(it1.hasNext()){
// System.out.println(qudouhao(it1.next()+""));
linshiyongli=qudouhao(it1.next()+"");
linshiyongli=linshiyongli.replace(",", "~");
set_n_t.add("\""+ziduanname+"\""+":{"+linshiyongli+"}");
}
//产生反向的用例,第一个参数是正确的参数集合支取一个,第二个参数集合是错误的集合
for(int i=0;i<listf.size();i++){
Set<String> sum2=getFReslut(sum1,listf.get(i));
Iterator it2 = sum2.iterator();
while(it2.hasNext()){
// System.out.println(qudouhao(it2.next()+""));
linshiyongli=qudouhao(it2.next()+"");
linshiyongli=linshiyongli.replace(",", "~");
set_n_f.add("\""+ziduanname+"\""+":{"+linshiyongli+"}");
}
}
listSum.add(set_n_t);
listSum.add(set_n_f);
return listSum;
}
//去掉逗号
public static String qudouhao(String str){
str=str.trim();
if(str.length()>0 && str.charAt(0)==','){
str=str.substring(1);
}else if(str.length()>0 && str.charAt(str.length()-1)==','){
str=str.substring(0,str.length()-1);
}
return str;
}
//准备正向的用例参数
public static Set<String> getTrue(String name,Object[] obj){
String str="";
for(int i=0;i<obj.length;i++){
str=str+obj[i]+",";
}
str=str.substring(0, str.length()-1);
str=name+":"+str;
Set<String> result = new HashSet<String>();
result.add(str);
return result;
}
//生成正确的用例
public static Set<String> getZReslut(List<Set<String>> list){
String str="";
for(int i=0;i<list.size();i++){
String str1="";
Object[] obj=setjihe(list.get(i));
str1=Arrays.toString(obj).trim();
// System.out.println(str1);
str=str+str1.substring(1, str1.length()-1)+"==".trim();
}
str=str.substring(0, str.length()-2);
Set<String> result = HelloHongShu.getSet(str);
return result;
}
public static Object[] setjihe(Set<String> set){
Object[] obj=set.toArray();
return obj;
}
//生成错误的用例
public static Set<String> getFReslut(Set<String> set1,Set<String> set2){
Set<String> set=new HashSet<String>();
Object[] obj1=set1.toArray();
Object[] obj2=set2.toArray();
//获取正确用例的其中一个
String zhengque=obj1[0]+"";
String linshi="";
String cuowulinshi="";
Object [] zhengque1=zhengque.split(",");
StringBuffer sb=new StringBuffer();
for(int i=0;i<zhengque1.length;i++){
sb.append(zhengque1[i]);
sb.append(",");
}
String jihe=sb.toString().substring(0,sb.toString().length()-1);
// System.out.println(jihe);
//用正确的用例为模板,找到与错误部分相同的一节内容进行替换操作
for(int i=0;i<zhengque1.length;i++){
// System.out.println(11111111);
// for(int j=0;j<obj2.length;j++){
for(int j=(obj2.length-1);j>=0;j--){
//错误用例中分号前面的那段信息
String cuowu=obj2[j]+"";
cuowulinshi=cuowu.trim();
cuowu=(cuowu.split(":")[0]).trim();
linshi=(zhengque1[i]+"").trim();
if(!linshi.contains(cuowu)){
break;
}
zhengque=jihe;
// System.out.println("被替代前="+zhengque);
// System.out.println("被替代内容="+linshi);
// System.out.println("替代为="+cuowulinshi);
zhengque=zhengque.replace(linshi, cuowulinshi);
zhengque=quchongfudouhao(zhengque);
set.add(zhengque);
// System.out.println("被替代后="+zhengque);
// System.out.println("set="+set);
}
}
return set;
}
public static String quchongfudouhao(String str){
return str.replace(",,", ",");
}
//第一个参数是变量名,第二个参数是参数集合,第三个参数是正的需要被类型转换的参数
public static Set<String> getObject(String name , Object[] obj,String s){
// Object w1[]=new Object[obj.length];
Set<String> set=new HashSet<String>();
String linshi="";
for(int j=0;j<obj.length;j++){
if(obj[j]==null || "code".equals(obj[j])){
linshi="\""+name+"\""+":"+obj[j];
}else if("Y".equals(obj[j])){
linshi="";
}else if("N".equals(obj[j])){
linshi="";
// continue;
}else if("String".equals(obj[j])){
Long w=StringToInt(s);
// System.out.println("w="+w);
if(w!=0){
linshi="\""+name+"\""+":"+w;
}else{
linshi="\""+name+"\""+":"+1;//字符串转换成int类型失败后,将字符串变为0
// System.out.println(linshi);
}
}else if("int".equals(obj[j])){
linshi="\""+name+"\""+":"+"\""+s+"\"";
}else{
linshi="\""+name+"\""+":"+""+obj[j]+"";
}
// System.out.println(linshi);
set.add(linshi);
// System.out.println(set);
}
return set;
}
public static Long StringToInt(String str){
Long a=0L;
try {
a=Long.parseLong(str);
} catch (Exception e) {
// System.out.println("转换异常");
}
return a;
}
}
package makeTestCase;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.offcn.TestUnti.cmdUtil;
import com.offcn.TestUnti.fileUntil;
public class Pict {
public Set<String> GenerateCases(List<Set<String>> listt,String kelidu){
// System.out.println(listt);
fileUntil fu=new fileUntil();
if(fu.WriterFile(listt)){ //写入文件
// System.out.println("写入成功");
if(mackOutcases(kelidu)){ //调用pict程序生成txt文件
return trueCases();
}
}
return null;
}
public static void main(String[] args) {
mackOutcases("3");
}
//根据文件生成正向用例
public static Set<String> trueCases(){
String [] title=null;
Set<String> set=new HashSet<String>();
try {
ArrayList<String []> list=readFile_("caseOut.txt");
for(int i=0;i<list.size();i++){
if(i==0){
title=list.get(i);
}else{
String KeyAndValue="";
for(int j=0;j<list.get(i).length;j++){
String [] value=list.get(i);
KeyAndValue=KeyAndValue+"\""+title[j]+"\":"+value[j]+",";
}
set.add(KeyAndValue.substring(0,KeyAndValue.length()-1));
}
// System.out.println(set);
}
return set;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static ArrayList<String []> readFile_(String filename)throws IOException{
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+filename;
//创建一个读取流对象和文件相关联。
FileReader fr = new FileReader(sourceFile);
//为了提高效率。加入缓冲技术。将字符读取流对象作为参数传递给缓冲对象的构造函数。
BufferedReader bufr = new BufferedReader(fr);
String line = null;
ArrayList<String []> list=new ArrayList<String[]>();
while((line=bufr.readLine())!=null){
System.out.println(line);
String []title =line.split("\t");
list.add(title);
}
bufr.close();
return list;
}
public static boolean mackOutcases(String kelidu){
try {
File directory = new File(".");
String sourceFile;
String sourceFile1;
sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"case.txt";
sourceFile1 = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator;
String cmd = "pict "+sourceFile+">"+sourceFile1+"caseOut.txt";
String cmd2 = "cmd /c " + "\"\" " + cmd ;
if(kelidu!=null){
cmd2=cmd2+" "+"/o:"+kelidu;
}
// System.out.println(cmd2);
cmdUtil.run(cmd2);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<Databases>
<Database name="xyzb">
<sqlurl>jdbc:mysql://rm-2ze364spvypz122fw8o.mysql.rds.aliyuncs.com:3306/xyu</sqlurl>
<sqlname>master</sqlname>
<sqlpwd>EDCdd22LLZBCADF123</sqlpwd>
</Database>
<Database name="tk">
<sqlurl>jdbc:mysql://39.105.124.219:3312/tiku?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull</sqlurl>
<sqlname>testTest</sqlname>
<sqlpwd>7b467efW#$%f5c50aa3d</sqlpwd>
</Database>
<Database name="nwn">
<sqlurl>jdbc:mysql://39.105.124.219:3312/nwn?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull</sqlurl>
<sqlname>nwnBeta</sqlname>
<sqlpwd>Beta@&amp;123</sqlpwd>
</Database>
</Databases>
\ No newline at end of file
pict C:\Users\ibm\git\tiku_app\tiku_App\src\resources\case.txt>C:\Users\ibm\git\tiku_app\tiku_App\src\resources\caseOut.txt
\ No newline at end of file
title:code
content:"详情"
type:"1"
url:"www.baidu.com"
id:"150"
push_type:"1"
push_token:"push_token"
appid:"tiku"
title content type url id push_type push_token appid
code "详情" "1" "www.baidu.com" "150" "1" "push_token" "tiku"
......@@ -49,21 +49,7 @@
<sqlpwd>7b467efW#$%f5c50aa3d</sqlpwd>
</system>
<system name="tkxs"><!-- 题库线上环境 -->
<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>
<client_id>bestbuy-acceptance</client_id>
<client_secret>bestbuy-acceptance</client_secret>
<grant_type>client_credentials</grant_type>
<isProduct>false</isProduct>
<RM_URI>http://test.tiku.eoffcn.com</RM_URI>
<RM_port></RM_port>
<RM_basePath></RM_basePath>
<redis_URI>10.10.229.48</redis_URI>
<redis_db_index>5</redis_db_index>
<sqlurl>jdbc:mysql://180.76.155.235:3306/tiku?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull</sqlurl>
<sqlname>tiku</sqlname>
<sqlpwd>PFQ6nJ7YlG8Y</sqlpwd>
</system>
<system name="nwn"><!-- nwn -->
<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>
......
<?xml version="1.0" encoding="UTF-8"?>
<systems>
<system name="gmysx"><!-- 更美预授信 -->
<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>
<client_id>bestbuy-acceptance</client_id>
<client_secret>bestbuy-acceptance</client_secret>
<grant_type>client_credentials</grant_type>
<isProduct>N</isProduct>
<RM_URI>http://t1.zuul.pub.puhuifinance.com</RM_URI>
<RM_port>80</RM_port>
<RM_basePath>/bestbuy-pclacceptance/api</RM_basePath>
<redis_URI>10.10.229.48</redis_URI>
<redis_db_index>5</redis_db_index>
<sqlurl>jdbc:mysql://10.10.231.135:3306/huimai_safe?user=root&amp;password=OYLDASuPfbpsEQB6&amp;useUnicode=true&amp;characterEncoding=UTF8</sqlurl>
</system>
<system name="gmdd"><!-- 更美订单 -->
<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>
<client_id>bestbuy-acceptance</client_id>
<client_secret>bestbuy-acceptance</client_secret>
<grant_type>client_credentials</grant_type>
<isProduct>N</isProduct>
<RM_URI>http://t1.zuul.pub.puhuifinance.com</RM_URI>
<RM_port>80</RM_port>
<RM_basePath>/bestbuy-pclacceptance/api</RM_basePath>
<redis_URI>10.10.229.48</redis_URI>
<redis_db_index>5</redis_db_index>
<sqlurl>jdbc:mysql://10.10.231.135:3306/huimai_safe?user=root&amp;password=OYLDASuPfbpsEQB6&amp;useUnicode=true&amp;characterEncoding=UTF8</sqlurl>
</system>
<system name="rgxs"><!-- 人工信审 -->
<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>
<client_id>bestbuy-acceptance</client_id>
<client_secret>bestbuy-acceptance</client_secret>
<grant_type>client_credentials</grant_type>
<isProduct>N</isProduct>
<RM_URI>http://ut1.zuul.pub.puhuifinance.com</RM_URI>
<RM_port>8765</RM_port>
<RM_basePath>/bestbuy-pclacceptance/api</RM_basePath>
<redis_URI>10.10.229.48</redis_URI>
<redis_db_index>5</redis_db_index>
<sqlurl>jdbc:mysql://10.10.231.135:3306/streaming?user=root&amp;password=OYLDASuPfbpsEQB6&amp;useUnicode=true&amp;characterEncoding=UTF8</sqlurl>
</system>
<system name="bl"><!-- 保理系统 -->
<access_token_uri>http://t.uaa.pub.puhuifinance.com:8082/uaa/oauth/token</access_token_uri>
<client_id>factoring-server</client_id>
<client_secret>factoring-server</client_secret>
<grant_type>client_credentials</grant_type>
<isProduct>N</isProduct>
<RM_URI>http://10.10.121.184</RM_URI>
<RM_port>8888</RM_port>
<RM_basePath>/baoli</RM_basePath>
<redis_URI>10.10.229.48</redis_URI>
<redis_db_index>5</redis_db_index>
<sqlurl>jdbc:mysql://10.10.231.135:3306/streaming?user=root&amp;password=OYLDASuPfbpsEQB6&amp;useUnicode=true&amp;characterEncoding=UTF8</sqlurl>
</system>
<system name="zy"><!-- 自营订单 -->
<!--<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>-->
<!--<client_id>bestbuy-acceptance</client_id>-->
<!--<client_secret>bestbuy-acceptance</client_secret>-->
<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>
<client_id>gengmei</client_id>
<client_secret>gengmei</client_secret>
<grant_type>client_credentials</grant_type>
<isProduct>N</isProduct>
<RM_URI>http://10.10.155.181</RM_URI>
<RM_port>3000</RM_port>
<RM_basePath></RM_basePath>
<redis_URI>10.10.229.48</redis_URI>
<redis_db_index>5</redis_db_index>
<sqlurl>jdbc:mysql://10.10.231.135:3306/huimai_safe?user=root&amp;password=OYLDASuPfbpsEQB6&amp;useUnicode=true&amp;characterEncoding=UTF8</sqlurl>
</system>
<system name="sh"><!-- 商户微信 -->
<access_token_uri>http://106.75.5.205:8082/uaa/oauth/token</access_token_uri>
<client_id>gengmei</client_id>
<client_secret>gengmei</client_secret>
<grant_type>client_credentials</grant_type>
<isProduct>N</isProduct>
<RM_URI>http://t1.zuul.pub.puhuifinance.com</RM_URI>
<RM_port>80</RM_port>
<RM_basePath>/bestbuy-pclacceptance/api</RM_basePath>
<redis_URI>10.10.229.48</redis_URI>
<redis_db_index>5</redis_db_index>
<sqlurl>jdbc:mysql://10.10.231.135:3306/huimai_safe?user=root&amp;password=OYLDASuPfbpsEQB6&amp;useUnicode=true&amp;characterEncoding=UTF8</sqlurl>
</system>
</systems>
\ No newline at end of file
xls=DataAll.xls
sheet=TestCase1
mysql_local_Online=local
\ No newline at end of file
mysql_local_Online=local
Percentage=60
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment