Commit 6acdd168 authored by 郭姣's avatar 郭姣

卡卡

parents
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/yep.iml" filepath="$PROJECT_DIR$/.idea/yep.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="false" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
This diff is collapsed.
# kejiji
apply plugin: 'java'
apply plugin: 'maven'
group = 'kjj'
version = '1.0-SNAPSHOT'
description = """"""
sourceCompatibility = 1.8
targetCompatibility = 1.8
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
repositories {
mavenLocal()
maven { url "http://nexus.dui88.com:8081/nexus/content/groups/public/" }
maven { url "https://plugins.gradle.org/m2/" } //sonarqube
maven { url "http://repo.spring.io/plugins-release" }
mavenCentral()
}
dependencies {
compile 'org.projectlombok:lombok:1.18.12'
compile 'org.java-websocket:Java-WebSocket:1.5.1'
annotationProcessor 'org.projectlombok:lombok:1.18.12'
testCompile 'org.projectlombok:lombok:1.18.12'
testCompile 'org.java-websocket:Java-WebSocket:1.5.1'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.12'
compile group: 'com.alibaba', name: 'fastjson', version:'1.2.58'
compile(group: 'commons-lang', name: 'commons-lang', version:'2.6') {
exclude(module: 'commons-logging')
}
compile group: 'mysql', name: 'mysql-connector-java', version:'8.0.15'
compile group: 'org.apache.poi', name: 'poi', version:'4.1.0'
compile group: 'org.apache.poi', name: 'poi-ooxml', version:'3.17'
compile group: 'com.relevantcodes', name: 'extentreports', version:'2.41.0'
compile group: 'com.vimalselvam', name: 'testng-extentsreport', version:'1.3.1'
compile group: 'com.aventstack', name: 'extentreports', version:'3.0.6'
compile group: 'com.google.inject', name: 'guice', version:'4.2.2'
testCompile group: 'org.testng', name: 'testng', version:'6.8.8'
testCompile group: 'io.rest-assured', name: 'rest-assured', version:'4.0.0'
}
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<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/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: org.testng:testng:6.8.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.beanshell:bsh:2.0b4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.beust:jcommander:1.27" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.58" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: io.rest-assured:rest-assured:4.0.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.groovy:groovy:2.5.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.groovy:groovy-xml:2.5.6" 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-logging:commons-logging:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpmime:4.5.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-library:2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ccil.cowan.tagsoup:tagsoup:1.2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: io.rest-assured:json-path:4.0.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.groovy:groovy-json:2.5.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: io.rest-assured:rest-assured-common:4.0.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: io.rest-assured:xml-path:4.0.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.commons:commons-lang3:3.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: javax.xml.bind:jaxb-api:2.2.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.sun.xml.bind:jaxb-osgi:2.2.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.sling:org.apache.sling.javax.activation:0.1.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: javax.activation:activation:1.1.1" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:8.0.15" level="project" />
<orderEntry type="library" name="Maven: com.google.protobuf:protobuf-java:3.6.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi:4.1.0" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.12" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-collections4:4.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-math3:3.6.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml:3.17" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml-schemas:3.17" level="project" />
<orderEntry type="library" name="Maven: org.apache.xmlbeans:xmlbeans:2.6.0" level="project" />
<orderEntry type="library" name="Maven: stax:stax-api:1.0.1" level="project" />
<orderEntry type="library" name="Maven: com.github.virtuald:curvesapi:1.04" level="project" />
<orderEntry type="library" name="Maven: org.java-websocket:Java-WebSocket:1.5.1" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" name="Maven: com.relevantcodes:extentreports:2.41.0" level="project" />
<orderEntry type="library" name="Maven: org.jsoup:jsoup:1.8.3" level="project" />
<orderEntry type="library" name="Maven: org.xerial:sqlite-jdbc:3.8.11.1" level="project" />
<orderEntry type="library" name="Maven: org.freemarker:freemarker:2.3.23" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongodb-driver:3.0.4" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:bson:3.0.4" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongodb-driver-core:3.0.4" level="project" />
<orderEntry type="library" name="Maven: com.vimalselvam:testng-extentsreport:1.3.1" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:20.0" level="project" />
<orderEntry type="library" name="Maven: com.aventstack:extentreports:3.0.6" level="project" />
<orderEntry type="library" name="Maven: com.google.inject:guice:4.2.2" level="project" />
<orderEntry type="library" name="Maven: javax.inject:javax.inject:1" level="project" />
<orderEntry type="library" name="Maven: aopalliance:aopalliance:1.0" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.12" level="project" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>kjj</groupId>
<artifactId>kjj</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- maven 参数配置,这里引用不同的testng.xml -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- maven 引用依赖不同的jar -->
<dependencies>
<!--导入TestNG依赖包-->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
<!-- 导入fastjson包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.0.0</version>
<scope>test</scope>
</dependency>
<!-- 导入commons-lang的jar包 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- 引入poi,解析workbook视图 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.1</version>
</dependency>
<!-- 依赖reportNg 关联testNg-->
<!-- <dependency>-->
<!-- <groupId>org.uncommons</groupId>-->
<!-- <artifactId>reportng</artifactId>-->
<!-- <version>1.1.4</version>-->
<!-- <scope>test</scope>-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.testng</groupId>-->
<!-- <artifactId>testng</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- </dependency>-->
<!-- ExtentReports测试报告 关联testNg-->
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.0</version>
</dependency>
<dependency>
<groupId>com.vimalselvam</groupId>
<artifactId>testng-extentsreport</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.0.6</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<!-- 编译插件 -->
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<encoding>utf-8</encoding>
<!--源代码的编译-->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
<suiteXmlFiles>
<suiteXmlFile>src/test/testNG.xml</suiteXmlFile>
</suiteXmlFiles>
<properties>
<!--即使测试失败,也继续下面的测试-->
<property>
<name>usedefaultlisteners</name>
<value>false</value>
</property>
<property>
<name>listener</name>
<value>com.oto.config.ExtentTestNGIReporterListener</value>
</property>
</properties>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
rootProject.name = 'kjj'
package com.oto.cases.admin;
import com.oto.utils.NetworkUtils;
import static com.oto.config.BasicConfig.*;
import static com.oto.utils.BaseUtils.*;
/**
* 管理员授权
* @author 吉吉,ID:907
*/
public interface Authorization {
NetworkUtils network = NetworkUtils.getInstance();
//oto销售工作台-销售
default void otosellerAuth() {
network.agentCookies.put(otoSellerCookieKey, otoSellerCookieValue);
}
//oto销售工作台-总监
default void otoLeaderAuth() {
network.agentCookies.put(otoLeaderCookieKey, otoLeaderCookieValue);
}
//oto销售工作台手机端-销售
default void otoSellerTku() {
network.agentCookies.put("tku", OTO_TKU);
}
//oto销售工作台-管理员
default void otoManagerAuth() {
network.agentCookies.put(otoManagerCookieKey, otoManagerCookieValue);
}
//久久保管理员-正常权限模式
default void jjbManagerAuth() {network.agentCookies.put(JJBManagerCookieKey,JJBManagerCookieValue);}
/**
* 集客助手相关授权
*/
//代理人吉吉 sid:2991
default void agentTku() {
network.agentCookies.put(TKU_COOKIE_NAME, AGENT_TKU);
System.out.println("代理人吉吉tku:" + AGENT_TKU);
}
//代理人xxx
default void agent2Tku() {
network.agentCookies.put(TKU_COOKIE_NAME, AGENT2_TKU);
System.out.println("代理人梦晨tku:" + AGENT2_TKU);
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
package com.oto.config;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.ResourceCDN;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.model.TestAttribute;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.util.*;
import com.oto.utils.DingTalkUtils;
public class ExtentTestNGIReporterListener implements IReporter {
// 生成的路径以及文件名
private static final String OUTPUT_FOLDER = "test-output/";
//注意这里如果用index.html可能会导致testng的report会覆盖它
private static final String FILE_NAME = "report.html";
private ExtentReports extent;
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
init();
boolean createSuiteNode = false;
//判断执行用例的队列是否有多个
if (suites.size() == 0) {
createSuiteNode = true;
}
StringBuffer contextString = new StringBuffer();
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
// 如果suite里面没有任何用例,直接跳过,不在报告里生成
if (result.size() == 0) {
continue;
}
// 统计suite下的成功、失败的总用例数
int suiteFailSize = 0;
int suitePassSize = 0;
ExtentTest suiteTest = null;
// 存在多个suite的情况下,在报告中将同一个suite的测试结果归为一类,创建一级节点。
if (createSuiteNode) {
suiteTest = extent.createTest(suite.getName()).assignCategory(suite.getName());
}
boolean createSuiteResultNode = false;
if (result.size() >= 1) {
createSuiteResultNode = true;
}
for (ISuiteResult r : result.values()) {
ExtentTest resultNode;
ITestContext context = r.getTestContext();
if (createSuiteResultNode) {
// 没有创建suite的情况下,将在SuiteResult的创建为一级节点,否则创建为suite的一个子节点。
if (null == suiteTest) {
resultNode = extent.createTest(r.getTestContext().getName());
} else {
resultNode = suiteTest.createNode(r.getTestContext().getName());
}
} else {
resultNode = suiteTest;
}
if (resultNode != null) {
resultNode.getModel().setName(suite.getName() + " : " + r.getTestContext().getName());
if (resultNode.getModel().hasCategory()) {
resultNode.assignCategory(r.getTestContext().getName());
} else {
resultNode.assignCategory(suite.getName(), r.getTestContext().getName());
}
resultNode.getModel().setStartTime(r.getTestContext().getStartDate());
resultNode.getModel().setEndTime(r.getTestContext().getEndDate());
// 统计SuiteResult下的数据
int passSize = r.getTestContext().getPassedTests().size();
int failSize = r.getTestContext().getFailedTests().size();
suitePassSize += passSize;
suiteFailSize += failSize;
if (failSize > 0) {
resultNode.getModel().setStatus(Status.FAIL);
}
resultNode.getModel().setDescription(
String.format("Pass: %s ; Fail: %s ;", passSize, failSize));
}
buildTestNodes(resultNode, context.getFailedTests(), Status.FAIL);
// buildTestNodes(resultNode, context.getSkippedTests(), Status.SKIP);
buildTestNodes(resultNode, context.getPassedTests(), Status.PASS);
}
if (suiteTest != null) {
suiteTest.getModel().setDescription(
String.format("Pass: %s ; Fail: %s ;", suitePassSize, suiteFailSize));
if (suiteFailSize > 0) {
suiteTest.getModel().setStatus(Status.FAIL);
}
}
contextString.append(suite.getName()).append("\n")
.append(String.format("总用例数: %s\n通过的用例数: %s\n失败的用例数: %s\n", suite.getAllMethods().size(), suitePassSize, suiteFailSize))
.append("\n");
}
try {
DingTalkUtils.sendVal(contextString.toString());
} catch (Exception e) {
e.printStackTrace();
}
extent.flush();
}
private void init() {
// 文件夹不存在的话进行创建
File reportDir = new File(OUTPUT_FOLDER);
if (!reportDir.exists() && !reportDir.isDirectory()) {
reportDir.mkdir();
}
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
// 设置静态文件的DNS
//怎么样解决cdn.rawgit.com访问不了的情况
htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);
htmlReporter.config().setDocumentTitle("客集集-自动化测试报告");
htmlReporter.config().setReportName("客集集-自动化测试报告");
htmlReporter.config().setChartVisibilityOnOpen(true);
//报表位置
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setCSS(".node.level-1 ul{ display:none;} .node.level-1.active ul{display:block;}");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
}
private void buildTestNodes(ExtentTest extenttest, IResultMap tests, Status status) {
// 存在父节点时,获取父节点的标签
String[] categories = new String[0];
if (extenttest != null) {
List<TestAttribute> categoryList = extenttest.getModel().getCategoryContext().getAll();
categories = new String[categoryList.size()];
for (int index = 0; index < categoryList.size(); index++) {
categories[index] = categoryList.get(index).getName();
}
}
ExtentTest test;
if (tests.size() > 0) {
// 调整用例排序,按时间排序
Set<ITestResult> treeSet = new TreeSet<ITestResult>(new Comparator<ITestResult>() {
@Override
public int compare(ITestResult o1, ITestResult o2) {
return o1.getStartMillis() < o2.getStartMillis() ? -1 : 1;
}
});
treeSet.addAll(tests.getAllResults());
for (ITestResult result : treeSet) {
Object[] parameters = result.getParameters();
String name = "";
// 如果有参数,则使用参数的toString组合代替报告中的name
for (Object param : parameters) {
name += param.toString();
}
if (name.length() > 0) {
if (name.length() > 50) {
name = name.substring(0, 49) + "...";
}
} else {
name = result.getMethod().getMethodName();
}
if (extenttest == null) {
test = extent.createTest(name);
} else {
// 作为子节点进行创建时,设置同父节点的标签一致,便于报告检索。
test = extenttest.createNode(name).assignCategory(categories);
}
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
List<String> outputList = Reporter.getOutput(result);
for (String output : outputList) {
// 将用例的log输出报告中
test.debug(output);
}
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
} else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
test.getModel().setStartTime(getTime(result.getStartMillis()));
test.getModel().setEndTime(getTime(result.getEndMillis()));
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
package com.oto.sql;
import java.sql.*;
import java.util.*;
public class KjyLiveNormalDB {
private static KjyLiveNormalDB user_Utils;
//数据库用户名
private String USERNAME = "auto_test";
//数据库密码
private String PASSWORD = "881QYHoGGgc09Ngv"; //= "yanzi";
//驱动信息
private String DRIVER="com.mysql.cj.jdbc.Driver";
//数据库地址
private String USER_URL="jdbc:mysql://rm-bp11mkg584kvjr485.mysql.rds.aliyuncs.com:3306/kjy_live_normal";
private Connection connection;
private PreparedStatement pstmt;
private ResultSet resultSet;
public static synchronized KjyLiveNormalDB getInstance(){
if (Objects.nonNull(user_Utils)){
return user_Utils;
}
user_Utils = new KjyLiveNormalDB();
user_Utils.initConnection();
return user_Utils;
}
/**
* 获得数据库的连接
* @return
*/
private Connection initConnection(){
try {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = USER_URL+"?autoReconnect=true&testOnBorrow=true&testWhileIdle=true";
connection = DriverManager.getConnection(url,USERNAME,PASSWORD);
System.out.println("数据库连接成功!");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 查询结果只有一行数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return map
* @throws SQLException
*/
public Map<String, Object> findSimpleResult(String sql, Object ...params) throws SQLException{
if(!connection.isValid(3)){
System.out.println("mysql connect is not vaild,reconnect.");
connection.close();
initConnection();
}
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
System.out.println("sql:"+pstmt.toString());
resultSet = pstmt.executeQuery();//返回查询结果
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();
while(resultSet.next()){
for(int i=0; i<col_len; i++ ){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
return map;
}
/**
* 返回多条数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return list
* @throws SQLException
*/
public List<Map<String, Object>> findModeResult(String sql, Object ...params) throws SQLException{
if(!connection.isValid(3)){
System.out.println("mysql connect is not vaild,reconnect.");
connection.close();
initConnection();
}
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while(resultSet.next()){
Map<String, Object> map = new HashMap<String, Object>();
for(int i=0; i<cols_len; i++){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
/**
* 执行更新语句
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return void
* @throws SQLException
*/
public void updataSql(String sql, Object ...params) throws SQLException{
if(!connection.isValid(3)){
System.out.println("mysql connect is not vaild,reconnect.");
connection.close();
initConnection();
}
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
System.out.println("sql:"+pstmt.toString());
pstmt.executeUpdate();//返回更新结果
}
/**
* 释放数据库连接
*/
public void releaseConn(){
if(resultSet != null){
try{
resultSet.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
package com.oto.sql;
import java.sql.*;
import java.util.*;
public class KjyUserDB {
private static KjyUserDB user_Utils;
//数据库用户名
private String USERNAME = "auto_test";
//数据库密码
private String PASSWORD = "881QYHoGGgc09Ngv"; //= "yanzi";
//驱动信息
private String DRIVER="com.mysql.cj.jdbc.Driver";
//数据库地址
private String USER_URL="jdbc:mysql://rm-bp11mkg584kvjr485.mysql.rds.aliyuncs.com:3306/kjy_user";
private Connection connection;
private PreparedStatement pstmt;
private ResultSet resultSet;
public static synchronized KjyUserDB getInstance(){
if (Objects.nonNull(user_Utils)){
return user_Utils;
}
user_Utils = new KjyUserDB();
user_Utils.initConnection();
return user_Utils;
}
/**
* 获得数据库的连接
* @return
*/
private Connection initConnection(){
try {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = USER_URL+"?autoReconnect=true&testOnBorrow=true&testWhileIdle=true";
connection = DriverManager.getConnection(url,USERNAME,PASSWORD);
System.out.println("数据库连接成功!");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 查询结果只有一行数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return map
* @throws SQLException
*/
public Map<String, Object> findSimpleResult(String sql, Object ...params) throws SQLException{
if(!connection.isValid(3)){
System.out.println("mysql connect is not vaild,reconnect.");
connection.close();
initConnection();
}
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
System.out.println("sql:"+pstmt.toString());
resultSet = pstmt.executeQuery();//返回查询结果
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();
while(resultSet.next()){
for(int i=0; i<col_len; i++ ){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
return map;
}
/**
* 返回多条数据
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return list
* @throws SQLException
*/
public List<Map<String, Object>> findModeResult(String sql, Object ...params) throws SQLException{
if(!connection.isValid(3)){
System.out.println("mysql connect is not vaild,reconnect.");
connection.close();
initConnection();
}
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while(resultSet.next()){
Map<String, Object> map = new HashMap<String, Object>();
for(int i=0; i<cols_len; i++){
String cols_name = metaData.getColumnName(i+1);
Object cols_value = resultSet.getObject(cols_name);
if(cols_value == null){
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
/**
* 执行更新语句
* @param sql sql语句
* @param params 可变参数,替换 ?
* @return void
* @throws SQLException
*/
public void updataSql(String sql, Object ...params) throws SQLException{
if(!connection.isValid(3)){
System.out.println("mysql connect is not vaild,reconnect.");
connection.close();
initConnection();
}
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if(params != null && !(params.length==0)){
for(int i=0; i<params.length; i++){
pstmt.setObject(index++, params[i]);
}
}
System.out.println("sql:"+pstmt.toString());
pstmt.executeUpdate();//返回更新结果
}
/**
* 释放数据库连接
*/
public void releaseConn(){
if(resultSet != null){
try{
resultSet.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
package com.oto.sql;
public class UserSqlFactory {
private UserSqlFactory(){}
public static final String selectUserIdByUnionId = "select id from tb_users where union_id=?";
public static final String selectUserIdByOpenId = "SELECT user_id FROM `tb_users_wx_ext` WHERE `open_id` = ?";
public static final String selectUserIdForJmeter = "SELECT a.`id` FROM `tb_live_user` a, `tb_users` b ,`tb_users_wx_ext` c WHERE a.`biz_user_id` = b.`id` and b.`id` = c.`user_id` and b.`union_id` NOT LIKE \"-d%\" AND c.`open_id` IS NOT NULL and c.`oa_id` = 14";
public static final String selectCodeIdByCustomerId = "SELECT `scan_code_id` FROM `tb_cust_interview_record` WHERE `customer_id` = ? and interview_status = 1 ORDER BY id DESC ";
}
package com.oto.utils;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
/**
* Created with IntelliJ IDEA.
* User: noah
* Date: 8/2/13
* Time: 10:36 AM
* To change this template use File | Settings | File Templates.
*/
public class Base58 {
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private static final int[] INDEXES = new int[128];
static {
for (int i = 0; i < INDEXES.length; i++) {
INDEXES[i] = -1;
}
for (int i = 0; i < ALPHABET.length; i++) {
INDEXES[ALPHABET[i]] = i;
}
}
/**
* Encodes the given bytes in base58. No checksum is appended.
*/
public static String encode(byte[] input) {
if (input.length == 0) {
return "";
}
input = copyOfRange(input, 0, input.length);
// Count leading zeroes.
int zeroCount = 0;
while (zeroCount < input.length && input[zeroCount] == 0) {
++zeroCount;
}
// The actual encoding.
byte[] temp = new byte[input.length * 2];
int j = temp.length;
int startAt = zeroCount;
while (startAt < input.length) {
byte mod = divmod58(input, startAt);
if (input[startAt] == 0) {
++startAt;
}
temp[--j] = (byte) ALPHABET[mod];
}
// Strip extra '1' if there are some after decoding.
while (j < temp.length && temp[j] == ALPHABET[0]) {
++j;
}
// Add as many leading '1' as there were leading zeros.
while (--zeroCount >= 0) {
temp[--j] = (byte) ALPHABET[0];
}
byte[] output = copyOfRange(temp, j, temp.length);
try {
return new String(output, "US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
public static byte[] decode(String input) throws IllegalArgumentException {
if (input.length() == 0) {
return new byte[0];
}
byte[] input58 = new byte[input.length()];
// Transform the String to a base58 byte sequence
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
int digit58 = -1;
if (c >= 0 && c < 128) {
digit58 = INDEXES[c];
}
if (digit58 < 0) {
throw new IllegalArgumentException("Illegal character " + c + " at " + i);
}
input58[i] = (byte) digit58;
}
// Count leading zeroes
int zeroCount = 0;
while (zeroCount < input58.length && input58[zeroCount] == 0) {
++zeroCount;
}
// The encoding
byte[] temp = new byte[input.length()];
int j = temp.length;
int startAt = zeroCount;
while (startAt < input58.length) {
byte mod = divmod256(input58, startAt);
if (input58[startAt] == 0) {
++startAt;
}
temp[--j] = mod;
}
// Do no add extra leading zeroes, move j to first non null byte.
while (j < temp.length && temp[j] == 0) {
++j;
}
return copyOfRange(temp, j - zeroCount, temp.length);
}
public static BigInteger decodeToBigInteger(String input) throws IllegalArgumentException {
return new BigInteger(1, decode(input));
}
//
// number -> number / 58, returns number % 58
//
private static byte divmod58(byte[] number, int startAt) {
int remainder = 0;
for (int i = startAt; i < number.length; i++) {
int digit256 = (int) number[i] & 0xFF;
int temp = remainder * 256 + digit256;
number[i] = (byte) (temp / 58);
remainder = temp % 58;
}
return (byte) remainder;
}
//
// number -> number / 256, returns number % 256
//
private static byte divmod256(byte[] number58, int startAt) {
int remainder = 0;
for (int i = startAt; i < number58.length; i++) {
int digit58 = (int) number58[i] & 0xFF;
int temp = remainder * 58 + digit58;
number58[i] = (byte) (temp / 256);
remainder = temp % 256;
}
return (byte) remainder;
}
private static byte[] copyOfRange(byte[] source, int from, int to) {
byte[] range = new byte[to - from];
System.arraycopy(source, from, range, 0, range.length);
return range;
}
}
package com.oto.utils;
import com.oto.config.BasicConfig;
import io.restassured.response.Response;
import org.testng.Assert;
import java.util.*;
import static com.oto.config.BasicConfig.*;
public class BaseUtils {
private static final NetworkUtils network = NetworkUtils.getInstance();
public static String tku1;
public static String tku2;
public static String superCookieKey;
public static String superCookieValue;
public static String companyCookieKey;
public static String companyCookieValue;
public static String officeCookieKey;
public static String officeCookieValue;
public static String otoSellerCookieKey;
public static String otoSellerCookieValue;
public static String otoLeaderCookieKey;
public static String otoLeaderCookieValue;
public static String otoManagerCookieKey;
public static String otoManagerCookieValue;
public static String JJBManagerCookieKey;
public static String JJBManagerCookieValue;
/**
* 登录管理后台
*/
public static void ssoLogin(){
// 请求下后台的管理员信息接口
Response response = network.getResponse(MANAGER_adminInfo);
String actualType = "application/json;charset=UTF-8";
String exceptType = response.headers().getValue("Content-Type"); //如果返回的是html的contentType,说明token已经失效
// 判断请求接口后 后台的Csrf-Token是否失效,若两个值相等则有效,反之
if (actualType.equals(exceptType)){
return;
}
// 1.先进入SSO登录框 登入管理后台
Map<String, Object> loginParams = new HashMap<String, Object>();
loginParams.put("email","test@duiba.com.cn");
loginParams.put("password","d83HjbsJY76UJH");
loginParams.put("loginTimeout",1);
loginParams.put("redirect",MANAGER_HOST);
loginParams.put("systemId",201);
response = network.postResponse(loginParams,SSO_doLogin);
Map<String, String> ssoCookies = response.getCookies();
network.agentCookies.putAll(ssoCookies); //存入cookies
ssoCookies = response.getCookies();
network.agentCookies.putAll(ssoCookies);
network.agentHeaders.put("X-Csrf-Token",ssoCookies.get("csrf_token"));
// 免登
network.agentCookies.put("sso_ticket", "autotest");
}
/**
* 普通销售员登录销售工作台
*/
public static void otoSellerLogin(){
// ThreadSleepUtils.sleep(2000);
// // 调用登录接口
// Map<String, Object> params = new HashMap<String, Object>();
// params.put("phoneNumber","18248405155");
// Response response = network.getResponse(params,BasicConfig.WORK_getCaptcha);
// boolean data = response.jsonPath().getBoolean("data");
// Assert.assertTrue(data,network.message(params,BasicConfig.WORK_getCaptcha,"获取验证码失败",response.body().asString()));
//
// //专用于自动化获取验证码
// params.clear();
// params.put("phoneNumber","18248405155");
// Response autoTestRes = network.getResponse(params,BasicConfig.WORK_verifyCode);
// String captcha = autoTestRes.jsonPath().getString("data");
// System.out.println(captcha);
//
// //登录接口
// ThreadSleepUtils.sleep(2000);
// params.clear();
// params.put("phoneNumber","18248405155");
// params.put("captcha",captcha);
// Response loginRes = network.postResponse(params,BasicConfig.WORK_login);
// boolean success = loginRes.jsonPath().getBoolean("success");
// Assert.assertTrue(success, network.message(params,BasicConfig.WORK_login,"登录失败",loginRes.body().asString()));
//
// //获取cookie
// String header = loginRes.getHeader("Set-Cookie");
// String cookieStr = header.split(";")[0];
// String[] cookieKeyValue = cookieStr.split("=");
// otoSellerCookieKey = cookieKeyValue[0];
// otoSellerCookieValue = cookieKeyValue[1];
otoSellerCookieKey = "otoToken";
otoSellerCookieValue = "64e83LYGbaXYX9EkHumCho2UoHa4LLngpoj9ksrdj5vUiAndSwpeHVxc45qhsXT8a8niiL6oifhdXYR2BvYntaAoj4zRqmExv6eEuMsTfiN";
network.agentCookies.put(otoSellerCookieKey, otoSellerCookieValue); //存入cookies
System.out.println("销售Cookie中key:"+ otoSellerCookieKey +" ,values:"+ otoSellerCookieValue);
}
/**
* 总监登录销售工作台
*/
public static void otoLeaderLogin(){
// ThreadSleepUtils.sleep(2000);
// // 调用登录接口
// Map<String, Object> params = new HashMap<String, Object>();
// params.put("phoneNumber","13454131091");
// Response response = network.getResponse(params,BasicConfig.WORK_getCaptcha);
// boolean data = response.jsonPath().getBoolean("data");
// Assert.assertTrue(data,network.message(params,BasicConfig.WORK_getCaptcha,"获取验证码失败",response.body().asString()));
//
// //专用于自动化获取验证码
// params.clear();
// params.put("phoneNumber","13454131091");
// Response autoTestRes = network.getResponse(params,BasicConfig.WORK_verifyCode);
// String captcha = autoTestRes.jsonPath().getString("data");
// System.out.println(captcha);
//
// //登录接口
// ThreadSleepUtils.sleep(2000);
// params.clear();
// params.put("phoneNumber","13454131091");
// params.put("captcha",captcha);
// Response loginRes = network.postResponse(params,BasicConfig.WORK_login);
// boolean success = loginRes.jsonPath().getBoolean("success");
// Assert.assertTrue(success, network.message(params,BasicConfig.WORK_login,"登录失败",loginRes.body().asString()));
//
// //获取cookie
// String header = loginRes.getHeader("Set-Cookie");
// String cookieStr = header.split(";")[0];
// String[] cookieKeyValue = cookieStr.split("=");
// otoLeaderCookieKey = cookieKeyValue[0];
// otoLeaderCookieValue = cookieKeyValue[1];
otoLeaderCookieKey = "otoToken";
otoLeaderCookieValue = "64e83LYGbaXYX9EkHumCho2UoHa4LLngtEH3qdP4vZcgziRKzqpEScM6Ea5UdYNEMDstTteXF6yrygqLEsBVdZJ1mKGyZ4cD5dZVM2RqyrK";
network.agentCookies.put(otoLeaderCookieKey, otoLeaderCookieValue); //存入cookies
System.out.println("总监Cookie中key:"+ otoLeaderCookieKey +" ,values:"+ otoLeaderCookieValue);
}
/**
* 管理员登录销售工作台
*/
public static void otoManagerLogin(){
// ThreadSleepUtils.sleep(2000);
// // 调用登录接口
// Map<String, Object> params = new HashMap<String, Object>();
// params.put("phoneNumber","13900651198");
// Response response = network.getResponse(params,BasicConfig.WORK_getCaptcha);
// boolean data = response.jsonPath().getBoolean("data");
// Assert.assertTrue(data,network.message(params,BasicConfig.WORK_getCaptcha,"获取验证码失败",response.body().asString()));
//
// //专用于自动化获取验证码
// params.clear();
// params.put("phoneNumber","15673990207");
// Response autoTestRes = network.getResponse(params,BasicConfig.WORK_verifyCode);
// String captcha = autoTestRes.jsonPath().getString("data");
// System.out.println(captcha);
//
// //登录接口
// ThreadSleepUtils.sleep(2000);
// params.clear();
// params.put("phoneNumber","15673990207");
// params.put("captcha",captcha);
// Response loginRes = network.postResponse(params,BasicConfig.WORK_login);
// boolean success = loginRes.jsonPath().getBoolean("success");
// Assert.assertTrue(success, network.message(params,BasicConfig.WORK_login,"登录失败",loginRes.body().asString()));
//
// //获取cookie
// String header = loginRes.getHeader("Set-Cookie");
// String cookieStr = header.split(";")[0];
// String[] cookieKeyValue = cookieStr.split("=");
// otoManagerCookieKey = cookieKeyValue[0];
// otoManagerCookieValue = cookieKeyValue[1];
otoManagerCookieKey = "otoToken";
otoManagerCookieValue = "2hdZyc3Wrhbokz5QFVTnXxxteUrg4U3szFLLQhKruh4Q6eZAVEBcYAKcwDfN5vGk9MNkshTkxpyidEtujMzGw5X5EsNfV1h7kn2bzap2P8baGi";
// network.agentCookies.put(otoManagerCookieKey, otoManagerCookieValue); //存入cookies
// System.out.println("销售Cookie中key:"+ otoManagerCookieKey +" ,values:"+ otoManagerCookieValue);
}
/**
* 登录久久保系统(目前账号及登录密码是写死的)
*/
public static void JJBLogin(){
Map<String,Object> params = new HashMap<>();
params.put("userName","adminzc");
params.put("userPwd","oto88888888");
Response response = network.postResponse(params,JiuJiuBao_login);
boolean data = response.jsonPath().getBoolean("data");
Assert.assertTrue(data, network.message(params, BasicConfig.JiuJiuBao_login,"久久保登录失败",response.body().asString()));
//获取cookie
String header = response.getHeader("Set-Cookie");
String cookieStr = header.split(";")[0];
String[] cookieKeyValue = cookieStr.split("=");
JJBManagerCookieKey = cookieKeyValue[0];
JJBManagerCookieValue = cookieKeyValue[1];
network.agentCookies.put(JJBManagerCookieKey,JJBManagerCookieValue);
System.out.println("久久保cookie中的key:"+JJBManagerCookieKey +",values:"+JJBManagerCookieValue);
}
}
package com.oto.utils;
import java.util.HashMap;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
/**
* Blowfish加密解密的方
*
* @link http://www.schneier.com/blowfish.html
*/
public class BlowfishUtils {
private static final String CIPHER_NAME="Blowfish/CFB8/NoPadding";
private static final String KEY_SPEC_NAME="Blowfish";
private static final ThreadLocal<HashMap<String, BlowfishUtils>> pool=new ThreadLocal<HashMap<String,BlowfishUtils>>();
private Cipher enCipher;
private Cipher deCipher;
private String key;
private BlowfishUtils(String key){
try {
this.key=key;
String iv= StringUtils.substring(DigestUtils.md5Hex(key), 0,8);
SecretKeySpec secretKeySpec=new SecretKeySpec(key.getBytes(), KEY_SPEC_NAME);
IvParameterSpec ivParameterSpec=new IvParameterSpec(iv.getBytes());
enCipher=Cipher.getInstance(CIPHER_NAME);
deCipher=Cipher.getInstance(CIPHER_NAME);
enCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivParameterSpec);
deCipher.init(Cipher.DECRYPT_MODE, secretKeySpec,ivParameterSpec);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encryptBlowfish(String s,String key){
return getInstance(key).encrypt(s);
}
public static String decryptBlowfish(String s,String key){
return getInstance(key).decrypt(s);
}
public static String encryptBlowfish(String s){
return encryptBlowfish(s, "abc");
}
public static String decryptBlowfish(String s){
return decryptBlowfish(s, "abc");
}
private static BlowfishUtils getInstance(String key){
HashMap<String, BlowfishUtils> keyMap=pool.get();
if(keyMap==null || keyMap.isEmpty()){
keyMap=new HashMap<String, BlowfishUtils>();
pool.set(keyMap);
}
BlowfishUtils instance=keyMap.get(key);
if(instance==null || !StringUtils.equals(instance.key, key)){
instance=new BlowfishUtils(key);
keyMap.put(key, instance);
}
return instance;
}
/**
* 加密
* @param s
* @return
*/
private String encrypt(String s){
String result=null;
if(StringUtils.isNotBlank(s)){
try {
byte[] encrypted=enCipher.doFinal(s.getBytes());
result=new String(Base58.encode(encrypted));
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
/**
* 解密
* @param s
* @return
*/
private String decrypt(String s){
String result=null;
if(StringUtils.isNotBlank(s)){
try {
byte[] decrypted=Base58.decode(s);
result=new String(deCipher.doFinal(decrypted));
} catch (Exception e) {
resetInstance();
e.printStackTrace();
}
}
return result;
}
private void resetInstance(){
pool.set(null);
}
}
package com.oto.utils;
import io.restassured.response.Response;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.oto.config.BasicConfig.isPushReport;
public class DingTalkUtils {
private static final NetworkUtils network = NetworkUtils.getInstance();
private static final AtomicBoolean hasSend = new AtomicBoolean(true);
// 通过钉钉机器人发送消息到钉钉群中
public static void sendVal(String context)throws Exception{
if (!hasSend.compareAndSet(true, false)){
return;
}
//测试结果
context = "【接口自动化测试结果反馈】\n"
+ context
+ "报告地址: http://10.172.58.199/view/kkk/job/kejiji_interface/HTML_20Report\n";
System.out.println(context);
Map<String, Object> contentParams = new HashMap<String, Object>();
contentParams.put("content",context);
Map<String, Object> atParams = new HashMap<String, Object>();
atParams.put("atMobiles","17830855590");
//钉钉机器人消息体
Map<String, Object> params = new HashMap<String, Object>();
params.put("msgtype","text");
params.put("text",contentParams);
params.put("at", atParams);
//发起dingding机器人通知
if (isPushReport){
Response response = network.dingTalkRobot(params);
System.out.println("钉钉 response:"+response.asString());
}
}
// 流程走不通,发送错误信息到钉钉
public static void sendError(String errorMessage){
Map<String, Object> contentParams = new HashMap<String, Object>();
contentParams.put("content","【测试结果】\n" + errorMessage);
//钉钉机器人消息体
Map<String, Object> params = new HashMap<String, Object>();
params.put("msgtype","text");
params.put("text",contentParams);
System.out.println(params);
//发起dingding机器人通知
if (isPushReport){
Response response = network.dingTalkRobot(params);
response.body().prettyPrint();
}
}
public static void main(String[] args) {
}
}
package com.oto.utils;
import java.util.HashMap;
import java.util.Map;
/**
* @author lizhi
* @date 2020/4/9 11:36 AM
*/
public enum IdConvertBase64Enum {
/**
* 注意,code只能是两位
*/
DEF("j2", "默认类型"),
TRANS("t3", "短链接服务"),
;
private String code;
private String desc;
IdConvertBase64Enum(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return "K"+ code;
}
private static final Map<String, IdConvertBase64Enum> ENUM_MAP = new HashMap<>();
static{
for(IdConvertBase64Enum lengthEnum : values()){
ENUM_MAP.put(lengthEnum.getCode(), lengthEnum);
}
}
public static IdConvertBase64Enum getByCode(String code) {
if (code == null) {
return null;
}
return ENUM_MAP.get(code);
}
}
\ No newline at end of file
package com.oto.utils;
import com.oto.cases.admin.Authorization;
import com.oto.config.BasicConfig;
import io.restassured.response.Response;
import org.apache.commons.lang.StringUtils;
import org.testng.Assert;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dugq on 2019-10-23.
*
* 把ID转换后通过base64编码得出来的值
* 规律: 以Kj2 开头。第四位为base64结尾'='的个数。避免url encoding
* 数字部分利用二进制左移3位,后三位补1 把数字变换掉,再base64转码。支持最大值为 2^(64-4)
* 兼容:旧版本以kjj开头 第四位取原数字第一位补充。 加密已删除,揭秘通过kjj 和 kj2 区分
* 修改原因: 旧版本太长, 且要处理URL编码问题导致多了一次转换16进制。 加密的主要方案在于 数字左移和补最高位,鉴于base64的高效,所以使用base64encode来美化ID
*
* base64加密效率: 加密 1 - 2千万 1s以内完成
*/
public class IdMakeUtil implements Authorization {
private static final Base64.Encoder encoder = Base64.getEncoder();
private static final Base64.Decoder decoder = Base64.getDecoder();
private static final String PREFIX = "Kj2";
private IdMakeUtil(){}
public static String encodingId(Long id) {
id = (id << 3) ^ 7;
String encode = encoder.encodeToString(Long.toString(id).getBytes());
String replace = encode.replace("=", "");
return PREFIX + (encode.length() - replace.length()) + replace;
}
public static Long decodingId(String encode) {
if (StringUtils.isBlank(encode)) {
return null;
}
try {
StringBuilder substring = new StringBuilder(encode.substring(4));
String decode = new String(decoder.decode(substring.toString()));
return Long.valueOf(decode) >> 3;
} catch (Exception e) {
return null;
}
}
public static String managerEncodingId(long id) {
BaseUtils.ssoLogin();
Map<String, Object> ids = new HashMap<>();
ids.put("code", id);
// System.out.println("input: "+id);
Response encodeIdRes = network.getResponse(ids, BasicConfig.MANAGER_ID_ENCODE);
// System.out.println("encodeIdRes: "+encodeIdRes.body().asString());
String encodeId = encodeIdRes.jsonPath().getString("data");
Assert.assertNotNull(encodeId, network.message(ids, BasicConfig.MANAGER_ID_ENCODE, "加密id失败", encodeIdRes.body().asString()));
return encodeId;
}
public static long managerDecodeingId(String code) {
BaseUtils.ssoLogin();
Map<String, Object> decodePar = new HashMap<>();
decodePar.put("code", code);
Response decodeRes = network.getResponse(decodePar, BasicConfig.MANAGER_ID_DECODE);
long decodeId = 0;
try {
decodeId = decodeRes.jsonPath().getLong("data");
}catch (NullPointerException e){
e.printStackTrace();
}
return decodeId;
}
public static String encodingId(Long id, IdConvertBase64Enum base64Enum) {
if (id == null || base64Enum == null || base64Enum.getCode().length() != 3) {
return null;
}
id = (id << 3) ^ 7;
String encode = encoder.encodeToString(Long.toString(id).getBytes());
String replace = encode.replace("=", "");
return base64Enum.getCode() + (encode.length() - replace.length()) + replace;
}
}
package com.oto.utils;
import com.oto.config.BasicConfig;
import com.oto.sql.KjyUserDB;
import com.oto.sql.UserSqlFactory;
import io.restassured.response.Response;
import org.testng.Assert;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JmeterAccountFile {
private static final NetworkUtils network = NetworkUtils.getInstance();
public static void main(String[] args) {
// String path = String.valueOf(JmeterAccountFile.class.getResource("/"));
// accountFile(path);
otoCookieMaker();
}
/**
* 生成otoCookie,仅用于压力测试文件
*/
public static void otoCookieMaker() {
}
//仅用于生成直播账号Authkey文件
public static void accountFile(String path) {
BaseUtils.ssoLogin();
// 保存路径
String file = path + "AccountFile.txt";
// 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw
try {
File accountFile = new File("AccountFile.txt");// 相对路径,如果没有则要建立一个新的output。txt文件
// 判断文件是否存在,不存在即新建
if(!accountFile.exists()) {
accountFile.createNewFile(); // 创建新文件
}
// 如果是在原有基础上写入则append属性为true,默认为false
BufferedWriter out = new BufferedWriter(new FileWriter(accountFile,true));
//获取直播用户id
List<Map<String, Object>> result = KjyUserDB.getInstance().findModeResult(UserSqlFactory.selectUserIdForJmeter);
for (Map<String, Object> item:result
) {
System.out.println(item.get("id"));
Map<String, Object> subscribeParam = new HashMap<>();
subscribeParam.put("liveUserId", item.get("id"));
subscribeParam.put("validDays", 365);
Response subscribeRes = network.getResponse(subscribeParam, BasicConfig.MANAGER_encryptAuthKey);
String data = subscribeRes.jsonPath().getString("data");
Assert.assertNotNull(data, network.message(subscribeParam, BasicConfig.MANAGER_encryptAuthKey, "增加测试用户失败", subscribeRes.body().asString()));
System.out.println(data);
out.write(data+"\t\n"); // 写入TXT
out.flush(); // 把缓存区内容压入文件
}
out.close(); // 最后记得关闭文件
} catch (SQLException throwables) {
throwables.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
package com.oto.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import groovy.json.JsonBuilder;
import io.restassured.response.Response;
import java.util.List;
import java.util.Map;
public class JsonUtil {
private JsonUtil() {
}
public static <T> T parseResponseToBeanTT(Response response, Class<T> tClass) {
Object data = response.jsonPath().getJsonObject("d");
String str = new JsonBuilder(data).toString();
return JSON.parseObject(str, tClass);
}
/**
* 将响应转换成对象
* @param response
* @param tClass
* @param <T>
* @return
*/
public static <T> T parseResponseToBean(Response response, Class<T> tClass){
Object data = response.jsonPath().getJsonObject("data");
String str = new JsonBuilder(data).toString();
return JSON.parseObject(str, tClass);
}
/**
* 分页接口专用-将响应转换成对象
* @param response
* @param tClass
* @param <T>
* @return
*/
public static <T> List<T> parseResponseToPageBean(Response response, Class<T> tClass){
return parseResponseToPageBean(response, tClass,"list");
}
/**
* 分页接口专用-将响应转换成对象
* @param response
* @param tClass
* @param <T>
* @return
*/
public static <T> List<T> parseResponseToPageBean(Response response, Class<T> tClass,String listName){
Object data = response.jsonPath().getJsonObject("data");
String str = new JsonBuilder(data).toString();
JSONObject jsonObject = JSON.parseObject(str);
JSONArray array = jsonObject.getJSONArray(listName);
return array.toJavaList(tClass);
}
public static <T> List<T> parseResponseToListBean(Response response, Class<T> tClass){
Object data = response.jsonPath().getJsonObject("data");
String str = new JsonBuilder(data).toString();
return JSON.parseArray(str, tClass);
}
public static <T> List<T> parseResponseToListBean(Response response, Class<T> tClass, String listName){
Map map = response.jsonPath().getJsonObject("data");
Object data = map.get(listName);
String str = new JsonBuilder(data).toString();
return JSON.parseArray(str, tClass);
}
public static <T> List<T> parseResponsePathToListBean(Response response, String path,Class<T> tClass){
Object data = response.jsonPath().getJsonObject(path);
String str = new JsonBuilder(data).toString();
return JSON.parseArray(str, tClass);
}
}
package com.oto.utils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
/**
* WebSocket工具类
* @author lizhi
* @date 2021/4/19 4:00 下午
*/
public class MyWebSocketUtil {
private static final String URL = "wss://ws.duibatest.com.cn/kws";
private MyWebSocketUtil() {
}
public static void main(String[] args) {
String authKey = "zFNkBc7JtvLPL6ifAfXbcgYH7WrugVmhv4CXQVq1CN1Y2C8pcBXoPvUPFbkWj7HbdkFpe4oX6SLjczK3ruYpQ8EaQ5";
String liveId= "Kj21MjMzMTE";
//连接
MyWebSocketClient client = connect();
//身份认证,识别用户信息
auth(client, authKey);
//进入直播间
enter(client, liveId);
//循环发送心跳,长时间不发消息,链接会断开
for (int i = 0; i < 5; i++) {
hb(client);
ThreadSleepUtils.sleep(5000);
}
//退出直播间
out(client, liveId);
//无意义命令
gt(client);
//关闭连接
close(client);
}
/**
* 创建链接
* @param url 需要链接的地址
* @return WebSocket客户端
*/
public static MyWebSocketClient connect(String url) {
MyWebSocketClient client = new MyWebSocketClient(URI.create(url));
client.connect();
int maxCount = 10;
int count = 0;
// 判断是否连接成功,未成功后面发送消息时会报错
while (!client.getReadyState().equals(ReadyState.OPEN)) {
ThreadSleepUtils.sleep(500);
count++;
if (count >= maxCount) {
System.out.println("WebSocketClient, connect, fail, url=" + url);
return null;
}
}
System.out.println("WebSocketClient, connect, url=" + url);
return client;
}
public static MyWebSocketClient connect() {
return connect(URL);
}
/**
* 授权
* @param client WebSocket客户端
* @param authKey 用户加密信息
*/
public static void auth(WebSocketClient client, String authKey) {
sendTextMsg(client, WebSocketConstant.AUTH_OP + WebSocketConstant.MESSAGE_BODY_SPLIT + authKey);
}
/**
* 进入直播间
* @param client WebSocket客户端
* @param liveId 加密的直播ID
*/
public static void enter(WebSocketClient client, String liveId) {
sendTextMsg(client, WebSocketConstant.ENTER_LIVE_OP + WebSocketConstant.MESSAGE_BODY_SPLIT + liveId + WebSocketConstant.MESSAGE_BODY_SPLIT + "2");
}
/**
* 退出直播间
* @param client WebSocket客户端
* @param liveId 加密的直播ID
*/
public static void out(WebSocketClient client, String liveId) {
sendTextMsg(client, WebSocketConstant.OUT_LIVE_OP + WebSocketConstant.MESSAGE_BODY_SPLIT + liveId);
}
/**
* 发送心跳
* @param client WebSocket客户端
*/
public static void hb(WebSocketClient client) {
sendTextMsg(client, WebSocketConstant.HEART_BEAT);
}
/**
* 无意义命令,用来判断链接是否还可用
* @param client WebSocket客户端
*/
public static void gt(WebSocketClient client) {
sendTextMsg(client, WebSocketConstant.GREETING_OP);
}
/**
* 关闭链接
* @param client WebSocket客户端
*/
public static void close(WebSocketClient client) {
client.closeConnection(0, "ok");
}
/**
* 发送消息
* @param client WebSocket客户端
* @param msg 要发送的消息
*/
private static void sendTextMsg(WebSocketClient client, String msg) {
client.send(msg);
System.out.println("WebSocketClient, sendTextMsg, msg=" + msg);
}
static class WebSocketConstant {
private WebSocketConstant() {}
/**
* websocket消息体的指令和body分隔符
*/
public static final String MESSAGE_BODY_SPLIT = "\r\n";
/**
* websocket身份认证指令
*/
public static final String AUTH_OP = "th";
/**
* ws进入直播指令
*/
public static final String ENTER_LIVE_OP = "en";
/**
* ws退出直播指令
*/
public static final String OUT_LIVE_OP = "out";
/**
* 前端验证通信指令,无意义
*/
public static final String GREETING_OP = "gt";
/**
* 心跳
*/
public static final String HEART_BEAT = "/hb";
}
static class MyWebSocketClient extends WebSocketClient {
public MyWebSocketClient(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
System.out.println("WebSocketClient, onOpen");
}
@Override
public void onMessage(String s) {
System.out.println("WebSocketClient, onMessage, s=" + s);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("WebSocketClient, onClose, code="+ code+", reason=" + reason + ", remote="+remote);
}
@Override
public void onError(Exception e) {
System.out.println("WebSocketClient, onError, e:"+ e.getMessage());
}
}
}
\ No newline at end of file
package com.oto.utils;
import static com.oto.config.BasicConfig.*;
import static io.restassured.RestAssured.*;
import com.alibaba.fastjson.JSONObject;
import io.restassured.response.Response;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class NetworkUtils {
// 代理人的 cookies和headers
public Map<String, Object> agentCookies = new HashMap<String, Object>();
public Map<String, Object> agentHeaders = new HashMap<String, Object>();
public Map<String, Object> fileHeaders = new HashMap<String, Object>();
// 钉钉的 headers
public Map<String, Object> dingTalkHeaders = new HashMap<String, Object>();
private volatile static NetworkUtils network;
// 构造函数 初始化tku、content-type
private NetworkUtils(){
//cookies中的tku
agentCookies.put("tku",AGENT_TKU);
//多场景测试标志
// agentCookies.put("_duibaServiceGroupKey","miria-2652");
//json类型的headers
agentHeaders.put("Content-Type","application/json");
//二进制文件的headers
fileHeaders.put("Content-Type","multipart/form-data");
//钉钉的headers
dingTalkHeaders.put("Content-Type","application/json;charset=utf-8");
}
//单例模式
//通过设置同步代码块,使用DCL双检查锁机制
//使用双检查锁机制成功的解决了单例模式的懒汉实现的线程不安全问题和效率问题
//DCL 也是大多数多线程结合单例模式使用的解决方案
public static NetworkUtils getInstance() {
if (network == null) {
synchronized (NetworkUtils.class) {
if (network == null) {
network = new NetworkUtils();
}
}
}
return network;
}
// get 不带参请求
public Response getResponse(String path) {
Response response = given()
.cookies(agentCookies)
.headers(agentHeaders)
.get(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
System.out.println(response.body().asString());
return response;
}
// get 带参请求
public Response getResponse(Map<String, Object> params, String path) {
Response response = given()
.cookies(agentCookies)
.headers(agentHeaders)
.params(params)
.get(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
System.out.println(response.body().asString());
return response;
}
// post 不帶参请求
public Response postResponse(String path) {
Response response = given()
.cookies(agentCookies)
.headers(agentHeaders)
.post(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
System.out.println(response.body().asString());
return response;
}
// post 带参请求
public Response postResponse(Map<String, Object> params, String path) {
String jsonStr = JSONObject.toJSONString(params);
Response response = given()
.cookies(agentCookies)
.headers(agentHeaders)
.body(jsonStr)
.post(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
System.out.println(response.body().asString());
return response;
}
// post 头部带参请求
public Response postHeaderResponse(Map<String, Object> params, String path) {
Response response = given()
.cookies(agentCookies)
.params(params)
.post(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
System.out.println(response.body().asString());
return response;
}
// post 文件上传
public Response postFileResponse(String filePath, String path){
Response response = given()
.cookies(agentCookies)
.headers(fileHeaders)
.multiPart("file",new File(filePath))
.post(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
return response;
}
// post xml请求方式
public Response postXMLResponse(String str, String path) {
Response response = given()
.cookies(agentCookies)
.headers(agentHeaders)
.body(str)
.post(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
return response;
}
// 管理后台
public Response getManagerCookies(String path){
Response response = given().
cookies(agentCookies).
redirects().
follow(false).
get(path);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,path=【"+path+"】 code=【"+response.statusCode()+"】");
}
return response;
}
// post 钉钉机器人
public Response dingTalkRobot(Map<String, Object> params) {
String jsonStr = JSONObject.toJSONString(params);
Response response = given()
.headers(dingTalkHeaders)
.body(jsonStr)
.post(dingTalkPath);
if (!Objects.equals(response.statusCode(),200)){
System.out.println("请求状态码错误,code=【"+response.statusCode()+"】");
}
return response;
}
/**
* 带参的接口完整信息
* @param params 接口参数
* @param path 接口路径
* @param errorMessage 自己打印的错误信息
* @param responseBody 返回的response
* @return 完整的接口信息
*/
public String message(Map<String, Object> params, String path, String errorMessage, String responseBody){
return "\n" + "path: " + path +
"\n" + "params: " + params +
"\n" + "message: " + errorMessage +
"\n" + "response:" + responseBody + "\n";
}
/**
* 不带参的接口完整信息
* @param path 接口路径
* @param errorMessage 自己打印的错误信息
* @param responseBody 返回的response
* @return 完整的接口信息
*/
public String message(String path, String errorMessage, String responseBody){
return "\n" + "path: " + path +
"\n" + "message: " + errorMessage +
"\n" + "response:" + responseBody + "\n";
}
}
package com.oto.utils;
//延时
public class ThreadSleepUtils {
private ThreadSleepUtils() {}
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="客集集" verbose="1" thread-count="3">
<suite-files>
<suite-file path="workTestNG.xml"></suite-file>
</suite-files>
<!-- 监听器-->
<listeners>
<listener class-name="com.oto.config.ExtentTestNGIReporterListener"/>
</listeners>
</suite>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="保险OTO" verbose="1" thread-count="3">
<test preserve-order="true" name="销售管理">
<classes>
<class name="com.oto.cases.otoseller.Manager"/>
</classes>
</test>
<test preserve-order="true" name="销售工作台PC端">
<classes>
<class name="com.oto.cases.otoseller.Work"/>
</classes>
</test>
<test preserve-order="true" name="销售工作台手机端">
<classes>
<class name="com.oto.cases.otoseller.Phone"/>
</classes>
</test>
</suite>
<!-- Suite -->
<!--
suite定义一个测试套件,可以设置是否使用多线程,可包含多个测试用例或者测试group
parallel = classes  每个测试用例class级别多线程
thread-count =3  线程数为5,可同时执行3个case
preserve-order = true   classes和methods按照配置中的顺序执行,false为乱序执行。(If you want the classes and methods listed in this file to be run in an unpredictible order, set the preserve-order attribute to false)
parameter 标签传递参数
-->
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment