1. WEB UI用例增加支持调用外部WEB UI用例

2. WEB UI用例增加支持接口步骤
3. 增加支持使用标题获取窗口句柄
4. 增加支持使用标题切换窗口
This commit is contained in:
Killua 2018-03-07 11:29:22 +08:00
parent 7947fe7671
commit b6836b8426
9 changed files with 1399 additions and 1120 deletions

92
LuckyFrameClient.iml Normal file
View File

@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Spring" name="Spring">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/Resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" />
<orderEntry type="library" name="Maven: c3p0:c3p0:0.9.1.2" level="project" />
<orderEntry type="library" name="Maven: com.jcraft:jsch:0.1.54" level="project" />
<orderEntry type="library" name="Maven: javax.mail:mail:1.4.7" level="project" />
<orderEntry type="library" name="Maven: javax.activation:activation:1.1" level="project" />
<orderEntry type="library" name="Maven: commons-beanutils:commons-beanutils:1.9.3" level="project" />
<orderEntry type="library" name="Maven: commons-cli:commons-cli:1.3.1" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.10" level="project" />
<orderEntry type="library" name="Maven: commons-collections:commons-collections:3.2.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-compress:1.13" level="project" />
<orderEntry type="library" name="Maven: commons-configuration:commons-configuration:1.10" level="project" />
<orderEntry type="library" name="Maven: commons-daemon:commons-daemon:1.0.15" level="project" />
<orderEntry type="library" name="Maven: commons-digester:commons-digester:2.1" level="project" />
<orderEntry type="library" name="Maven: commons-el:commons-el:1.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.6" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.5" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: commons-logging:commons-logging:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-math:2.2" level="project" />
<orderEntry type="library" name="Maven: commons-net:commons-net:3.6" level="project" />
<orderEntry type="library" name="Maven: log4j:log4j:1.2.17" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.24" level="project" />
<orderEntry type="library" name="Maven: br.eti.kinoshita:testlink-java-api:1.9.16-0" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.5" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.8.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-core:2.8.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-configuration2:2.1.1" level="project" />
<orderEntry type="library" name="Maven: commons-httpclient:commons-httpclient:3.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.xmlrpc:xmlrpc-client:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.xmlrpc:xmlrpc-common:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.ws.commons.util:ws-commons-util:1.0.2" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-java:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-api:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-chrome-driver:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-edge-driver:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-firefox-driver:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-ie-driver:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-opera-driver:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-safari-driver:3.8.1" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-support:3.8.1" level="project" />
<orderEntry type="library" name="Maven: net.bytebuddy:byte-buddy:1.7.5" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-exec:1.3" level="project" />
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.8.2" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:23.0" level="project" />
<orderEntry type="library" name="Maven: com.google.code.findbugs:jsr305:1.3.9" level="project" />
<orderEntry type="library" name="Maven: com.google.errorprone:error_prone_annotations:2.0.18" level="project" />
<orderEntry type="library" name="Maven: com.google.j2objc:j2objc-annotations:1.1" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.mojo:animal-sniffer-annotations:1.14" level="project" />
<orderEntry type="library" name="Maven: org.seleniumhq.selenium:selenium-remote-driver:3.8.1" level="project" />
<orderEntry type="library" name="Maven: xml-apis:xml-apis:1.4.01" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:6.0.5" level="project" />
<orderEntry type="library" name="Maven: org.freemarker:freemarker:2.3.26-incubating" level="project" />
<orderEntry type="library" name="Maven: net.sf.json-lib:json-lib:jdk15:2.4" level="project" />
<orderEntry type="library" name="Maven: net.sf.ezmorph:ezmorph:1.0.6" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.5.2" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.5.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.5.1" level="project" />
<orderEntry type="library" name="Maven: io.appium:java-client:6.0.0-BETA2" level="project" />
<orderEntry type="library" name="Maven: cglib:cglib:3.2.5" level="project" />
<orderEntry type="library" name="Maven: org.ow2.asm:asm:5.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.ant:ant:1.9.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.ant:ant-launcher:1.9.6" level="project" />
<orderEntry type="library" name="Maven: commons-validator:commons-validator:1.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.0.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.0.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.0.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.0.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.0.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.0.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.8.13" level="project" />
<orderEntry type="library" name="Maven: org.openpnp:opencv:3.2.0-1" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpmime:4.5.4" level="project" />
</component>
</module>

Binary file not shown.

View File

@ -1,5 +1,6 @@
#===============================系统配置=====================================
server.web.ip=localhost
#server.web.ip=localhost
server.web.ip=192.168.12.112
server.web.port=8080
#===============================TestLink=====================================
#TestLink URL地址
@ -8,15 +9,18 @@ testlink.api.ip=localhost
testlink.api.devkey=40ad3f1eb4cac155a5e0704e9c5280d2
#================================数据库=============================================
#数据库地址
mysql.db.ip=localhost
#mysql.db.ip=localhost
mysql.db.ip=192.168.12.94
#数据库端口
mysql.db.port=3306
#数据库名
mysql.db.dbname=luckyframedb
#数据库链接用户名
mysql.db.username=luckyframe
#mysql.db.username=luckyframe
mysql.db.username=root
#数据库链接密码
mysql.db.userpwd=luckyframe
#mysql.db.userpwd=luckyframe
mysql.db.userpwd=Devops123
#==================================邮件============================================
#smtp邮件IP
mail.smtp.ip=smtp.qq.com

View File

@ -7,6 +7,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import luckyclient.caserun.exinterface.analyticsteps.InterfaceAnalyticCase;
import luckyclient.caserun.exwebdriver.ex.WebCaseExecution;
import luckyclient.caserun.exwebdriver.ex.WebDriverAnalyticCase;
import luckyclient.dblog.DbLink;
import luckyclient.dblog.LogOperation;
import luckyclient.planapi.api.GetServerAPI;
@ -16,6 +18,7 @@ import luckyclient.planapi.entity.PublicCaseParams;
import luckyclient.publicclass.ChangString;
import luckyclient.publicclass.InvokeMethod;
import luckyclient.publicclass.LogUtil;
import org.openqa.selenium.WebDriver;
/**
* =================================================================
@ -23,99 +26,98 @@ import luckyclient.publicclass.LogUtil;
* 为了尊重作者的劳动成果LuckyFrame关键版权信息严禁篡改
* 有任何疑问欢迎联系作者讨论 QQ:1573584944 seagull1985
* =================================================================
*
*
* @author seagull
* @date 2017年12月1日 上午9:29:40
*
*/
public class TestCaseExecution {
protected static final String ASSIGNMENT_SIGN = "$=";
protected static final String FUZZY_MATCHING_SIGN = "%=";
protected static final String REGULAR_MATCHING_SIGN = "~=";
protected static final String ASSIGNMENT_SIGN = "$=";
protected static final String FUZZY_MATCHING_SIGN = "%=";
protected static final String REGULAR_MATCHING_SIGN = "~=";
/**
* @param 项目名
* @param 用例编号
* @param 用例版本号
* 用于单条用例调试并通过日志框架写日志到UTP上用做UTP上单条用例运行
*/
@SuppressWarnings("static-access")
public static void oneCaseExecuteForTast(String projectname, String testCaseExternalId, int version, String taskid) {
Map<String, String> variable = new HashMap<String, String>(0);
TestControl.TASKID = taskid;
DbLink.exetype = 0;
// 初始化写用例结果以及日志模块
LogOperation caselog = new LogOperation();
String packagename = null;
String functionname = null;
String expectedresults = null;
Integer setresult = 1;
Object[] getParameterValues = null;
String testnote = "初始化测试结果";
int k = 0;
// 删除旧的日志
LogOperation.deleteCaseLogDetail(testCaseExternalId, taskid);
ProjectCase testcaseob = GetServerAPI.cgetCaseBysign(testCaseExternalId);
List<PublicCaseParams> pcplist=GetServerAPI.cgetParamsByProjectid(String.valueOf(testcaseob.getProjectid()));
// 把公共参数加入到MAP中
for (PublicCaseParams pcp : pcplist) {
variable.put(pcp.getParamsname(), pcp.getParamsvalue());
}
List<ProjectCasesteps> steps = GetServerAPI.getStepsbycaseid(testcaseob.getId());
if(steps.size()==0){
setresult=2;
luckyclient.publicclass.LogUtil.APP.error("用例中未找到步骤,请检查!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid,"用例中未找到步骤,请检查!", "error", "1");
testnote="用例中未找到步骤,请检查!";
}
// 进入循环解析用例所有步骤
for (int i = 0; i < steps.size(); i++) {
Map<String, String> casescript = InterfaceAnalyticCase.analyticCaseStep(testcaseob, steps.get(i), taskid,caselog);
try {
packagename = casescript.get("PackageName");
packagename = ChangString.changparams(packagename, variable,"包路径");
functionname = casescript.get("FunctionName");
functionname = ChangString.changparams(functionname, variable,"方法名");
} catch (Exception e) {
k = 0;
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcaseob.getSign() + "解析包名或是方法名失败,请检查!");
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名或是方法名失败,请检查!", "error", String.valueOf(i + 1), "");
e.printStackTrace();
break; // 某一步骤失败后此条用例置为失败退出
}
// 用例名称解析出现异常或是单个步骤参数解析异常
if ((null != functionname && functionname.contains("解析异常")) || k == 1) {
k = 0;
testnote = "用例第" + (i + 1) + "步解析出错啦!";
break;
}
expectedresults = casescript.get("ExpectedResults");
expectedresults = ChangString.changparams(expectedresults, variable,"预期结果");
// 判断方法是否带参数
if (casescript.size() > 4) {
// 获取传入参数放入对象中初始化参数对象个数
getParameterValues = new Object[casescript.size() - 4];
for (int j = 0; j < casescript.size() - 4; j++) {
if (casescript.get("FunctionParams" + (j + 1)) == null) {
k = 1;
break;
}
String parameterValues = casescript.get("FunctionParams" + (j + 1));
parameterValues = ChangString.changparams(parameterValues, variable,"用例参数");
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcaseob.getSign() + "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues);
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues, "info", String.valueOf(i + 1), "");
getParameterValues[j] = parameterValues;
}
} else {
getParameterValues = null;
}
// 调用动态方法执行测试用例
try {
luckyclient.publicclass.LogUtil.APP.info("开始调用方法:" + functionname + " .....");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "开始调用方法:" + functionname + " .....", "info", String.valueOf(i + 1));
/**
* @param projectname 项目名
* @param testCaseExternalId 用例编号
* @param version 用例版本号
* 用于单条用例调试并通过日志框架写日志到UTP上用做UTP上单条用例运行
*/
@SuppressWarnings("static-access")
public static void oneCaseExecuteForTast(String projectname, String testCaseExternalId, int version, String taskid) {
Map<String, String> variable = new HashMap<String, String>(0);
TestControl.TASKID = taskid;
DbLink.exetype = 0;
// 初始化写用例结果以及日志模块
LogOperation caselog = new LogOperation();
String packagename = null;
String functionname = null;
String expectedresults = null;
Integer setresult = 1;
Object[] getParameterValues = null;
String testnote = "初始化测试结果";
int k = 0;
// 删除旧的日志
LogOperation.deleteCaseLogDetail(testCaseExternalId, taskid);
ProjectCase testcaseob = GetServerAPI.cgetCaseBysign(testCaseExternalId);
List<PublicCaseParams> pcplist = GetServerAPI.cgetParamsByProjectid(String.valueOf(testcaseob.getProjectid()));
// 把公共参数加入到MAP中
for (PublicCaseParams pcp : pcplist) {
variable.put(pcp.getParamsname(), pcp.getParamsvalue());
}
List<ProjectCasesteps> steps = GetServerAPI.getStepsbycaseid(testcaseob.getId());
if (steps.size() == 0) {
setresult = 2;
luckyclient.publicclass.LogUtil.APP.error("用例中未找到步骤,请检查!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "用例中未找到步骤,请检查!", "error", "1");
testnote = "用例中未找到步骤,请检查!";
}
// 进入循环解析用例所有步骤
for (int i = 0; i < steps.size(); i++) {
Map<String, String> casescript = InterfaceAnalyticCase.analyticCaseStep(testcaseob, steps.get(i), taskid, caselog);
try {
packagename = casescript.get("PackageName");
packagename = ChangString.changparams(packagename, variable, "包路径");
functionname = casescript.get("FunctionName");
functionname = ChangString.changparams(functionname, variable, "方法名");
} catch (Exception e) {
k = 0;
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcaseob.getSign() + "解析包名或是方法名失败,请检查!");
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名或是方法名失败,请检查!", "error", String.valueOf(i + 1), "");
e.printStackTrace();
break; // 某一步骤失败后此条用例置为失败退出
}
// 用例名称解析出现异常或是单个步骤参数解析异常
if ((null != functionname && functionname.contains("解析异常")) || k == 1) {
k = 0;
testnote = "用例第" + (i + 1) + "步解析出错啦!";
break;
}
expectedresults = casescript.get("ExpectedResults");
expectedresults = ChangString.changparams(expectedresults, variable, "预期结果");
// 判断方法是否带参数
if (casescript.size() > 4) {
// 获取传入参数放入对象中初始化参数对象个数
getParameterValues = new Object[casescript.size() - 4];
for (int j = 0; j < casescript.size() - 4; j++) {
if (casescript.get("FunctionParams" + (j + 1)) == null) {
k = 1;
break;
}
testnote = InvokeMethod.callCase(packagename, functionname, getParameterValues,steps.get(i).getSteptype(),steps.get(i).getAction());
String parameterValues = casescript.get("FunctionParams" + (j + 1));
parameterValues = ChangString.changparams(parameterValues, variable, "用例参数");
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcaseob.getSign() + "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues);
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues, "info", String.valueOf(i + 1), "");
getParameterValues[j] = parameterValues;
}
} else {
getParameterValues = null;
}
// 调用动态方法执行测试用例
try {
luckyclient.publicclass.LogUtil.APP.info("开始调用方法:" + functionname + " .....");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "开始调用方法:" + functionname + " .....", "info", String.valueOf(i + 1));
testnote = InvokeMethod.callCase(packagename, functionname, getParameterValues, steps.get(i).getSteptype(), steps.get(i).getAction());
if (null != expectedresults && !expectedresults.isEmpty()) {
luckyclient.publicclass.LogUtil.APP.info("expectedResults=【" + expectedresults + "");
@ -164,117 +166,117 @@ public class TestCaseExecution {
}
}
// 获取步骤间等待时间
int waitsec = Integer.parseInt(casescript.get("StepWait"));
if (waitsec > 0) {
Thread.sleep(waitsec * 1000);
}
} catch (Exception e) {
luckyclient.publicclass.LogUtil.ERROR.error("调用方法过程出错,方法名:" + functionname + " 请重新检查脚本方法名称以及参数!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "调用方法过程出错,方法名:" + functionname + " 请重新检查脚本方法名称以及参数!", "error", String.valueOf(i + 1));
luckyclient.publicclass.LogUtil.ERROR.error(e, e);
testnote = "CallCase调用出错";
setresult = 1;
e.printStackTrace();
break;
}
}
variable.clear(); // 清空传参MAP
// 如果调用方法过程中未出错进入设置测试结果流程
if (!testnote.contains("CallCase调用出错") && !testnote.contains("解析出错啦!")) {
luckyclient.publicclass.LogUtil.APP.info("用例 " + testCaseExternalId + "解析成功,并成功调用用例中方法,请继续查看执行结果!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "解析成功,并成功调用用例中方法,请继续查看执行结果!", "info", "SETCASERESULT...");
caselog.updateCaseDetail(taskid, testCaseExternalId, setresult);
} else {
setresult = 1;
luckyclient.publicclass.LogUtil.APP.error("用例 " + testCaseExternalId + "解析或是调用步骤中的方法出错!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "解析或是调用步骤中的方法出错!", "error", "SETCASERESULT...");
caselog.updateCaseDetail(taskid, testCaseExternalId, 2);
}
if (0 == setresult) {
luckyclient.publicclass.LogUtil.APP.info("用例 " + testCaseExternalId + "步骤全部执行成功!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "步骤全部执行成功!", "info", "EXECUTECASESUC...");
} else {
luckyclient.publicclass.LogUtil.APP.error("用例 " + testCaseExternalId + "在执行过程中失败,请检查日志!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "在执行过程中失败,请检查日志!", "error", "EXECUTECASESUC...");
}
LogOperation.updateTastdetail(taskid, 0);
}
// 获取步骤间等待时间
int waitsec = Integer.parseInt(casescript.get("StepWait"));
if (waitsec > 0) {
Thread.sleep(waitsec * 1000);
}
} catch (Exception e) {
luckyclient.publicclass.LogUtil.ERROR.error("调用方法过程出错,方法名:" + functionname + " 请重新检查脚本方法名称以及参数!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "调用方法过程出错,方法名:" + functionname + " 请重新检查脚本方法名称以及参数!", "error", String.valueOf(i + 1));
luckyclient.publicclass.LogUtil.ERROR.error(e, e);
testnote = "CallCase调用出错";
setresult = 1;
e.printStackTrace();
break;
}
}
variable.clear(); // 清空传参MAP
// 如果调用方法过程中未出错进入设置测试结果流程
if (!testnote.contains("CallCase调用出错") && !testnote.contains("解析出错啦!")) {
luckyclient.publicclass.LogUtil.APP.info("用例 " + testCaseExternalId + "解析成功,并成功调用用例中方法,请继续查看执行结果!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "解析成功,并成功调用用例中方法,请继续查看执行结果!", "info", "SETCASERESULT...");
caselog.updateCaseDetail(taskid, testCaseExternalId, setresult);
} else {
setresult = 1;
luckyclient.publicclass.LogUtil.APP.error("用例 " + testCaseExternalId + "解析或是调用步骤中的方法出错!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "解析或是调用步骤中的方法出错!", "error", "SETCASERESULT...");
caselog.updateCaseDetail(taskid, testCaseExternalId, 2);
}
if (0 == setresult) {
luckyclient.publicclass.LogUtil.APP.info("用例 " + testCaseExternalId + "步骤全部执行成功!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "步骤全部执行成功!", "info", "EXECUTECASESUC...");
} else {
luckyclient.publicclass.LogUtil.APP.error("用例 " + testCaseExternalId + "在执行过程中失败,请检查日志!");
LogOperation.updateCaseLogDetail(testCaseExternalId, taskid, "在执行过程中失败,请检查日志!", "error", "EXECUTECASESUC...");
}
LogOperation.updateTastdetail(taskid, 0);
}
/**
* @param 项目名
* @param 用例编号
* @param 用例版本号
* 用于在UI的测试过程中需要调用接口的测试用例
*/
protected static String oneCaseExecuteForWebDriver(String testCaseExternalId, String taskid,LogOperation caselog) {
Map<String, String> variable = new HashMap<String, String>(0);
String packagename = null;
String functionname = null;
String expectedresults = null;
Integer setresult = 1;
Object[] getParameterValues = null;
String testnote = "初始化测试结果";
int k = 0;
ProjectCase testcaseob = GetServerAPI.cgetCaseBysign(testCaseExternalId);
List<PublicCaseParams> pcplist=GetServerAPI.cgetParamsByProjectid(String.valueOf(testcaseob.getProjectid()));
// 把公共参数加入到MAP中
for (PublicCaseParams pcp : pcplist) {
variable.put(pcp.getParamsname(), pcp.getParamsvalue());
}
List<ProjectCasesteps> steps = GetServerAPI.getStepsbycaseid(testcaseob.getId());
if(steps.size()==0){
setresult=2;
luckyclient.publicclass.LogUtil.APP.error("用例中未找到步骤,请检查!");
caselog.caseLogDetail(taskid, testcaseob.getSign(), "用例中未找到步骤,请检查!", "error", "1", "");
testnote="用例中未找到步骤,请检查!";
}
// 进入循环解析用例所有步骤
for (int i = 0; i < steps.size(); i++) {
Map<String, String> casescript = InterfaceAnalyticCase.analyticCaseStep(testcaseob, steps.get(i), taskid,caselog);
try {
packagename = casescript.get("PackageName");
packagename = ChangString.changparams(packagename, variable,"包路径");
functionname = casescript.get("FunctionName");
functionname = ChangString.changparams(functionname, variable,"方法名");
} catch (Exception e) {
k = 0;
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcaseob.getSign() + "解析包名或是方法名失败,请检查!");
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名或是方法名失败,请检查!", "error", String.valueOf(i + 1), "");
e.printStackTrace();
break; // 某一步骤失败后此条用例置为失败退出
}
// 用例名称解析出现异常或是单个步骤参数解析异常
if ((null != functionname && functionname.contains("解析异常")) || k == 1) {
k = 0;
testnote = "用例第" + (i + 1) + "步解析出错啦!";
break;
}
expectedresults = casescript.get("ExpectedResults");
expectedresults = ChangString.changparams(expectedresults, variable,"预期结果");
// 判断方法是否带参数
if (casescript.size() > 4) {
// 获取传入参数放入对象中
getParameterValues = new Object[casescript.size() - 4];
for (int j = 0; j < casescript.size() - 4; j++) {
if (casescript.get("FunctionParams" + (j + 1)) == null) {
k = 1;
break;
}
String parameterValues = casescript.get("FunctionParams" + (j + 1));
parameterValues = ChangString.changparams(parameterValues, variable,"用例参数");
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcaseob.getSign() + "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues);
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues, "info", String.valueOf(i + 1), "");
getParameterValues[j] = parameterValues;
}
} else {
getParameterValues = null;
}
// 调用动态方法执行测试用例
try {
luckyclient.publicclass.LogUtil.APP.info("开始调用方法:" + functionname + " .....");
/**
* @param testCaseExternalId 用例编号
* @param taskid 任务ID
* @param caselog 日志操作对象
* 用于在UI的测试过程中需要调用接口的测试用例
*/
protected static String oneCaseExecuteForWebDriver(String testCaseExternalId, String taskid, LogOperation caselog) {
Map<String, String> variable = new HashMap<String, String>(0);
String packagename = null;
String functionname = null;
String expectedresults = null;
Integer setresult = 1;
Object[] getParameterValues = null;
String testnote = "初始化测试结果";
int k = 0;
ProjectCase testcaseob = GetServerAPI.cgetCaseBysign(testCaseExternalId);
List<PublicCaseParams> pcplist = GetServerAPI.cgetParamsByProjectid(String.valueOf(testcaseob.getProjectid()));
// 把公共参数加入到MAP中
for (PublicCaseParams pcp : pcplist) {
variable.put(pcp.getParamsname(), pcp.getParamsvalue());
}
List<ProjectCasesteps> steps = GetServerAPI.getStepsbycaseid(testcaseob.getId());
if (steps.size() == 0) {
setresult = 2;
luckyclient.publicclass.LogUtil.APP.error("用例中未找到步骤,请检查!");
caselog.caseLogDetail(taskid, testcaseob.getSign(), "用例中未找到步骤,请检查!", "error", "1", "");
testnote = "用例中未找到步骤,请检查!";
}
// 进入循环解析用例所有步骤
for (int i = 0; i < steps.size(); i++) {
Map<String, String> casescript = InterfaceAnalyticCase.analyticCaseStep(testcaseob, steps.get(i), taskid, caselog);
try {
packagename = casescript.get("PackageName");
packagename = ChangString.changparams(packagename, variable, "包路径");
functionname = casescript.get("FunctionName");
functionname = ChangString.changparams(functionname, variable, "方法名");
} catch (Exception e) {
k = 0;
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcaseob.getSign() + "解析包名或是方法名失败,请检查!");
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名或是方法名失败,请检查!", "error", String.valueOf(i + 1), "");
e.printStackTrace();
break; // 某一步骤失败后此条用例置为失败退出
}
// 用例名称解析出现异常或是单个步骤参数解析异常
if ((null != functionname && functionname.contains("解析异常")) || k == 1) {
k = 0;
testnote = "用例第" + (i + 1) + "步解析出错啦!";
break;
}
expectedresults = casescript.get("ExpectedResults");
expectedresults = ChangString.changparams(expectedresults, variable, "预期结果");
// 判断方法是否带参数
if (casescript.size() > 4) {
// 获取传入参数放入对象中
getParameterValues = new Object[casescript.size() - 4];
for (int j = 0; j < casescript.size() - 4; j++) {
if (casescript.get("FunctionParams" + (j + 1)) == null) {
k = 1;
break;
}
String parameterValues = casescript.get("FunctionParams" + (j + 1));
parameterValues = ChangString.changparams(parameterValues, variable, "用例参数");
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcaseob.getSign() + "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues);
caselog.caseLogDetail(taskid, testcaseob.getSign(), "解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues, "info", String.valueOf(i + 1), "");
getParameterValues[j] = parameterValues;
}
} else {
getParameterValues = null;
}
// 调用动态方法执行测试用例
try {
luckyclient.publicclass.LogUtil.APP.info("开始调用方法:" + functionname + " .....");
testnote = InvokeMethod.callCase(packagename, functionname, getParameterValues,steps.get(i).getSteptype(),steps.get(i).getAction());
testnote = InvokeMethod.callCase(packagename, functionname, getParameterValues, steps.get(i).getSteptype(), steps.get(i).getAction());
if (null != expectedresults && !expectedresults.isEmpty()) {
luckyclient.publicclass.LogUtil.APP.info("expectedResults=【" + expectedresults + "");
@ -323,26 +325,81 @@ public class TestCaseExecution {
}
}
int waitsec = Integer.parseInt(casescript.get("StepWait"));
if (waitsec > 0) {
Thread.sleep(waitsec * 1000);
}
} catch (Exception e) {
LogUtil.ERROR.error("调用方法过程出错,方法名:" + functionname + " 请重新检查脚本方法名称以及参数!");
LogUtil.ERROR.error(e, e);
testnote = "CallCase调用出错";
setresult = 1;
e.printStackTrace();
break;
}
}
variable.clear(); // 清空传参MAP
if (0 == setresult) {
luckyclient.publicclass.LogUtil.APP.info("用例 " + testcaseob.getSign() + "步骤全部执行成功!");
} else {
luckyclient.publicclass.LogUtil.APP.error("用例 " + testcaseob.getSign() + "在执行过程中失败,请检查日志!");
}
return testnote;
}
int waitsec = Integer.parseInt(casescript.get("StepWait"));
if (waitsec > 0) {
Thread.sleep(waitsec * 1000);
}
} catch (Exception e) {
LogUtil.ERROR.error("调用方法过程出错,方法名:" + functionname + " 请重新检查脚本方法名称以及参数!");
LogUtil.ERROR.error(e, e);
testnote = "CallCase调用出错";
setresult = 1;
e.printStackTrace();
break;
}
}
variable.clear(); // 清空传参MAP
if (0 == setresult) {
luckyclient.publicclass.LogUtil.APP.info("用例 " + testcaseob.getSign() + "步骤全部执行成功!");
} else {
luckyclient.publicclass.LogUtil.APP.error("用例 " + testcaseob.getSign() + "在执行过程中失败,请检查日志!");
}
return testnote;
}
protected static String oneCaseExecuteForWebCase(String testCaseExternalId, String taskid, LogOperation caselog, WebDriver driver) throws InterruptedException {
Map<String, String> variable = new HashMap<>(0);
String expectedresults = null;
Integer setresult = 1;
String testnote = "初始化测试结果";
ProjectCase testcaseob = GetServerAPI.cgetCaseBysign(testCaseExternalId);
List<PublicCaseParams> pcplist = GetServerAPI.cgetParamsByProjectid(String.valueOf(testcaseob.getProjectid()));
// 把公共参数加入到MAP中
for (PublicCaseParams pcp : pcplist) {
variable.put(pcp.getParamsname(), pcp.getParamsvalue());
}
List<ProjectCasesteps> steps = GetServerAPI.getStepsbycaseid(testcaseob.getId());
if (steps.size() == 0) {
setresult = 2;
luckyclient.publicclass.LogUtil.APP.error("用例中未找到步骤,请检查!");
caselog.caseLogDetail(taskid, testcaseob.getSign(), "用例中未找到步骤,请检查!", "error", "1", "");
testnote = "用例中未找到步骤,请检查!";
}
// 进入循环解析用例所有步骤
for (ProjectCasesteps step : steps) {
Map<String, String> params;
String result;
// 根据步骤类型来分析步骤参数
if (1 == step.getSteptype()) params = WebDriverAnalyticCase.analyticCaseStep(testcaseob, step, taskid, caselog);
else params = InterfaceAnalyticCase.analyticCaseStep(testcaseob, step, taskid, caselog);
// 判断分析步骤参数是否有异常
if (params.get("exception") != null && params.get("exception").contains("解析异常")) {
setresult = 2;
break;
}
// 根据步骤类型来执行步骤
if (1 == step.getSteptype()) result = WebCaseExecution.runWebStep(params, variable, driver, taskid, testcaseob.getSign(), step.getStepnum(), caselog);
else result = WebCaseExecution.runStep(params, variable, taskid, testcaseob.getSign(), step, caselog);
expectedresults = params.get("ExpectedResults");
expectedresults = ChangString.changparams(expectedresults, variable, "预期结果");
// 判断结果
if (0 != (setresult = WebCaseExecution.judgeResult(testcaseob, step, params, driver, taskid, expectedresults, result, caselog))) break;
}
variable.clear(); // 清空传参MAP
if (0 == setresult) {
testnote = "调用用例【" + testcaseob.getSign() + "】执行成功!";
luckyclient.publicclass.LogUtil.APP.info("用例 " + testcaseob.getSign() + "步骤全部执行成功!");
} else {
testnote = "调用用例【" + testcaseob.getSign() + "】执行失败,请检查日志!";
luckyclient.publicclass.LogUtil.APP.error("用例 " + testcaseob.getSign() + "在执行过程中失败,请检查日志!");
}
return testnote;
}
}

View File

@ -24,7 +24,6 @@ public class InterfaceAnalyticCase{
private static String splitFlag = "\\|";
/**
* @param args
*/
@SuppressWarnings("finally")
public static Map<String,String> analyticCaseStep(ProjectCase projectcase,ProjectCasesteps step,String taskid,LogOperation caselog){
@ -69,7 +68,7 @@ public class InterfaceAnalyticCase{
caselog.caseLogDetail(taskid, projectcase.getSign(),"步骤编号:"+step.getStepnum()+" 解析自动化用例步骤脚本出错!","error",String.valueOf(step.getStepnum()),"");
}
luckyclient.publicclass.LogUtil.ERROR.error(e,e);
params.put("FunctionName","用例编号:"+projectcase.getSign()+"|解析异常,用例步骤为空或是用例脚本错误!");
params.put("exception","用例编号:"+projectcase.getSign()+"|解析异常,用例步骤为空或是用例脚本错误!");
return params;
}
return params;

View File

@ -1,371 +1,461 @@
package luckyclient.caserun.exwebdriver;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import luckyclient.caserun.exwebdriver.ocr.Ocr;
/**
* =================================================================
* 这是一个受限制的自由软件您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途也不允许对程序代码修改后以任何形式任何目的的再发布
* 为了尊重作者的劳动成果LuckyFrame关键版权信息严禁篡改
* 有任何疑问欢迎联系作者讨论 QQ:1573584944 seagull1985
* =================================================================
*
* @author seagull
* @date 2017年12月1日 上午9:29:40
*/
public class EncapsulateOperation {
public static String selectOperation(WebElement we, String operation, String operationValue) throws Exception {
String result = "";
// 下拉框对象处理
Select select = new Select(we);
// 处理下拉框事件
switch (operation) {
case "selectbyvisibletext":
select.selectByVisibleText(operationValue);
result = "下拉框对象通过VisibleText属性选择...【VisibleText属性值:" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info("下拉框对象通过VisibleText属性选择...【VisibleText属性值:" + operationValue + "");
break;
case "selectbyvalue":
select.selectByValue(operationValue);
result = "下拉框对象通过Value属性选择...【Value属性值:" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info("下拉框对象通过Value属性选择...【Value属性值:" + operationValue + "");
break;
case "selectbyindex":
select.selectByIndex(Integer.valueOf(operationValue));
result = "下拉框对象通过Index属性选择...【Index属性值:" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info("下拉框对象通过Index属性选择...【Index属性值:" + operationValue + "");
break;
case "isselect":
result = "获取到的值是【" + we.isSelected() + "";
luckyclient.publicclass.LogUtil.APP.info("判断对象是否已经被选择...【结果值:" + we.isSelected() + "");
break;
default:
break;
}
return result;
}
public static String getOperation(WebDriver wd, WebElement we, String operation, String value) throws Exception {
String result = "";
// 获取对象处理
switch (operation) {
case "gettext":
result = "获取到的值是【" + we.getText() + "";
luckyclient.publicclass.LogUtil.APP.info("getText获取对象text属性...【text属性值:" + result + "");
break; // 获取输入框内容
case "gettagname":
result = "获取到的值是【" + we.getTagName() + "";
luckyclient.publicclass.LogUtil.APP.info("getTagName获取对象tagname属性...【tagname属性值:" + result + "");
break;
case "getattribute":
result = "获取到的值是【" + we.getAttribute(value) + "";
luckyclient.publicclass.LogUtil.APP.info("getAttribute获取对象【" + value + "】属性...【" + value + "属性值:" + result + "");
break;
case "getcssvalue":
result = "获取到的值是【" + we.getCssValue(value) + "";
luckyclient.publicclass.LogUtil.APP.info("getCssValue获取对象【" + value + "】属性...【" + value + "属性值:" + result + "");
break;
case "getcaptcha":
result = "获取到的值是【" + Ocr.getCAPTCHA(wd, we) + "";
luckyclient.publicclass.LogUtil.APP.info("getcaptcha获取验证码...【验证码值:" + result + "");
break;
default:
break;
}
return result;
}
public static String actionWeOperation(WebDriver wd, WebElement we, String operation, String operationValue, String property, String propertyValue) throws Exception {
String result = "";
Actions action = new Actions(wd);
// action处理
switch (operation) {
//鼠标左键点击
case "mouselkclick":
action.click(we).perform();
result = "mouselkclick鼠标左键点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info("mouselkclick鼠标左键点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "");
break;
case "mouserkclick":
action.contextClick(we).perform();
result = "mouserkclick鼠标右键点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info("mouserkclick鼠标右键点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "");
break;
case "mousedclick":
action.doubleClick(we).perform();
result = "mousedclick鼠标双击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info("mousedclick鼠标双击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "");
break;
case "mouseclickhold":
action.clickAndHold(we).perform();
result = "mouseclickhold鼠标点击对象后不释放...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info("mouseclickhold鼠标点击对象后不释放...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "");
break;
case "mousedrag":
String[] temp = operationValue.split(",", -1);
action.dragAndDropBy(we, Integer.valueOf(temp[0]), Integer.valueOf(temp[1])).perform();
result = "mousedrag鼠标移动至对象相对坐标...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "】 坐标x" + Integer.valueOf(temp[0])
+ " 坐标y" + Integer.valueOf(temp[1]);
luckyclient.publicclass.LogUtil.APP.info("mousedrag鼠标移动至对象相对坐标...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "】 坐标x" + Integer.valueOf(temp[0])
+ " 坐标y" + Integer.valueOf(temp[1]));
break;
case "mouseto":
String[] temp1 = operationValue.split(",", -1);
action.moveToElement(we, Integer.valueOf(temp1[0]), Integer.valueOf(temp1[1])).perform();
result = "mouseto鼠标移动至对象相对坐标...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "】 坐标x" + Integer.valueOf(temp1[0])
+ " 坐标y" + Integer.valueOf(temp1[1]);
luckyclient.publicclass.LogUtil.APP.info("mouseto鼠标移动至对象相对坐标...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "】 坐标x" + Integer.valueOf(temp1[0])
+ " 坐标y" + Integer.valueOf(temp1[1]));
break;
case "mouserelease":
action.release(we).perform();
result = "mouserelease鼠标释放...";
luckyclient.publicclass.LogUtil.APP.info("mouserelease鼠标释放...");
break;
default:
break;
}
return result;
}
public static String actionOperation(WebDriver wd, String operation, String operationValue) throws Exception {
String result = "";
Actions action = new Actions(wd);
// action处理
switch (operation) {
//鼠标左键点击
case "mouselkclick":
action.click().perform();
result = "mouselkclick鼠标左键点击当前位置...";
luckyclient.publicclass.LogUtil.APP.info("mouselkclick鼠标左键点击当前位置...");
break;
case "mouserkclick":
action.contextClick().perform();
result = "mouserkclick鼠标右键点击当前位置...";
luckyclient.publicclass.LogUtil.APP.info("mouserkclick鼠标右键点击当前位置...");
break;
case "mousedclick":
action.doubleClick().perform();
result = "mousedclick鼠标双击当前位置...";
luckyclient.publicclass.LogUtil.APP.info("mousedclick鼠标双击当前位置...");
break;
case "mouseclickhold":
action.clickAndHold().perform();
result = "mouseclickhold鼠标点击当前位置后不释放...";
luckyclient.publicclass.LogUtil.APP.info("mouseclickhold鼠标点击当前位置后不释放...");
break;
case "mouseto":
String[] temp1 = operationValue.split(",", -1);
action.moveByOffset(Integer.valueOf(temp1[0]), Integer.valueOf(temp1[1])).perform();
result = "mouseto鼠标移动至对象相对坐标...坐标x" + Integer.valueOf(temp1[0])
+ " 坐标y" + Integer.valueOf(temp1[1]);
luckyclient.publicclass.LogUtil.APP.info("mouseto鼠标移动至对象相对坐标... 坐标x" + Integer.valueOf(temp1[0])
+ " 坐标y" + Integer.valueOf(temp1[1]));
break;
case "mouserelease":
action.release().perform();
result = "mouserelease鼠标释放...";
luckyclient.publicclass.LogUtil.APP.info("mouserelease鼠标释放...");
break;
case "mousekey":
switch (operationValue) {
case "tab":
action.sendKeys(Keys.TAB).perform();
result = "键盘操作TAB键...";
luckyclient.publicclass.LogUtil.APP.info("键盘操作TAB键...");
break;
case "space":
action.sendKeys(Keys.SPACE).perform();
result = "键盘操作SPACE键...";
luckyclient.publicclass.LogUtil.APP.info("键盘操作SPACE键...");
break;
case "ctrl":
action.sendKeys(Keys.CONTROL).perform();
result = "键盘操作CONTROL键...";
luckyclient.publicclass.LogUtil.APP.info("键盘操作CONTROL键...");
break;
case "shift":
action.sendKeys(Keys.SHIFT).perform();
result = "键盘操作SHIFT键...";
luckyclient.publicclass.LogUtil.APP.info("键盘操作SHIFT键...");
break;
case "enter":
action.sendKeys(Keys.ENTER).perform();
result = "键盘操作SHIFT键...";
luckyclient.publicclass.LogUtil.APP.info("键盘操作SHIFT键...");
break;
default:
break;
}
break;
default:
break;
}
return result;
}
public static String objectOperation(WebDriver wd, WebElement we, String operation, String operationValue, String property, String propertyValue) throws Exception {
String result = "";
// 处理WebElement对象操作
switch (operation) {
case "click":
we.click();
result = "click点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info("click点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "");
break;
case "sendkeys":
we.sendKeys(operationValue);
result = "sendKeys对象输入...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "; 操作值:" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info("sendkeys对象输入...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "; 操作值:" + operationValue + "");
break;
case "clear":
we.clear();
result = "clear清空输入框...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info("clear清空输入框...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "");
break; // 清空输入框
case "gotoframe":
wd.switchTo().frame(we);
result = "切换Frame...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info("gotoframe切换Frame...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "");
break;
case "isenabled":
result = "获取到的值是【" + we.isEnabled() + "";
luckyclient.publicclass.LogUtil.APP.info("当前对象判断是否可用布尔值为【" + we.isEnabled() + "");
break;
case "isdisplayed":
result = "获取到的值是【" + we.isDisplayed() + "";
luckyclient.publicclass.LogUtil.APP.info("当前对象判断是否可见布尔值为【" + we.isDisplayed() + "");
break;
case "exjsob":
JavascriptExecutor jse = (JavascriptExecutor) wd;
jse.executeScript(operationValue, we);
result = "执行JS...【" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info("执行JS...【" + operationValue + "");
break;
default:
break;
}
return result;
}
public static String alertOperation(WebDriver wd, String operation) throws Exception {
String result = "";
Alert alert = wd.switchTo().alert();
switch (operation) {
case "alertaccept":
alert.accept();
result = "弹出框对象点击同意...";
luckyclient.publicclass.LogUtil.APP.info("弹出框对象点击同意...");
break;
case "alertdismiss":
alert.dismiss();
result = "弹出框对象点击取消...";
luckyclient.publicclass.LogUtil.APP.info("弹出框对象点击取消...");
break;
case "alertgettext":
result = "获取到的值是【" + alert.getText() + "";
luckyclient.publicclass.LogUtil.APP.info("弹出框对象通过getText获取对象text属性...【Text属性值:" + alert.getText() + "");
break;
default:
break;
}
return result;
}
public static String driverOperation(WebDriver wd, String operation, String operationValue) throws Exception {
String result = "";
// 处理页面对象操作
switch (operation) {
case "open":
wd.get(operationValue);
result = "Open页面...【" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info("Open页面...【" + operationValue + "");
break;
case "exjs":
JavascriptExecutor jse = (JavascriptExecutor) wd;
jse.executeScript(operationValue);
result = "执行JS...【" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info("执行JS...【" + operationValue + "");
break;
case "gotodefaultcontent":
wd.switchTo().defaultContent();
result = "切换至默认页面位置...";
luckyclient.publicclass.LogUtil.APP.info("gotodefaultcontent切换至默认页面位置...");
break;
case "gettitle":
result = "获取到的值是【" + wd.getTitle() + "";
luckyclient.publicclass.LogUtil.APP.info("获取页面Title...【" + wd.getTitle() + "");
break;
case "getwindowhandle":
Set<String> handles = wd.getWindowHandles();
int handlenum = 1;
for (String handle : handles) {
if (String.valueOf(handlenum).equals(operationValue)) {
if (wd.getWindowHandle().equals(handle)) {
result = "请注意你指定的handle就是当前页面哦获取到的值是【" + handle + "";
} else {
result = "指定handles的顺序值值是" + operationValue + ",获取到的值是【" + handle + "";
}
break;
}
handlenum++;
}
luckyclient.publicclass.LogUtil.APP.info("getWindowHandle获取窗口句柄..." + result);
break;
case "gotowindow":
Set<String> gotohandles = wd.getWindowHandles();
int flag = 0;
for (String handleName : gotohandles) {
if (handleName.contains(operationValue)) {
flag = 1;
wd.switchTo().window(operationValue);
break;
}
}
if (flag == 1) {
result = "切换窗口句柄至【" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
} else {
result = "切换窗口失败,未找到句柄值为【" + operationValue + "】的对象";
luckyclient.publicclass.LogUtil.APP.info(result);
}
break;
case "timeout":
try {
//设置页面加载最大时长30秒
wd.manage().timeouts().pageLoadTimeout(Integer.valueOf(operationValue), TimeUnit.SECONDS);
//设置元素出现最大时长30秒
wd.manage().timeouts().implicitlyWait(Integer.valueOf(operationValue), TimeUnit.SECONDS);
result = "当前任务操作等待【" + operationValue + "】秒...";
luckyclient.publicclass.LogUtil.APP.info("当前任务操作等待【" + operationValue + "】秒...");
break;
} catch (NumberFormatException e) {
luckyclient.publicclass.LogUtil.APP.error("等待时间转换出错 ");
e.printStackTrace();
result = "【等待时间转换出错,请检查参数】";
break;
}
default:
break;
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
package luckyclient.caserun.exwebdriver;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import luckyclient.publicclass.ChangString;
import luckyclient.publicclass.LogUtil;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import luckyclient.caserun.exwebdriver.ocr.Ocr;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* =================================================================
* 这是一个受限制的自由软件您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途也不允许对程序代码修改后以任何形式任何目的的再发布
* 为了尊重作者的劳动成果LuckyFrame关键版权信息严禁篡改
* 有任何疑问欢迎联系作者讨论 QQ:1573584944 seagull1985
* =================================================================
*
* @author seagull
* @date 2017年12月1日 上午9:29:40
*/
public class EncapsulateOperation {
public static String selectOperation(WebElement we, String operation, String operationValue) throws Exception {
String result = "";
// 下拉框对象处理
Select select = new Select(we);
// 处理下拉框事件
switch (operation) {
case "selectbyvisibletext":
select.selectByVisibleText(operationValue);
result = "下拉框对象通过VisibleText属性选择...【VisibleText属性值:" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "selectbyvalue":
select.selectByValue(operationValue);
result = "下拉框对象通过Value属性选择...【Value属性值:" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "selectbyindex":
select.selectByIndex(Integer.valueOf(operationValue));
result = "下拉框对象通过Index属性选择...【Index属性值:" + operationValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "isselect":
result = "获取到的值是【" + we.isSelected() + "";
luckyclient.publicclass.LogUtil.APP.info("判断对象是否已经被选择...【结果值:" + we.isSelected() + "");
break;
default:
break;
}
return result;
}
public static String getOperation(WebDriver wd, WebElement we, String operation, String value) throws Exception {
String result = "";
// 获取对象处理
switch (operation) {
case "gettext":
result = "获取到的值是【" + we.getText() + "";
luckyclient.publicclass.LogUtil.APP.info("getText获取对象text属性...【text属性值:" + result + "");
break; // 获取输入框内容
case "gettagname":
result = "获取到的值是【" + we.getTagName() + "";
luckyclient.publicclass.LogUtil.APP.info("getTagName获取对象tagname属性...【tagname属性值:" + result + "");
break;
case "getattribute":
result = "获取到的值是【" + we.getAttribute(value) + "";
luckyclient.publicclass.LogUtil.APP.info("getAttribute获取对象【" + value + "】属性...【" + value + "属性值:" + result + "");
break;
case "getcssvalue":
result = "获取到的值是【" + we.getCssValue(value) + "";
luckyclient.publicclass.LogUtil.APP.info("getCssValue获取对象【" + value + "】属性...【" + value + "属性值:" + result + "");
break;
case "getcaptcha":
result = "获取到的值是【" + Ocr.getCAPTCHA(wd, we) + "";
luckyclient.publicclass.LogUtil.APP.info("getcaptcha获取验证码...【验证码值:" + result + "");
break;
default:
break;
}
return result;
}
public static String actionWeOperation(WebDriver wd, WebElement we, String operation, String operationValue, String property, String propertyValue) throws Exception {
String result = "";
Actions action = new Actions(wd);
// action处理
switch (operation) {
//鼠标左键点击
case "mouselkclick":
action.click(we).perform();
result = "mouselkclick鼠标左键点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouserkclick":
action.contextClick(we).perform();
result = "mouserkclick鼠标右键点击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mousedclick":
action.doubleClick(we).perform();
result = "mousedclick鼠标双击对象...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouseclickhold":
action.clickAndHold(we).perform();
result = "mouseclickhold鼠标点击对象后不释放...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mousedrag":
String[] temp = operationValue.split(",", -1);
action.dragAndDropBy(we, Integer.valueOf(temp[0]), Integer.valueOf(temp[1])).perform();
result = "mousedrag鼠标移动至对象相对坐标...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "】 坐标x" + Integer.valueOf(temp[0]) + " 坐标y" + Integer.valueOf(temp[1]);
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouseto":
String[] temp1 = operationValue.split(",", -1);
action.moveToElement(we, Integer.valueOf(temp1[0]), Integer.valueOf(temp1[1])).perform();
result = "mouseto鼠标移动至对象相对坐标...【对象定位属性:" + property + "; 定位属性值:" + propertyValue + "】 坐标x" + Integer.valueOf(temp1[0]) + " 坐标y" + Integer.valueOf(temp1[1]);
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouserelease":
action.release(we).perform();
result = "mouserelease鼠标释放...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
default:
break;
}
return result;
}
public static String actionOperation(WebDriver wd, String operation, String operationValue) throws Exception {
String result = "";
Actions action = new Actions(wd);
// action处理
switch (operation) {
//鼠标左键点击
case "mouselkclick":
action.click().perform();
result = "mouselkclick鼠标左键点击当前位置...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouserkclick":
action.contextClick().perform();
result = "mouserkclick鼠标右键点击当前位置...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mousedclick":
action.doubleClick().perform();
result = "mousedclick鼠标双击当前位置...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouseclickhold":
action.clickAndHold().perform();
result = "mouseclickhold鼠标点击当前位置后不释放...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouseto":
String[] temp1 = operationValue.split(",", -1);
action.moveByOffset(Integer.valueOf(temp1[0]), Integer.valueOf(temp1[1])).perform();
result = "mouseto鼠标移动至对象相对坐标...坐标x" + Integer.valueOf(temp1[0]) + " 坐标y" + Integer.valueOf(temp1[1]);
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mouserelease":
action.release().perform();
result = "mouserelease鼠标释放...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "mousekey":
switch (operationValue) {
case "tab":
action.sendKeys(Keys.TAB).perform();
result = "键盘操作TAB键...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "space":
action.sendKeys(Keys.SPACE).perform();
result = "键盘操作SPACE键...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "ctrl":
action.sendKeys(Keys.CONTROL).perform();
result = "键盘操作CONTROL键...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "shift":
action.sendKeys(Keys.SHIFT).perform();
result = "键盘操作SHIFT键...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "enter":
action.sendKeys(Keys.ENTER).perform();
result = "键盘操作SHIFT键...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
default:
break;
}
break;
default:
break;
}
return result;
}
public static String objectOperation(WebDriver wd, WebElement we, String operation, String operationValue, String property, String propertyValue) throws Exception {
String result = "";
// 处理WebElement对象操作
switch (operation) {
case "click":
we.click();
result = "click点击对象...【对象定位属性:"+property+"; 定位属性值:"+propertyValue+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "sendkeys":
we.sendKeys(operationValue);
result = "sendKeys对象输入...【对象定位属性:"+property+"; 定位属性值:"+propertyValue+"; 操作值:"+operationValue+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "clear":
we.clear();
result = "clear清空输入框...【对象定位属性:"+property+"; 定位属性值:"+propertyValue+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break; // 清空输入框
case "gotoframe":
wd.switchTo().frame(we);
result = "gotoframe切换Frame...【对象定位属性:"+property+"; 定位属性值:"+propertyValue+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "isenabled":
result = "获取到的值是【"+we.isEnabled()+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "isdisplayed":
result = "获取到的值是【"+we.isDisplayed()+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "exjsob":
JavascriptExecutor jse = (JavascriptExecutor) wd;
jse.executeScript(operationValue, we);
result = "执行JS...【"+operationValue+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
default:
break;
}
return result;
}
public static String alertOperation(WebDriver wd, String operation) throws Exception {
String result = "";
Alert alert = wd.switchTo().alert();
switch (operation) {
case "alertaccept":
alert.accept();
result = "弹出框对象点击同意...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "alertdismiss":
alert.dismiss();
result = "弹出框对象点击取消...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "alertgettext":
result = "获取到的值是【"+alert.getText()+"";
luckyclient.publicclass.LogUtil.APP.info("弹出框对象通过getText获取对象text属性...【Text属性值:" + alert.getText() + "");
break;
default:
break;
}
return result;
}
public static String driverOperation(WebDriver wd, String operation, String operationValue) throws Exception {
String result = "";
// 处理页面对象操作
switch (operation) {
case "open":
wd.get(operationValue);
result = "Open页面...【"+operationValue+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "exjs":
JavascriptExecutor jse = (JavascriptExecutor) wd;
jse.executeScript(operationValue);
result = "执行JS...【"+operationValue+"";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "gotodefaultcontent":
wd.switchTo().defaultContent();
result = "gotodefaultcontent切换至默认页面位置...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
case "gettitle":
result = "获取到的值是【"+wd.getTitle()+"";
luckyclient.publicclass.LogUtil.APP.info("获取页面Title...【"+wd.getTitle()+"");
break;
case "getwindowhandle":
result = getTargetWindowHandle(wd, operationValue);
break;
case "gotowindow":
result = switchToTargetWindow(wd, operationValue);
break;
case "timeout":
try {
// 设置页面加载最大时长30秒
wd.manage().timeouts().pageLoadTimeout(Integer.valueOf(operationValue), TimeUnit.SECONDS);
// 设置元素出现最大时长30秒
wd.manage().timeouts().implicitlyWait(Integer.valueOf(operationValue), TimeUnit.SECONDS);
result = "当前任务操作等待【"+operationValue+"】秒...";
luckyclient.publicclass.LogUtil.APP.info(result);
break;
} catch (NumberFormatException e) {
luckyclient.publicclass.LogUtil.APP.error("等待时间转换出错!");
e.printStackTrace();
result = "【等待时间转换出错,请检查参数】";
break;
}
default:
break;
}
return result;
}
// operationValue为目标窗口句柄的下标, 1开始; 小于等于0即获取当前窗口的句柄值
// 窗口句柄值都已CDwindow-开头, 可以作为预期结果的断言
private static String getTargetWindowHandle(WebDriver driver, String target) {
String result;
if (null != driver) {
if (! ChangString.isInteger(target)) {
result = windowHandleByTitle(driver, target);
} else {
int index = Integer.valueOf(target);
result = windowHandleByIndex(driver, index);
}
} else {
result = "获取窗口句柄值失败WebDriver为空";
}
if (result.contains("获取窗口句柄值失败")) LogUtil.APP.error(result);
else LogUtil.APP.info("获取窗口句柄值成功,目标窗口句柄值为【" + result + "");
return result;
}
private static String windowHandleByTitle(WebDriver driver, String title) {
String result = "";
String original = driver.getWindowHandle();
if (title.isEmpty()) {
result = original;
} else {
Set<String> windowHandles = driver.getWindowHandles();
for (String windowHandle : windowHandles) {
driver.switchTo().window(windowHandle);
if (title.equals(driver.getTitle())) {
result = windowHandle;
break;
}
}
if (0 < windowHandles.size()) driver.switchTo().window(original);
}
result = result.isEmpty() ? "获取窗口句柄值失败,需要获取窗口句柄值的标题【" + title + "】没有找到" : "获取到的值是【" + result + "";
return result;
}
private static String windowHandleByIndex(WebDriver driver, int index) {
String result;
try {
List<String> windowHandles = new ArrayList<>(driver.getWindowHandles());
if (index > windowHandles.size()) {
result = "获取窗口句柄值失败,需要获取窗口句柄值的下标【" + index + "】大于当前窗口句柄总数【" + windowHandles.size() + "";
} else {
if (0 >= index) result = "获取到的值是【" + driver.getWindowHandle() + "";
else result = "获取到的值是【" + windowHandles.get(index - 1) + "";
}
} catch (IndexOutOfBoundsException e) {
result = "获取窗口句柄值失败,需要获取窗口句柄值的下标【" + index + "】越界";
}
return result;
}
// 最长等待30秒, 每500毫秒轮询一次
private static FluentWait<WebDriver> Wait(WebDriver driver) {
return new FluentWait<>(driver).withTimeout(30 * 1000, MILLISECONDS).pollingEvery(500, MILLISECONDS);
}
private static ExpectedCondition<WebDriver> windowToBeAvailableAndSwitchToIt(final String nameOrHandleOrTitle) {
return driver -> {
try {
if (null != driver)
return driver.switchTo().window(nameOrHandleOrTitle);
else
return null;
} catch (NoSuchWindowException windowWithNameOrHandleNotFound) {
try {
return windowByTitle(driver, nameOrHandleOrTitle);
} catch (NoSuchWindowException windowWithTitleNotFound) {
if (ChangString.isInteger(nameOrHandleOrTitle))
return windowByIndex(driver, Integer.valueOf(nameOrHandleOrTitle));
else
return null;
}
}
};
}
private static WebDriver windowByTitle(WebDriver driver, String title) {
String original = driver.getWindowHandle();
Set<String> windowHandles = driver.getWindowHandles();
for (String windowHandle : windowHandles) {
driver.switchTo().window(windowHandle);
if (title.equals(driver.getTitle())) {
return driver;
}
}
if (0 < windowHandles.size()) driver.switchTo().window(original);
throw new NoSuchWindowException("Window with title[" + title + "] not found");
}
private static WebDriver windowByIndex(WebDriver driver, int index) {
try {
List<String> windowHandles = new ArrayList<>(driver.getWindowHandles());
return driver.switchTo().window(windowHandles.get(index));
} catch (IndexOutOfBoundsException windowWithIndexNotFound) {
return null;
}
}
private static String switchToTargetWindow(WebDriver driver, String target) {
String result;
try {
if (null == Wait(driver).until(windowToBeAvailableAndSwitchToIt(target))) {
result = "切换窗口句柄失败,未找到句柄值为【" + target + "】的对象";
LogUtil.APP.error(result);
} else {
result = "切换窗口句柄成功,找到句柄值为【" + target + "】的对象";
LogUtil.APP.info(result);
}
return result;
} catch (TimeoutException e) {
result = "切换窗口句柄失败,等待超时,未找到句柄值为【" + target + "】的对象";
LogUtil.APP.error(result);
return result;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}

View File

@ -7,6 +7,9 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import luckyclient.caserun.exinterface.analyticsteps.InterfaceAnalyticCase;
import luckyclient.publicclass.InvokeMethod;
import luckyclient.publicclass.LogUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
@ -32,6 +35,10 @@ import luckyclient.publicclass.ChangString;
*/
public class WebCaseExecution extends TestCaseExecution {
private static Map<String, String> variable = new HashMap<>();
// 0:成功 1:失败 2:锁定 其他锁定
private static int setresult = 0;
private static String casenote = "备注初始化";
private static String imagname = "";
/*
public static void caseExcutionBak(ProjectCase testcase, List<ProjectCasesteps> steps, String taskid, WebDriver wd, LogOperation caselog, List<PublicCaseParams> pcplist)
@ -172,12 +179,7 @@ public class WebCaseExecution extends TestCaseExecution {
}
*/
public static void caseExcution(ProjectCase testcase, List<ProjectCasesteps> steps, String taskid, WebDriver wd, LogOperation caselog, List<PublicCaseParams> pcplist)
throws InterruptedException {
// 0:成功 1:失败 2:锁定 其他锁定
int setresult = 0;
String casenote = "备注初始化";
String imagname = "";
public static void caseExcution(ProjectCase testcase, List<ProjectCasesteps> steps, String taskid, WebDriver wd, LogOperation caselog, List<PublicCaseParams> pcplist) throws InterruptedException {
// 把公共参数加入到MAP中
for (PublicCaseParams pcp : pcplist) {
variable.put(pcp.getParamsname(), pcp.getParamsvalue());
@ -186,120 +188,28 @@ public class WebCaseExecution extends TestCaseExecution {
caselog.addCaseDetail(taskid, testcase.getSign(), "1", testcase.getName(), 4);
for (ProjectCasesteps step : steps) {
Map<String, String> params = WebDriverAnalyticCase.analyticCaseStep(testcase, step, taskid, caselog);
Map<String, String> params;
String result;
// 根据步骤类型来分析步骤参数
if (1 == step.getSteptype()) params = WebDriverAnalyticCase.analyticCaseStep(testcase, step, taskid, caselog);
else params = InterfaceAnalyticCase.analyticCaseStep(testcase, step, taskid, caselog);
// 判断分析步骤参数是否有异常
if (params.get("exception") != null && params.get("exception").contains("解析异常")) {
setresult = 2;
break;
}
String result = WebCaseExecution.runStep(params, wd, taskid, testcase.getSign(), step.getStepnum(), caselog);
// 根据步骤类型来执行步骤
if (1 == step.getSteptype()) result = runWebStep(params, variable, wd, taskid, testcase.getSign(), step.getStepnum(), caselog);
else result = runStep(params, variable, taskid, testcase.getSign(), step, caselog);
String expectedResults = params.get("ExpectedResults");
expectedResults = ChangString.changparams(expectedResults, variable, "预期结果");
// 运行结果正常
if (null != result && !result.contains("出错") && !result.contains("失败")) {
// 获取步骤间等待时间
int waitsec = Integer.parseInt(params.get("StepWait"));
if (waitsec > 0) {
luckyclient.publicclass.LogUtil.APP.info("操作休眠【" + waitsec + "】秒");
Thread.sleep(waitsec * 1000);
}
// 有预期结果
if (null != expectedResults && !expectedResults.isEmpty()) {
luckyclient.publicclass.LogUtil.APP.info("expectedResults=【" + expectedResults + "");
// 赋值传参模式
if (expectedResults.length() > ASSIGNMENT_SIGN.length() && expectedResults.startsWith(ASSIGNMENT_SIGN)) {
variable.put(expectedResults.substring(ASSIGNMENT_SIGN.length()), result);
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,将测试结果【" + result + "】赋值给变量【" + expectedResults.substring(ASSIGNMENT_SIGN.length()) + "");
caselog.caseLogDetail(taskid, testcase.getSign(), "将测试结果【" + result + "】赋值给变量【" + expectedResults.substring(ASSIGNMENT_SIGN.length()) + "", "info", String.valueOf(step.getStepnum()), "");
}
// WebUI检查模式
else if (params.get("checkproperty") != null && params.get("checkproperty_value") != null) {
String checkproperty = params.get("checkproperty");
String checkPropertyValue = params.get("checkproperty_value");
WebElement we = isElementExist(wd, checkproperty, checkPropertyValue);
if (null != we) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,在当前页面中找到预期结果中对象。当前步骤执行成功!");
caselog.caseLogDetail(taskid, testcase.getSign(), "在当前页面中找到预期结果中对象。当前步骤执行成功!", "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,没有在当前页面中找到预期结果中对象。执行失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(wd, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,没有在当前页面中找到预期结果中对象。当前步骤执行失败!");
caselog.caseLogDetail(taskid, testcase.getSign(), "在当前页面中没有找到预期结果中对象。当前步骤执行失败!" + "checkproperty【" + checkproperty + "】 checkproperty_value【" + checkPropertyValue + "", "error", String.valueOf(step.getStepnum()), imagname);
break;
}
}
// 其它匹配模式
else {
// 模糊匹配预期结果模式
if (expectedResults.length() > FUZZY_MATCHING_SIGN.length() && expectedResults.startsWith(FUZZY_MATCHING_SIGN)) {
if (result.contains(expectedResults.substring(FUZZY_MATCHING_SIGN.length()))) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,模糊匹配预期结果成功!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "模糊匹配预期结果成功!执行结果:" + result, "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,模糊匹配预期结果失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(wd, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,模糊匹配预期结果失败!预期结果:" + expectedResults.substring(FUZZY_MATCHING_SIGN.length()) + ",测试结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "模糊匹配预期结果失败!预期结果:" + expectedResults.substring(FUZZY_MATCHING_SIGN.length()) + ",测试结果:" + result, "error", String.valueOf(step.getStepnum()), imagname);
break;
}
}
// 正则匹配预期结果模式
else if (expectedResults.length() > REGULAR_MATCHING_SIGN.length() && expectedResults.startsWith(REGULAR_MATCHING_SIGN)) {
Pattern pattern = Pattern.compile(expectedResults.substring(REGULAR_MATCHING_SIGN.length()));
Matcher matcher = pattern.matcher(result);
if (matcher.find()) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,正则匹配预期结果成功!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "正则匹配预期结果成功!", "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,正则匹配预期结果失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(wd, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,正则匹配预期结果失败!预期结果:" + expectedResults.substring(REGULAR_MATCHING_SIGN.length()) + ",测试结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "正则匹配预期结果失败!预期结果:" + expectedResults.substring(REGULAR_MATCHING_SIGN.length()) + ",测试结果:" + result, "error", String.valueOf(step.getStepnum()), imagname);
break;
}
}
// 精确匹配预期结果模式
else {
if (expectedResults.equals(result)) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,精确匹配预期结果成功!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "精确匹配预期结果成功!", "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,精确匹配预期结果失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(wd, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,精确匹配预期结果失败!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "精确匹配预期结果失败!执行结果:" + result, "error", String.valueOf(step.getStepnum()), imagname);
break;
}
}
}
}
} else {
casenote = (null != result) ? result : "";
setresult = 2;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(wd, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步," + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "当前步骤在执行过程中解析|定位元素|操作对象失败!" + result,
"error", String.valueOf(step.getStepnum()), imagname);
break;
}
// 判断结果
if (0 != judgeResult(testcase, step, params, wd, taskid, expectedResults, result, caselog)) break;
}
variable.clear();
@ -311,10 +221,9 @@ public class WebCaseExecution extends TestCaseExecution {
luckyclient.publicclass.LogUtil.APP.error("用例【" + testcase.getSign() + "】步骤执行过程中失败或是锁定...请查看具体原因!" + casenote);
caselog.caseLogDetail(taskid, testcase.getSign(), "用例执行过程中失败或是锁定" + casenote, "error", "ending", "");
}
//LogOperation.UpdateTastdetail(taskid, 0);
}
private static String runStep(Map<String, String> params, WebDriver wd, String taskid, String casenum, int stepno, LogOperation caselog) {
public static String runWebStep(Map<String, String> params, Map<String, String> variable, WebDriver wd, String taskid, String casenum, int stepno, LogOperation caselog) {
String result = "";
String property;
String propertyValue;
@ -345,17 +254,18 @@ public class WebCaseExecution extends TestCaseExecution {
//调用接口用例
if (null != operation && null != operationValue && "runcase".equals(operation)) {
String[] temp = operationValue.split(",", -1);
String ex = TestCaseExecution.oneCaseExecuteForWebDriver(temp[0], taskid, caselog);
if (ex.indexOf("CallCase调用出错") <= -1 && ex.indexOf("解析出错啦!") <= -1 && ex.indexOf("匹配失败") <= -1) {
String ex = TestCaseExecution.oneCaseExecuteForWebCase(temp[0], taskid, caselog, wd);
// String ex = TestCaseExecution.oneCaseExecuteForWebDriver(temp[0], taskid, caselog);
if (!ex.contains("CallCase调用出错") && !ex.contains("解析出错啦!") && !ex.contains("失败")) {
return ex;
} else {
return "调用接口用例过程失败";
return "调用外部用例过程失败";
}
}
WebElement we = null;
// 页面元素层
if (null != property && null != propertyValue) {
if (null != property && null != propertyValue && null != operation) {
we = isElementExist(wd, property, propertyValue);
// 判断此元素是否存在
if (null == we) {
@ -363,11 +273,11 @@ public class WebCaseExecution extends TestCaseExecution {
return "isElementExist定位元素过程失败";
}
if (operation.indexOf("select") > -1) {
if (operation.contains("select")) {
result = EncapsulateOperation.selectOperation(we, operation, operationValue);
} else if (operation.indexOf("get") > -1) {
} else if (operation.contains("get")) {
result = EncapsulateOperation.getOperation(wd, we, operation, operationValue);
} else if (operation.indexOf("mouse") > -1) {
} else if (operation.contains("mouse")) {
result = EncapsulateOperation.actionWeOperation(wd, we, operation, operationValue, property, propertyValue);
} else {
result = EncapsulateOperation.objectOperation(wd, we, operation, operationValue, property, propertyValue);
@ -375,9 +285,9 @@ public class WebCaseExecution extends TestCaseExecution {
// Driver层操作
} else if (null == property && null != operation) {
// 处理弹出框事件
if (operation.indexOf("alert") > -1) {
if (operation.contains("alert")) {
result = EncapsulateOperation.alertOperation(wd, operation);
} else if (operation.indexOf("mouse") > -1) {
} else if (operation.contains("mouse")) {
result = EncapsulateOperation.actionOperation(wd, operation, operationValue);
} else {
result = EncapsulateOperation.driverOperation(wd, operation, operationValue);
@ -390,16 +300,68 @@ public class WebCaseExecution extends TestCaseExecution {
luckyclient.publicclass.LogUtil.APP.error("元素定位过程或是操作过程失败或异常!" + e.getMessage());
return "元素定位过程或是操作过程失败或异常!" + e.getMessage();
}
caselog.caseLogDetail(taskid, casenum, result, "info", String.valueOf(stepno), "");
if (result.indexOf("获取到的值是【") > -1 && result.indexOf("") > -1) {
if (result.contains("失败")) caselog.caseLogDetail(taskid, casenum, result, "error", String.valueOf(stepno), "");
else caselog.caseLogDetail(taskid, casenum, result, "info", String.valueOf(stepno), "");
if (result.contains("获取到的值是【") && result.contains("")) {
result = result.substring(7, result.length() - 1);
}
return result;
}
public static WebElement isElementExist(WebDriver wd, String property, String propertyValue) {
public static String runStep(Map<String, String> params, Map<String, String> variable, String taskid, String casenum, ProjectCasesteps step, LogOperation caselog) {
String result = "";
String packagename = "";
String functionname = "";
Object[] getParameterValues = null;
try {
packagename = params.get("PackageName");
packagename = ChangString.changparams(packagename, variable, "包路径");
functionname = params.get("FunctionName");
functionname = ChangString.changparams(functionname, variable, "方法名");
if (null != functionname && functionname.contains("解析异常")) {
LogUtil.APP.error("用例: " + casenum + ", 解析这个方法【" + functionname + "】失败!");
caselog.caseLogDetail(taskid, casenum, "用例: " + casenum + ", 解析这个方法【" + functionname + "】失败!", "error", String.valueOf(step.getStepnum()), "");
return "解析用例失败!";
}
// 判断方法是否带参数
if (params.size() > 4) {
// 获取传入参数放入对象中
getParameterValues = new Object[params.size() - 4];
for (int j = 0; j < params.size() - 4; j++) {
if (params.get("FunctionParams" + (j + 1)) == null) {
break;
}
String parameterValues = params.get("FunctionParams" + (j + 1));
parameterValues = ChangString.changparams(parameterValues, variable, "用例参数");
luckyclient.publicclass.LogUtil.APP.info("用例: " + casenum + ", 解析包路径:" + packagename + "; 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues);
caselog.caseLogDetail(taskid, casenum, "用例: " + casenum + ", 解析包名:" + packagename + " 方法名:" + functionname + "" + (j + 1) + "个参数:" + parameterValues, "info", String.valueOf(step.getStepnum()), "");
getParameterValues[j] = parameterValues;
}
} else {
getParameterValues = null;
}
LogUtil.APP.info("二次解析用例过程完成,等待进行接口操作......");
caselog.caseLogDetail(taskid, casenum, "包路径: " + packagename + "; 方法名: " + functionname, "info", String.valueOf(step.getStepnum()), "");
result = InvokeMethod.callCase(packagename, functionname, getParameterValues, step.getSteptype(), step.getAction());
} catch (Exception e) {
LogUtil.APP.error("调用方法过程出错,方法名:" + functionname + ",请重新检查脚本方法名称以及参数!");
return "接口调用出错!";
}
if (result.contains("调用异常")) caselog.caseLogDetail(taskid, casenum, result, "error", String.valueOf(step.getStepnum()), "");
else caselog.caseLogDetail(taskid, casenum, result, "info", String.valueOf(step.getStepnum()), "");
return result;
}
private static WebElement isElementExist(WebDriver wd, String property, String propertyValue) {
try {
WebElement we = null;
property = property.toLowerCase();
@ -436,6 +398,107 @@ public class WebCaseExecution extends TestCaseExecution {
}
public static int judgeResult(ProjectCase testcase, ProjectCasesteps step, Map<String, String> params, WebDriver driver, String taskid, String expect, String result, LogOperation caselog) throws InterruptedException {
setresult = 0;
if (null != result && !result.contains("出错") && !result.contains("失败")) {
// 获取步骤间等待时间
int waitsec = Integer.parseInt(params.get("StepWait"));
if (waitsec > 0) {
luckyclient.publicclass.LogUtil.APP.info("操作休眠【" + waitsec + "】秒");
Thread.sleep(waitsec * 1000);
}
// 有预期结果
if (null != expect && !expect.isEmpty()) {
luckyclient.publicclass.LogUtil.APP.info("期望结果为【" + expect + "");
// 赋值传参模式
if (expect.length() > ASSIGNMENT_SIGN.length() && expect.startsWith(ASSIGNMENT_SIGN)) {
variable.put(expect.substring(ASSIGNMENT_SIGN.length()), result);
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,将测试结果【" + result + "】赋值给变量【" + expect.substring(ASSIGNMENT_SIGN.length()) + "");
caselog.caseLogDetail(taskid, testcase.getSign(), "将测试结果【" + result + "】赋值给变量【" + expect.substring(ASSIGNMENT_SIGN.length()) + "", "info", String.valueOf(step.getStepnum()), "");
}
// WebUI检查模式
else if (1 == step.getSteptype() && params.get("checkproperty") != null && params.get("checkproperty_value") != null) {
String checkproperty = params.get("checkproperty");
String checkPropertyValue = params.get("checkproperty_value");
WebElement we = isElementExist(driver, checkproperty, checkPropertyValue);
if (null != we) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,在当前页面中找到预期结果中对象。当前步骤执行成功!");
caselog.caseLogDetail(taskid, testcase.getSign(), "在当前页面中找到预期结果中对象。当前步骤执行成功!", "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,没有在当前页面中找到预期结果中对象。执行失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(driver, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,没有在当前页面中找到预期结果中对象。当前步骤执行失败!");
caselog.caseLogDetail(taskid, testcase.getSign(), "在当前页面中没有找到预期结果中对象。当前步骤执行失败!" + "checkproperty【" + checkproperty + "】 checkproperty_value【" + checkPropertyValue + "", "error", String.valueOf(step.getStepnum()), imagname);
}
}
// 其它匹配模式
else {
// 模糊匹配预期结果模式
if (expect.length() > FUZZY_MATCHING_SIGN.length() && expect.startsWith(FUZZY_MATCHING_SIGN)) {
if (result.contains(expect.substring(FUZZY_MATCHING_SIGN.length()))) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,模糊匹配预期结果成功!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "模糊匹配预期结果成功!执行结果:" + result, "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,模糊匹配预期结果失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(driver, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,模糊匹配预期结果失败!预期结果:" + expect.substring(FUZZY_MATCHING_SIGN.length()) + ",测试结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "模糊匹配预期结果失败!预期结果:" + expect.substring(FUZZY_MATCHING_SIGN.length()) + ",测试结果:" + result, "error", String.valueOf(step.getStepnum()), imagname);
}
}
// 正则匹配预期结果模式
else if (expect.length() > REGULAR_MATCHING_SIGN.length() && expect.startsWith(REGULAR_MATCHING_SIGN)) {
Pattern pattern = Pattern.compile(expect.substring(REGULAR_MATCHING_SIGN.length()));
Matcher matcher = pattern.matcher(result);
if (matcher.find()) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,正则匹配预期结果成功!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "正则匹配预期结果成功!", "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,正则匹配预期结果失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(driver, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,正则匹配预期结果失败!预期结果:" + expect.substring(REGULAR_MATCHING_SIGN.length()) + ",测试结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "正则匹配预期结果失败!预期结果:" + expect.substring(REGULAR_MATCHING_SIGN.length()) + ",测试结果:" + result, "error", String.valueOf(step.getStepnum()), imagname);
}
}
// 精确匹配预期结果模式
else {
if (expect.equals(result)) {
luckyclient.publicclass.LogUtil.APP.info("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,精确匹配预期结果成功!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "精确匹配预期结果成功!", "info", String.valueOf(step.getStepnum()), "");
} else {
casenote = "" + step.getStepnum() + "步,精确匹配预期结果失败!";
setresult = 1;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(driver, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,精确匹配预期结果失败!执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "精确匹配预期结果失败!执行结果:" + result, "error", String.valueOf(step.getStepnum()), imagname);
}
}
}
}
} else {
casenote = (null != result) ? result : "";
setresult = 2;
java.text.DateFormat timeformat = new java.text.SimpleDateFormat("MMdd-hhmmss");
imagname = timeformat.format(new Date());
BaseWebDrive.webScreenShot(driver, imagname);
luckyclient.publicclass.LogUtil.APP.error("用例:" + testcase.getSign() + "" + step.getStepnum() + "步,执行结果:" + result);
caselog.caseLogDetail(taskid, testcase.getSign(), "当前步骤在执行过程中解析|定位元素|操作对象失败!" + result, "error", String.valueOf(step.getStepnum()), imagname);
}
return setresult;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}

View File

@ -1,6 +1,7 @@
package luckyclient.publicclass;
import java.util.Map;
import java.util.regex.Pattern;
/**
* =================================================================
@ -8,83 +9,87 @@ import java.util.Map;
* 为了尊重作者的劳动成果LuckyFrame关键版权信息严禁篡改
* 有任何疑问欢迎联系作者讨论 QQ:1573584944 seagull1985
* =================================================================
*
*
* @author seagull
* @date 2017年12月1日 上午9:29:40
*
*/
public class ChangString {
public static String changparams(String str,Map<String,String> variable,String changname){
try{
if(null==str){
return null;
}
str = str.replaceAll("&quot;", "\"");
str = str.replaceAll("&#39;", "\'");
//@@用来注释@的引用作用
int varcount=counter(str,"@")-counter(str,"@@")*2;
public static String changparams(String str, Map<String, String> variable, String changname) {
try {
if (null == str) {
return null;
}
str = str.replaceAll("&quot;", "\"");
str = str.replaceAll("&#39;", "\'");
//@@用来注释@的引用作用
int varcount = counter(str, "@") - counter(str, "@@") * 2;
//如果存在传参进行处理
if(varcount>0){
luckyclient.publicclass.LogUtil.APP.info(""+changname+""+str+"】中找到"+varcount+"个可替换参数");
int changcount=0;
//从参数列表中查找匹配变量
for (Map.Entry<String, String> entry : variable.entrySet()) {
if(str.indexOf("@"+entry.getKey())>-1){
if(str.indexOf("@@"+entry.getKey())>-1){
str=str.replaceAll("@@"+entry.getKey(), "////CHANG////");
}
//用来替换字符串中带了\"或是\'会导致\消失的问题
entry.setValue(entry.getValue().replaceAll("\\\\\"", "\\&quot;"));
entry.setValue(entry.getValue().replaceAll("\\\\\'", "\\\\&#39;"));
int viewcount=counter(str,"@"+entry.getKey());
str=str.replaceAll("@"+entry.getKey(), entry.getValue());
luckyclient.publicclass.LogUtil.APP.info(""+changname+"引用变量【@"+entry.getKey()+"】替换成值【"+entry.getValue()+"");
str=str.replaceAll("////CHANG////","@@"+entry.getKey());
changcount=changcount+viewcount;
}
}
if(varcount!=changcount){
luckyclient.publicclass.LogUtil.APP.error(changname+"有引用变量未在参数列中找到,请检查!处理结果【"+str+"");
}
}
str=str.replaceAll("@@","@");
//用来恢复字符串中带了\"或是\'会导致\消失的问题
str = str.replaceAll("\\&quot;", "\\\\\"");
str = str.replaceAll("\\&#39;", "\\\\\'");
return str;
}catch(Exception e){
e.printStackTrace();
return "";
}
}
public static int counter(String str1,String str2){
int total = 0;
for (String tmp = str1; tmp != null&&tmp.length()>=str2.length();){
if(tmp.indexOf(str2) == 0){
total ++;
tmp = tmp.substring(str2.length());
}else{
tmp = tmp.substring(1);
}
}
return total;
}
public static boolean isNumeric(String str){
for (int i = 0; i < str.length(); i++){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
public static void main(String[] args) {
//如果存在传参进行处理
if (varcount > 0) {
luckyclient.publicclass.LogUtil.APP.info("" + changname + "" + str + "】中找到" + varcount + "个可替换参数");
int changcount = 0;
//从参数列表中查找匹配变量
for (Map.Entry<String, String> entry : variable.entrySet()) {
if (str.indexOf("@" + entry.getKey()) > -1) {
if (str.indexOf("@@" + entry.getKey()) > -1) {
str = str.replaceAll("@@" + entry.getKey(), "////CHANG////");
}
//用来替换字符串中带了\"或是\'会导致\消失的问题
entry.setValue(entry.getValue().replaceAll("\\\\\"", "\\&quot;"));
entry.setValue(entry.getValue().replaceAll("\\\\\'", "\\\\&#39;"));
int viewcount = counter(str, "@" + entry.getKey());
str = str.replaceAll("@" + entry.getKey(), entry.getValue());
luckyclient.publicclass.LogUtil.APP.info("" + changname + "引用变量【@" + entry.getKey() + "】替换成值【" + entry.getValue() + "");
str = str.replaceAll("////CHANG////", "@@" + entry.getKey());
changcount = changcount + viewcount;
}
}
}
if (varcount != changcount) {
luckyclient.publicclass.LogUtil.APP.error(changname + "有引用变量未在参数列中找到,请检查!处理结果【" + str + "");
}
}
str = str.replaceAll("@@", "@");
//用来恢复字符串中带了\"或是\'会导致\消失的问题
str = str.replaceAll("\\&quot;", "\\\\\"");
str = str.replaceAll("\\&#39;", "\\\\\'");
return str;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static int counter(String str1, String str2) {
int total = 0;
for (String tmp = str1; tmp != null && tmp.length() >= str2.length(); ) {
if (tmp.indexOf(str2) == 0) {
total++;
tmp = tmp.substring(str2.length());
} else {
tmp = tmp.substring(1);
}
}
return total;
}
public static boolean isNumeric(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
public static void main(String[] args) {
}
}

View File

@ -20,353 +20,322 @@ import net.sf.json.JsonConfig;
* 为了尊重作者的劳动成果LuckyFrame关键版权信息严禁篡改
* 有任何疑问欢迎联系作者讨论 QQ:1573584944 seagull1985
* =================================================================
*
*
* @ClassName: InvokeMethod
* @Description: 动态调用方法
* @Description: 动态调用方法
* @author seagull
* @date 2017年9月24日 上午9:29:40
*
*/
public class InvokeMethod {
/**
* @param args
* @throws Throwable
*/
public static String callCase(String packagename, String functionname, Object[] getParameterValues, int steptype,
String action) {
String result = "调用异常,请查看错误日志!";
try {
if (steptype == 0) {
// 调用非静态方法用到
Object server = Class.forName(packagename).newInstance();
@SuppressWarnings("rawtypes")
Class[] getParameterTypes = null;
if (getParameterValues != null) {
int paramscount = getParameterValues.length;
// 赋值数组定义类型
getParameterTypes = new Class[paramscount];
for (int i = 0; i < paramscount; i++) {
getParameterTypes[i] = String.class;
}
}
Method method = getMethod(server.getClass().getMethods(), functionname, getParameterTypes);
if (method == null) {
throw new Exception(
"客户端本地驱动目录下没有在包名为【" + packagename + "】中找到被调用的方法【" + functionname + "】,请检查方法名称以及参数个数是否一致!");
}
Object str = method.invoke(server, getParameterValues);
if (str == null) {
result = "返回结果是null";
} else {
result = str.toString();
}
} else if (steptype == 2) {
String templateidstr = action.substring(1, action.indexOf(""));
String templatenamestr = action.substring(action.indexOf("") + 1);
luckyclient.publicclass.LogUtil.APP
.info("即将使用模板【" + templatenamestr + "】 ID:【" + templateidstr + "】 发送HTTP请求");
/**
* @throws Throwable
*/
public static String callCase(String packagename, String functionname, Object[] getParameterValues, int steptype, String action) {
String result = "调用异常,请查看错误日志!";
try {
if (steptype == 0) {
// 调用非静态方法用到
Object server = Class.forName(packagename).newInstance();
@SuppressWarnings("rawtypes")
Class[] getParameterTypes = null;
if (getParameterValues != null) {
int paramscount = getParameterValues.length;
// 赋值数组定义类型
getParameterTypes = new Class[paramscount];
for (int i = 0; i < paramscount; i++) {
getParameterTypes[i] = String.class;
}
}
Method method = getMethod(server.getClass().getMethods(), functionname, getParameterTypes);
if (method == null) {
throw new Exception("客户端本地驱动目录下没有在包名为【" + packagename + "】中找到被调用的方法【" + functionname + "】,请检查方法名称以及参数个数是否一致!");
}
Object str = method.invoke(server, getParameterValues);
if (str == null) {
result = "调用异常返回结果是null";
} else {
result = str.toString();
}
} else if (steptype == 2) {
String templateidstr = action.substring(1, action.indexOf(""));
String templatenamestr = action.substring(action.indexOf("") + 1);
luckyclient.publicclass.LogUtil.APP.info("即将使用模板【" + templatenamestr + "ID【" + templateidstr + "】发送HTTP请求");
String httpppt = HttpRequest
.loadJSON("/projectprotocolTemplate/cgetPTemplateById.do?templateid=" + templateidstr);
JSONObject jsonpptObject = JSONObject.fromObject(httpppt.toString());
ProjectProtocolTemplate ppt = (ProjectProtocolTemplate) JSONObject.toBean(jsonpptObject,
ProjectProtocolTemplate.class);
if(null==ppt){
luckyclient.publicclass.LogUtil.APP.error("协议模板为空,请检查用例使用的协议模板是否已经删除!");
return "协议模板为空,请确认用例使用的模板是否已经删除!";
}
String httpppt = HttpRequest.loadJSON("/projectprotocolTemplate/cgetPTemplateById.do?templateid=" + templateidstr);
JSONObject jsonpptObject = JSONObject.fromObject(httpppt);
ProjectProtocolTemplate ppt = (ProjectProtocolTemplate) JSONObject.toBean(jsonpptObject,
ProjectProtocolTemplate.class);
if (null == ppt) {
luckyclient.publicclass.LogUtil.APP.error("协议模板为空,请检查用例使用的协议模板是否已经删除!");
return "协议模板为空,请确认用例使用的模板是否已经删除!";
}
String httpptp = HttpRequest
.loadJSON("/projectTemplateParams/cgetParamsByTemplate.do?templateid=" + templateidstr);
JSONObject jsonptpObject = JSONObject.fromObject(httpptp.toString());
JSONArray jsonarr = JSONArray.fromObject(jsonptpObject.getString("params"));
//处理json-lib 2.4版本当遇到json格式字符串时把它当成对象处理的bug
for(int i=0;i<jsonarr.size();i++){
JSONObject tempobj=(JSONObject) jsonarr.get(i);
String str=tempobj.get("param").toString();
if(str.length()>0&&"[".equals(str.substring(0, 1))&&"]".equals(str.substring(str.length()-1))){
tempobj.element("param", "***"+str);
jsonarr.set(i, tempobj);
}
}
//处理头域
Map<String, String> headmsg = new HashMap<String, String>(0);
if(null!=ppt.getHeadmsg()&&!ppt.getHeadmsg().equals("")&&ppt.getHeadmsg().indexOf("=")>0){
String[] temp=ppt.getHeadmsg().split(";",-1);
for(int i=0;i<temp.length;i++){
if(null!=temp[i]&&!temp[i].equals("")&&temp[i].indexOf("=")>0){
String key=temp[i].substring(0, temp[i].indexOf("="));
String value=temp[i].substring(temp[i].indexOf("=")+1);
headmsg.put(key, value);
}
}
}
@SuppressWarnings("unchecked")
List<ProjectTemplateParams> paramslist = JSONArray.toList(jsonarr, new ProjectTemplateParams(),
new JsonConfig());
String httpptp = HttpRequest.loadJSON("/projectTemplateParams/cgetParamsByTemplate.do?templateid=" + templateidstr);
JSONObject jsonptpObject = JSONObject.fromObject(httpptp);
JSONArray jsonarr = JSONArray.fromObject(jsonptpObject.getString("params"));
//处理json-lib 2.4版本当遇到json格式字符串时把它当成对象处理的bug
for (int i = 0; i < jsonarr.size(); i++) {
JSONObject tempobj = (JSONObject) jsonarr.get(i);
String str = tempobj.get("param").toString();
if (str.length() > 0 && "[".equals(str.substring(0, 1)) && "]".equals(str.substring(str.length() - 1))) {
tempobj.element("param", "***" + str);
jsonarr.set(i, tempobj);
}
}
//处理头域
Map<String, String> headmsg = new HashMap<>(0);
if (null != ppt.getHeadmsg() && !ppt.getHeadmsg().equals("") && ppt.getHeadmsg().indexOf("=") > 0) {
String[] temp = ppt.getHeadmsg().split(";", -1);
for (int i = 0; i < temp.length; i++) {
if (null != temp[i] && !temp[i].equals("") && temp[i].indexOf("=") > 0) {
String key = temp[i].substring(0, temp[i].indexOf("="));
String value = temp[i].substring(temp[i].indexOf("=") + 1);
headmsg.put(key, value);
}
}
}
@SuppressWarnings("unchecked")
List<ProjectTemplateParams> paramslist = JSONArray.toList(jsonarr, new ProjectTemplateParams(),
new JsonConfig());
//处理更换参数
if(null!=getParameterValues){
String booleanheadmsg="headmsg(";
String msgend=")";
for (Object obp : getParameterValues) {
String paramob = obp.toString();
String key = paramob.substring(0, paramob.indexOf("#"));
String value = paramob.substring(paramob.indexOf("#") + 1);
if(key.indexOf(booleanheadmsg)>-1&&key.indexOf(msgend)>-1){
String head=key.substring(key.indexOf(booleanheadmsg)+8, key.lastIndexOf(msgend));
headmsg.put(head, value);
continue;
}
for (int i=0;i<paramslist.size();i++) {
ProjectTemplateParams ptp = paramslist.get(i);
if(ptp.getParamname().equals(key)){
ptp.setParam(value);
paramslist.set(i, ptp);
}
}
}
}
//处理参数
Map<String, Object> params = new HashMap<String, Object>(0);
for (ProjectTemplateParams ptp : paramslist) {
if(ptp.getParam().indexOf("***[")>-1&&"***[".equals(ptp.getParam().substring(0, 4))){
ptp.setParam(ptp.getParam().substring(3));
}
//处理参数对象
if(ptp.getParamtype()==1){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
JSONObject json= JSONObject.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), json);
luckyclient.publicclass.LogUtil.APP
.info("模板参数【" + ptp.getParamname() + "】 JSONObject类型参数值:【" + json.toString() + "");
}else if(ptp.getParamtype()==2){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
JSONArray jarr=JSONArray.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), jarr);
luckyclient.publicclass.LogUtil.APP
.info("模板参数【" + ptp.getParamname() + "】 JSONArray类型参数值:【" + jarr.toString() + "");
}else if(ptp.getParamtype()==3){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
File file=new File(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), file);
luckyclient.publicclass.LogUtil.APP
.info("模板参数【" + ptp.getParamname() + "】 File类型参数值:【" + file.getAbsolutePath() + "");
}else if(ptp.getParamtype()==4){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
Double dp=Double.valueOf(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), dp);
luckyclient.publicclass.LogUtil.APP
.info("模板参数【" + ptp.getParamname() + "】 数字类型参数值:【" + tempparam + "");
}else if(ptp.getParamtype()==5){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
Boolean bn=Boolean.valueOf(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), bn);
luckyclient.publicclass.LogUtil.APP
.info("模板参数【" + ptp.getParamname() + "】 Boolean类型参数值:【" + bn + "");
}else{
params.put(ptp.getParamname().replaceAll("&quot;", "\""), ptp.getParam().replaceAll("&quot;", "\""));
luckyclient.publicclass.LogUtil.APP
.info("模板参数【" + ptp.getParamname() + "】 String类型参数值:【" + ptp.getParam().replaceAll("&quot;", "\"") + "");
}
}
if (functionname.toLowerCase().equals("httpurlpost")) {
result = HttpClientHelper.sendHttpURLPost(packagename, params,
ppt.getContentencoding().toLowerCase(),ppt.getConnecttimeout(),headmsg);
} else if (functionname.toLowerCase().equals("urlpost")) {
result = HttpClientHelper.sendURLPost(packagename, params,
ppt.getContentencoding().toLowerCase(),ppt.getConnecttimeout(),headmsg);
} else if (functionname.toLowerCase().equals("getandsavefile")) {
String fileSavePath = System.getProperty("user.dir")+"\\HTTPSaveFile\\";
HttpClientHelper.sendGetAndSaveFile(packagename, params,fileSavePath,ppt.getConnecttimeout(),headmsg);
result = "下载文件成功,请前往客户端路径:"+fileSavePath+" 查看附件。";
} else if (functionname.toLowerCase().equals("httpurlget")) {
result = HttpClientHelper.sendHttpURLGet(packagename, params,
ppt.getContentencoding().toLowerCase(),ppt.getConnecttimeout(),headmsg);
} else if (functionname.toLowerCase().equals("urlget")) {
result = HttpClientHelper.sendURLGet(packagename, params,
ppt.getContentencoding().toLowerCase(),ppt.getConnecttimeout(),headmsg);
} else if (functionname.toLowerCase().equals("httpclientpost")) {
result = HttpClientHelper.httpClientPost(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else if (functionname.toLowerCase().equals("httpclientuploadfile")) {
result = HttpClientHelper.httpClientUploadFile(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else if (functionname.toLowerCase().equals("httpclientpostjson")) {
result = HttpClientHelper.httpClientPostJson(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else if (functionname.toLowerCase().equals("httpurldelete")) {
result = HttpClientHelper.sendHttpURLDel(packagename, params,
ppt.getContentencoding().toLowerCase(),ppt.getConnecttimeout(),headmsg);
} else if (functionname.toLowerCase().equals("httpclientputjson")) {
result = HttpClientHelper.httpClientPutJson(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else if (functionname.toLowerCase().equals("httpclientput")) {
result = HttpClientHelper.httpClientPut(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else if (functionname.toLowerCase().equals("httpclientget")) {
result = HttpClientHelper.httpClientGet(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else {
luckyclient.publicclass.LogUtil.APP.error("您的HTTP操作方法异常检测到的操作方法是" + functionname);
result = "调用异常,请查看错误日志!";
}
} else if (steptype == 3) {
String templateidstr = action.substring(1, action.indexOf(""));
String templatenamestr = action.substring(action.indexOf("") + 1);
luckyclient.publicclass.LogUtil.APP
.info("即将使用模板【" + templatenamestr + "】 ID:【" + templateidstr + "】 发送SOCKET请求");
if (null != getParameterValues) {
String booleanheadmsg = "headmsg(";
String msgend = ")";
for (Object obp : getParameterValues) {
String paramob = obp.toString();
String key = paramob.substring(0, paramob.indexOf("#"));
String value = paramob.substring(paramob.indexOf("#") + 1);
if (key.contains(booleanheadmsg) && key.contains(msgend)) {
String head = key.substring(key.indexOf(booleanheadmsg) + 8, key.lastIndexOf(msgend));
headmsg.put(head, value);
continue;
}
for (int i = 0; i < paramslist.size(); i++) {
ProjectTemplateParams ptp = paramslist.get(i);
if (ptp.getParamname().equals(key)) {
ptp.setParam(value);
paramslist.set(i, ptp);
}
}
}
}
//处理参数
Map<String, Object> params = new HashMap<String, Object>(0);
for (ProjectTemplateParams ptp : paramslist) {
if (ptp.getParam().contains("***[") && "***[".equals(ptp.getParam().substring(0, 4))) {
ptp.setParam(ptp.getParam().substring(3));
}
//处理参数对象
if (ptp.getParamtype() == 1) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
JSONObject json = JSONObject.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), json);
luckyclient.publicclass.LogUtil.APP.info("模板参数【" + ptp.getParamname() + "】 JSONObject类型参数值:【" + json.toString() + "");
} else if (ptp.getParamtype() == 2) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
JSONArray jarr = JSONArray.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), jarr);
luckyclient.publicclass.LogUtil.APP.info("模板参数【" + ptp.getParamname() + "】 JSONArray类型参数值:【" + jarr.toString() + "");
} else if (ptp.getParamtype() == 3) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
File file = new File(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), file);
luckyclient.publicclass.LogUtil.APP.info("模板参数【" + ptp.getParamname() + "】 File类型参数值:【" + file.getAbsolutePath() + "");
} else if (ptp.getParamtype() == 4) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
Double dp = Double.valueOf(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), dp);
luckyclient.publicclass.LogUtil.APP.info("模板参数【" + ptp.getParamname() + "】 数字类型参数值:【" + tempparam + "");
} else if (ptp.getParamtype() == 5) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
Boolean bn = Boolean.valueOf(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), bn);
luckyclient.publicclass.LogUtil.APP.info("模板参数【" + ptp.getParamname() + "】 Boolean类型参数值:【" + bn + "");
} else {
params.put(ptp.getParamname().replaceAll("&quot;", "\""), ptp.getParam().replaceAll("&quot;", "\""));
luckyclient.publicclass.LogUtil.APP.info("模板参数【" + ptp.getParamname() + "】 String类型参数值:【" + ptp.getParam().replaceAll("&quot;", "\"") + "");
}
}
String httpppt = HttpRequest
.loadJSON("/projectprotocolTemplate/cgetPTemplateById.do?templateid=" + templateidstr);
JSONObject jsonpptObject = JSONObject.fromObject(httpppt.toString());
ProjectProtocolTemplate ppt = (ProjectProtocolTemplate) JSONObject.toBean(jsonpptObject,
ProjectProtocolTemplate.class);
if (functionname.toLowerCase().equals("httpurlpost")) {
result = HttpClientHelper.sendHttpURLPost(packagename, params, ppt.getContentencoding().toLowerCase(), ppt.getConnecttimeout(), headmsg);
} else if (functionname.toLowerCase().equals("urlpost")) {
result = HttpClientHelper.sendURLPost(packagename, params, ppt.getContentencoding().toLowerCase(), ppt.getConnecttimeout(), headmsg);
} else if (functionname.toLowerCase().equals("getandsavefile")) {
String fileSavePath = System.getProperty("user.dir") + "\\HTTPSaveFile\\";
HttpClientHelper.sendGetAndSaveFile(packagename, params, fileSavePath, ppt.getConnecttimeout(), headmsg);
result = "下载文件成功,请前往客户端路径:" + fileSavePath + " 查看附件。";
} else if (functionname.toLowerCase().equals("httpurlget")) {
result = HttpClientHelper.sendHttpURLGet(packagename, params, ppt.getContentencoding().toLowerCase(), ppt.getConnecttimeout(), headmsg);
} else if (functionname.toLowerCase().equals("urlget")) {
result = HttpClientHelper.sendURLGet(packagename, params, ppt.getContentencoding().toLowerCase(), ppt.getConnecttimeout(), headmsg);
} else if (functionname.toLowerCase().equals("httpclientpost")) {
result = HttpClientHelper.httpClientPost(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else if (functionname.toLowerCase().equals("httpclientuploadfile")) {
result = HttpClientHelper.httpClientUploadFile(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else if (functionname.toLowerCase().equals("httpclientpostjson")) {
result = HttpClientHelper.httpClientPostJson(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else if (functionname.toLowerCase().equals("httpurldelete")) {
result = HttpClientHelper.sendHttpURLDel(packagename, params, ppt.getContentencoding().toLowerCase(), ppt.getConnecttimeout(), headmsg);
} else if (functionname.toLowerCase().equals("httpclientputjson")) {
result = HttpClientHelper.httpClientPutJson(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else if (functionname.toLowerCase().equals("httpclientput")) {
result = HttpClientHelper.httpClientPut(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else if (functionname.toLowerCase().equals("httpclientget")) {
result = HttpClientHelper.httpClientGet(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else {
luckyclient.publicclass.LogUtil.APP.error("您的HTTP操作方法异常检测到的操作方法是" + functionname);
result = "调用异常,请查看错误日志!";
}
} else if (steptype == 3) {
String templateidstr = action.substring(1, action.indexOf(""));
String templatenamestr = action.substring(action.indexOf("") + 1);
luckyclient.publicclass.LogUtil.APP.info("即将使用模板【" + templatenamestr + "】 ID:【" + templateidstr + "】 发送SOCKET请求");
String httpptp = HttpRequest
.loadJSON("/projectTemplateParams/cgetParamsByTemplate.do?templateid=" + templateidstr);
JSONObject jsonptpObject = JSONObject.fromObject(httpptp.toString());
JSONArray jsonarr = JSONArray.fromObject(jsonptpObject.getString("params"));
//处理json-lib 2.4版本当遇到json格式字符串时把它当成对象处理的bug
for(int i=0;i<jsonarr.size();i++){
JSONObject tempobj=(JSONObject) jsonarr.get(i);
String str=tempobj.get("param").toString();
if(str.length()>0&&"[".equals(str.substring(0, 1))&&"]".equals(str.substring(str.length()-1))){
tempobj.element("param", "***"+str);
jsonarr.set(i, tempobj);
}
}
//处理头域
Map<String, String> headmsg = new HashMap<String, String>(0);
if(null!=ppt.getHeadmsg()&&!ppt.getHeadmsg().equals("")&&ppt.getHeadmsg().indexOf("=")>0){
String[] temp=ppt.getHeadmsg().split(";",-1);
for(int i=0;i<temp.length;i++){
if(null!=temp[i]&&!temp[i].equals("")&&temp[i].indexOf("=")>0){
String key=temp[i].substring(0, temp[i].indexOf("="));
String value=temp[i].substring(temp[i].indexOf("=")+1);
headmsg.put(key, value);
}
}
}
@SuppressWarnings("unchecked")
List<ProjectTemplateParams> paramslist = JSONArray.toList(jsonarr, new ProjectTemplateParams(),
new JsonConfig());
String httpppt = HttpRequest.loadJSON("/projectprotocolTemplate/cgetPTemplateById.do?templateid=" + templateidstr);
JSONObject jsonpptObject = JSONObject.fromObject(httpppt);
ProjectProtocolTemplate ppt = (ProjectProtocolTemplate) JSONObject.toBean(jsonpptObject,
ProjectProtocolTemplate.class);
String httpptp = HttpRequest.loadJSON("/projectTemplateParams/cgetParamsByTemplate.do?templateid=" + templateidstr);
JSONObject jsonptpObject = JSONObject.fromObject(httpptp);
JSONArray jsonarr = JSONArray.fromObject(jsonptpObject.getString("params"));
//处理json-lib 2.4版本当遇到json格式字符串时把它当成对象处理的bug
for (int i = 0; i < jsonarr.size(); i++) {
JSONObject tempobj = (JSONObject) jsonarr.get(i);
String str = tempobj.get("param").toString();
if (str.length() > 0 && "[".equals(str.substring(0, 1)) && "]".equals(str.substring(str.length() - 1))) {
tempobj.element("param", "***" + str);
jsonarr.set(i, tempobj);
}
}
//处理头域
Map<String, String> headmsg = new HashMap<String, String>(0);
if (null != ppt.getHeadmsg() && !ppt.getHeadmsg().equals("") && ppt.getHeadmsg().indexOf("=") > 0) {
String[] temp = ppt.getHeadmsg().split(";", -1);
for (int i = 0; i < temp.length; i++) {
if (null != temp[i] && !temp[i].equals("") && temp[i].indexOf("=") > 0) {
String key = temp[i].substring(0, temp[i].indexOf("="));
String value = temp[i].substring(temp[i].indexOf("=") + 1);
headmsg.put(key, value);
}
}
}
@SuppressWarnings("unchecked")
List<ProjectTemplateParams> paramslist = JSONArray.toList(jsonarr, new ProjectTemplateParams(), new JsonConfig());
//处理更换参数
if(null!=getParameterValues){
String booleanheadmsg="headmsg(";
String msgend=")";
for (Object obp : getParameterValues) {
String paramob = obp.toString();
String key = paramob.substring(0, paramob.indexOf("#"));
String value = paramob.substring(paramob.indexOf("#") + 1);
if(key.indexOf(booleanheadmsg)>-1&&key.indexOf(msgend)>-1){
String head=key.substring(key.indexOf(booleanheadmsg)+8, key.lastIndexOf(msgend));
headmsg.put(head, value);
continue;
}
for (int i=0;i<paramslist.size();i++) {
ProjectTemplateParams ptp = paramslist.get(i);
if(ptp.getParamname().equals(key)){
ptp.setParam(value);
paramslist.set(i, ptp);
}
}
}
}
Map<String, Object> params = new HashMap<String, Object>(0);
for (ProjectTemplateParams ptp : paramslist) {
if(ptp.getParam().indexOf("***[")>-1&&"***[".equals(ptp.getParam().substring(0, 4))){
ptp.setParam(ptp.getParam().substring(3));
}
//处理参数对象
if(ptp.getParamtype()==1){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
JSONObject json= JSONObject.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), json);
}else if(ptp.getParamtype()==2){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
JSONArray jarr=JSONArray.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), jarr);
}else if(ptp.getParamtype()==3){
String tempparam=ptp.getParam().replaceAll("&quot;", "\"");
File file=new File(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), file);
}else{
params.put(ptp.getParamname().replaceAll("&quot;", "\""), ptp.getParam().replaceAll("&quot;", "\""));
}
}
if (null != getParameterValues) {
String booleanheadmsg = "headmsg(";
String msgend = ")";
for (Object obp : getParameterValues) {
String paramob = obp.toString();
String key = paramob.substring(0, paramob.indexOf("#"));
String value = paramob.substring(paramob.indexOf("#") + 1);
if (key.contains(booleanheadmsg) && key.contains(msgend)) {
String head = key.substring(key.indexOf(booleanheadmsg) + 8, key.lastIndexOf(msgend));
headmsg.put(head, value);
continue;
}
for (int i = 0; i < paramslist.size(); i++) {
ProjectTemplateParams ptp = paramslist.get(i);
if (ptp.getParamname().equals(key)) {
ptp.setParam(value);
paramslist.set(i, ptp);
}
}
}
}
Map<String, Object> params = new HashMap<String, Object>(0);
for (ProjectTemplateParams ptp : paramslist) {
if (ptp.getParam().contains("***[") && "***[".equals(ptp.getParam().substring(0, 4))) {
ptp.setParam(ptp.getParam().substring(3));
}
//处理参数对象
if (ptp.getParamtype() == 1) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
JSONObject json = JSONObject.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), json);
} else if (ptp.getParamtype() == 2) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
JSONArray jarr = JSONArray.fromObject(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), jarr);
} else if (ptp.getParamtype() == 3) {
String tempparam = ptp.getParam().replaceAll("&quot;", "\"");
File file = new File(tempparam);
params.put(ptp.getParamname().replaceAll("&quot;", "\""), file);
} else {
params.put(ptp.getParamname().replaceAll("&quot;", "\""), ptp.getParam().replaceAll("&quot;", "\""));
}
}
if (functionname.toLowerCase().equals("socketpost")) {
result = HttpClientHelper.sendSocketPost(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else if (functionname.toLowerCase().equals("socketget")) {
result = HttpClientHelper.sendSocketGet(packagename, params,
ppt.getContentencoding().toLowerCase(),headmsg);
} else {
luckyclient.publicclass.LogUtil.APP.error("您的SOCKET操作方法异常检测到的操作方法是" + functionname);
result = "调用异常,请查看错误日志!";
}
}
} catch (Throwable e) {
luckyclient.publicclass.LogUtil.APP.error(e.getMessage(), e);
return "调用异常,请查看错误日志!";
}
return result;
}
public static Method getMethod(Method[] methods, String methodName, @SuppressWarnings("rawtypes") Class[] parameterTypes) {
for (int i = 0; i < methods.length; i++) {
if (!methods[i].getName().equals(methodName)){
continue;
}
if (compareParameterTypes(parameterTypes, methods[i].getParameterTypes())){
return methods[i];
}
}
return null;
}
if (functionname.toLowerCase().equals("socketpost")) {
result = HttpClientHelper.sendSocketPost(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else if (functionname.toLowerCase().equals("socketget")) {
result = HttpClientHelper.sendSocketGet(packagename, params, ppt.getContentencoding().toLowerCase(), headmsg);
} else {
luckyclient.publicclass.LogUtil.APP.error("您的SOCKET操作方法异常检测到的操作方法是" + functionname);
result = "调用异常,请查看错误日志!";
}
}
} catch (Throwable e) {
luckyclient.publicclass.LogUtil.APP.error(e.getMessage(), e);
return "调用异常,请查看错误日志!";
}
return result;
}
public static boolean compareParameterTypes(@SuppressWarnings("rawtypes") Class[] parameterTypes, @SuppressWarnings("rawtypes") Class[] orgParameterTypes) {
// parameterTypes 里面int->Integer
// orgParameterTypes是原始参数类型
if (parameterTypes == null && orgParameterTypes == null){
return true;
}
if (parameterTypes == null && orgParameterTypes != null) {
if (orgParameterTypes.length == 0){
return true;
}else{
return false;
}
}
if (parameterTypes != null && orgParameterTypes == null) {
if (parameterTypes.length == 0){
return true;
}else{
return false;
}
}
if (parameterTypes.length != orgParameterTypes.length){
return false;
}
return true;
}
public static Method getMethod(Method[] methods, String methodName, @SuppressWarnings("rawtypes") Class[] parameterTypes) {
for (int i = 0; i < methods.length; i++) {
if (!methods[i].getName().equals(methodName)) {
continue;
}
if (compareParameterTypes(parameterTypes, methods[i].getParameterTypes())) {
return methods[i];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
return null;
}
}
public static boolean compareParameterTypes(@SuppressWarnings("rawtypes") Class[] parameterTypes, @SuppressWarnings("rawtypes") Class[] orgParameterTypes) {
// parameterTypes 里面int->Integer
// orgParameterTypes是原始参数类型
if (parameterTypes == null && orgParameterTypes == null) {
return true;
}
if (parameterTypes == null && orgParameterTypes != null) {
if (orgParameterTypes.length == 0) {
return true;
} else {
return false;
}
}
if (parameterTypes != null && orgParameterTypes == null) {
if (parameterTypes.length == 0) {
return true;
} else {
return false;
}
}
if (parameterTypes.length != orgParameterTypes.length) {
return false;
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}