提交 337e4248 authored 作者: 黄承天's avatar 黄承天

取消队列机制

优化实时显示机制
上级 39c4b8bb
package com.zjty.autotest.config;
import org.apache.catalina.session.StandardSessionFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
@Configuration
public class WebSocketConfig {
public class WebSocketConfig extends ServerEndpointConfig.Configurator{
private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);
/**
* 修改握手信息
*/
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
StandardSessionFacade ssf = (StandardSessionFacade) request.getHttpSession();
if (ssf != null) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
//关键操作
sec.getUserProperties().put("sessionId", httpSession.getId());
log.info("获取到的SessionID:" + httpSession.getId());
}
super.modifyHandshake(sec, request, response);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
......
package com.zjty.autotest.controller;
import com.zjty.autotest.mq.TestTask;
import com.zjty.autotest.pojo.sjq.AutoResultSet;
import com.zjty.autotest.pojo.sjq.TestChannel;
import com.zjty.autotest.pojo.sjq.TestReport;
import com.zjty.autotest.pojo.sjq.common.AppHttpCodeEnum;
import com.zjty.autotest.pojo.sjq.common.PageResult;
import com.zjty.autotest.pojo.sjq.common.ResponseResult;
import com.zjty.autotest.pojo.test.Project;
import com.zjty.autotest.service.AutoResultSetService;
import com.zjty.autotest.service.TestReportService;
import com.zjty.autotest.service.TransHelper;
import com.zjty.autotest.service.impl.SeleniumExecutor;
import com.zjty.autotest.util.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -15,49 +19,81 @@ import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* @author C
*/
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@RestController
@CrossOrigin
@RequestMapping("/auto")
@Api(value = "自动测评管理接口",description = "自动测评管理接口,提供页面的增、删、改、查")
@Api(value = "自动测评管理接口", description = "自动测评管理接口,提供页面的增、删、改、查")
public class AutoResultSetController {
@Autowired
private AutoResultSetService autoResultSetService;
@Autowired
private TestReportService testReportService;
@Autowired
private SeleniumExecutor seleniumExecutor;
@Autowired
private TransHelper transHelper;
@Autowired
private IdWorker idWorker;
@ApiOperation("根据条件分页排序查询")
@RequestMapping(value = "/search/id/{id}", method = RequestMethod.POST)
public ResponseResult findSearch(@PathVariable String id) {
return ResponseResult.okResult(autoResultSetService.findById(id));
}
/**
* 分页+多条件查询
* @param searchMap 查询条件封装
* @param page 页码
* @param size 页大小
* @return 分页结果
*/
* 分页+多条件查询
*
* @param searchMap 查询条件封装
* @param page 页码
* @param size 页大小
* @return 分页结果
*/
@ApiOperation("根据条件分页排序查询")
@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
public ResponseResult findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
@RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
public ResponseResult findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
Page<AutoResultSet> pageList = autoResultSetService.findSearch(searchMap, page, size);
return ResponseResult.okResult(new PageResult<>(pageList.getTotalElements(), pageList.getContent()) );
return ResponseResult.okResult(new PageResult<>(pageList.getTotalElements(), pageList.getContent()));
}
@ApiOperation("根据id删除")
@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
public ResponseResult delete(@PathVariable String id ){
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseResult delete(@PathVariable String id) {
return autoResultSetService.deleteByid(id);
}
@ApiOperation("新增")
@RequestMapping(method=RequestMethod.POST)
public ResponseResult add(@RequestBody TestChannel testChannel ){
return autoResultSetService.addResultSet(testChannel);
@RequestMapping(method = RequestMethod.POST)
public ResponseResult add(@RequestBody TestChannel testChannel) {
Project project = transHelper.toProject(testChannel);
if (seleniumExecutor.getRunning()) {
return ResponseResult.errorResult(AppHttpCodeEnum.SAVE_ERROR, "已有进行中的测试!");
} else {
String id = autoResultSetService.addResultSet(testChannel);
autoResultSetService.updateByid(id, 0);
CompletableFuture.runAsync(() -> seleniumExecutor.execute(project, id));
AutoResultSet result = autoResultSetService.findById(id);
return ResponseResult.okResult(result);
}
}
@ApiOperation("停止当前进行中的测试")
@GetMapping("/quit")
public ResponseResult quit(){
public ResponseResult quit() {
seleniumExecutor.quit();
return ResponseResult.okResult(200,"ok");
return ResponseResult.okResult(200, "ok");
}
}
......@@ -5,20 +5,20 @@ import java.util.Map;
import java.util.Set;
public class CacheManager {
private static Map<String,Object> cacheMap=new HashMap<>();
private static Map<String,Integer> statusMap=new HashMap<>();
private static Map<String, Object> cacheMap = new HashMap<>();
private static Map<String, Integer> statusMap = new HashMap<>();
public static Object getCache(String key){
public static Object getCache(String key) {
return cacheMap.get(key);
}
public static void putCache(String key,Object obj){
cacheMap.put(key,obj);
public static void putCache(String key, Object obj) {
cacheMap.put(key, obj);
}
public static void removeCache(String key){
public static void removeCache(String key) {
Object o = cacheMap.get(key);
if(o!=null){
if (o != null) {
cacheMap.remove(key);
}
......
......@@ -20,12 +20,12 @@ public class Report {
/**
* 主键
*/
private Integer id;
private String id;
/**
* 所属项目id
*/
private Integer projectId;
private String projectId;
/**
* 测试项目名
......
......@@ -14,6 +14,8 @@ import java.util.List;
@Data
@ApiModel(description = "评测报告类")
public class EvaReport {
@ApiModelProperty(value = "id")
private String id;
@ApiModelProperty(value = "系统名称")
private String projectName;
@ApiModelProperty(value = "浏览器")
......
......@@ -31,5 +31,8 @@ public class PageContentTest {
* 截图的url
*/
private String screenshot;
private List<PageContent> contents;
}
......@@ -5,12 +5,11 @@ import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.List;
/**
* 测试项目
* @author C
*/
@Data
@AllArgsConstructor
......@@ -20,7 +19,7 @@ public class Project {
/**
* 主键
*/
private Integer id;
private String id;
/**
* 项目名称
......@@ -40,7 +39,7 @@ public class Project {
/**
* 是否为快速模式
*/
private Boolean fastmode;
private Boolean fastMode;
/**
* 输入参数
......
package com.zjty.autotest.runner;
import com.zjty.autotest.pojo.sjq.AutoResultSet;
import com.zjty.autotest.service.AutoResultSetService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* <p>Description : autotest
* <p>Date : 2020/5/28 14:49
* <p>@author : C
*/
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@Slf4j
@Component
public class InitRunner implements CommandLineRunner {
@Autowired
AutoResultSetService autoResultSetService;
@Override
public void run(String... args) throws Exception {
log.info("初始化报告状态...");
List<AutoResultSet> resultsForReset = autoResultSetService.findAll().stream()
.filter(autoResultSet -> Objects.equals(autoResultSet.getStatus(), 0))
.collect(Collectors.toList());
for (AutoResultSet resultSet : resultsForReset) {
autoResultSetService.updateByid(resultSet.getId(),2);
}
log.info("初始化完毕...");
}
}
......@@ -6,9 +6,17 @@ import com.zjty.autotest.pojo.sjq.TestReport;
import com.zjty.autotest.pojo.sjq.common.ResponseResult;
import org.springframework.data.domain.Page;
import java.util.List;
import java.util.Map;
/**
* @see com.zjty.autotest.service.impl.AutoResultSetServiceImpl
*/
public interface AutoResultSetService {
List<AutoResultSet> findAll();
AutoResultSet findById(String id);
/**
* 根据条件分页排序查询
*/
......@@ -25,10 +33,11 @@ public interface AutoResultSetService {
* @return
*/
ResponseResult updateByid(String id,Integer status);
/**
* 新增
*/
ResponseResult addResultSet(TestChannel testChannel);
String addResultSet(TestChannel testChannel);
/**
* 上传前端源代码
*/
......
......@@ -6,6 +6,9 @@ import com.zjty.autotest.pojo.sjq.common.ResponseResult;
import java.util.Map;
/**
* @see com.zjty.autotest.service.impl.TestReportServiceImpl
*/
public interface TestReportService{
ResponseResult deleteByResultId(String id);
......
package com.zjty.autotest.service;
import com.alibaba.fastjson.JSON;
import com.zjty.autotest.mq.TestTask;
import com.zjty.autotest.pojo.report.ElementDetail;
import com.zjty.autotest.pojo.report.Measure;
import com.zjty.autotest.pojo.sjq.*;
import com.zjty.autotest.pojo.test.Input;
import com.zjty.autotest.pojo.test.Project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Objects.nonNull;
/**
* @author C
*/
@SuppressWarnings({"SpringAutowiredFieldsWarningInspection"})
@Service
public class TransHelper {
@Autowired
TestTask task;
public TestReport toTestReport(EvaReport evaReport,String id){
String out = JSON.toJSONString(evaReport);
TestReport testReport = new TestReport();
testReport.setResultId(id);
testReport.setOutReport(out);
return testReport;
}
public Project toProject(TestChannel testChannel){
Project project = new Project();
project.setBrowser(testChannel.getBrowser().toLowerCase());
project.setName(testChannel.getName());
project.setUrl(testChannel.getUrl());
project.setFastMode(testChannel.getFastMode());
List<RuleSet> ruleSets = testChannel.getRuleSets();
List<Input> inputs = new ArrayList<>();
project.setInputs(null);
if (ruleSets != null) {
for (RuleSet ruleSet : ruleSets) {
Input input = new Input();
input.setKey(ruleSet.getDes());
input.setAttrName(ruleSet.getCommand());
input.setAttrValue(ruleSet.getTarget());
input.setValue(ruleSet.getValue());
inputs.add(input);
}
project.setInputs(inputs);
}
return project;
}
public EvaReport toEvaReport(Project project, String os, List<Measure> measures) {
EvaReport evaReport = new EvaReport();
evaReport.setId(project.getId());
evaReport.setCreateTime(new Date());
evaReport.setProjectName(project.getName());
evaReport.setBrowser(project.getBrowser());
evaReport.setSystem(os);
evaReport.setUrl(project.getUrl());
if (nonNull(measures)) {
long count = measures.stream().filter(m -> !m.getSuccess()).count();
evaReport.setFailCount(project.getName() + "系统通过测试," + "未通过测试点共0个");
if (count > 0) {
evaReport.setFailCount(project.getName() + "系统未通过测试," + "未通过测试点共" + count + "个");
}
List<FailMessage> failMessages = measures.stream()
.filter(m -> !m.getSuccess())
.map(this::toFailMessage)
.collect(Collectors.toList());
evaReport.setFailMessages(failMessages);
List<PageContentTest> pageContents = measures.stream()
.map(this::toPageContentTest)
.collect(Collectors.toList());
evaReport.setPageContents(pageContents);
List<PageRoute> pageRoutes = measures.stream()
.map(this::toPageRoute)
.collect(Collectors.toList());
evaReport.setPageRoutes(pageRoutes);
}
return evaReport;
}
private FailMessage toFailMessage(Measure measure) {
FailMessage failMessage = new FailMessage();
failMessage.setUrl(measure.getUrl());
failMessage.setMessage(measure.getMessage());
failMessage.setPicture(measure.getScreenshot());
return failMessage;
}
private PageContentTest toPageContentTest(Measure measure) {
PageContentTest pageContentTest = new PageContentTest();
pageContentTest.setUrl(measure.getUrl());
pageContentTest.setMessage(measure.getMessage());
pageContentTest.setResponseTime(measure.getResponseTime());
pageContentTest.setScreenshot(measure.getScreenshot());
pageContentTest.setSuccess(0);
if (measure.getSuccess()) {
pageContentTest.setSuccess(1);
}
List<ElementDetail> elementDetails = measure.getElementDetails();
if (nonNull(elementDetails)) {
List<PageContent> contents = elementDetails.stream().map(this::toPageContent).collect(Collectors.toList());
pageContentTest.setContents(contents);
} else {
pageContentTest.setContents(Collections.emptyList());
}
return pageContentTest;
}
private PageContent toPageContent(ElementDetail elementDetail) {
PageContent pageContent = new PageContent();
pageContent.setParms(elementDetail.getType());
pageContent.setMessage(elementDetail.getMessage());
pageContent.setResponseTime(elementDetail.getResponseTime());
pageContent.setSuccess(0);
if (elementDetail.getSuccess()) {
pageContent.setSuccess(1);
}
return pageContent;
}
private PageRoute toPageRoute(Measure measure) {
PageRoute pageRoute = new PageRoute();
pageRoute.setPageName(measure.getUrl());
pageRoute.setSuccess(0);
if (measure.getSuccess()) {
pageRoute.setSuccess(1);
}
pageRoute.setMessage("无/有");
pageRoute.setPicture(measure.getScreenshot());
pageRoute.setResponseTime(measure.getResponseTime());
return pageRoute;
}
}
......@@ -19,46 +19,50 @@ import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
@Service
public class AutoResultSetServiceImpl implements AutoResultSetService {
@Autowired
private AutoResultSetDao autoResultSetDao;
@Autowired
private TestReportService testReportService;
@Autowired
private IdWorker idWorker;
@Override
public List<AutoResultSet> findAll() {
return autoResultSetDao.findAll();
}
@Override
public AutoResultSet findById(String id) {
return autoResultSetDao.findById(id).orElse(new AutoResultSet());
}
@Override
public Page<AutoResultSet> findSearch(Map whereMap, int page, int size) {
Specification<AutoResultSet> specification = createSpecification(whereMap);
PageRequest pageRequest = PageRequest.of(page-1, size, Sort.Direction.DESC,"createTime");
PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.Direction.DESC, "createTime");
return autoResultSetDao.findAll(specification, pageRequest);
}
/**
* 动态条件构建
*
* @param searchMap
* @return
*/
private Specification<AutoResultSet> createSpecification(Map searchMap) {
return new Specification<AutoResultSet>() {
@Override
public Predicate toPredicate(Root<AutoResultSet> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicateList = new ArrayList<Predicate>();
if (searchMap.get("projectName") != null && !"".equals(searchMap.get("projectName"))) {
predicateList.add(cb.like(root.get("projectName").as(String.class), "%" + (String) searchMap.get("projectName") + "%"));
}
return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
return (root, query, cb) -> {
List<Predicate> predicateList = new ArrayList<>();
if (searchMap.get("projectName") != null && !"".equals(searchMap.get("projectName"))) {
predicateList.add(cb.like(root.get("projectName").as(String.class), "%" + (String) searchMap.get("projectName") + "%"));
}
return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
};
}
......@@ -67,7 +71,7 @@ public class AutoResultSetServiceImpl implements AutoResultSetService {
try {
autoResultSetDao.deleteById(id);
testReportService.deleteByResultId(id);
}catch (Exception e){
} catch (Exception e) {
return ResponseResult.okResult(AppHttpCodeEnum.SAVE_ERROR);
}
......@@ -75,9 +79,9 @@ public class AutoResultSetServiceImpl implements AutoResultSetService {
}
@Override
public ResponseResult updateByid(String id,Integer status) {
public ResponseResult updateByid(String id, Integer status) {
Optional<AutoResultSet> optional = autoResultSetDao.findById(id);
if(optional.isPresent()){
if (optional.isPresent()) {
AutoResultSet autoResultSet = optional.get();
autoResultSet.setStatus(status);
autoResultSet.setUpdateTime(new Date());
......@@ -88,32 +92,23 @@ public class AutoResultSetServiceImpl implements AutoResultSetService {
}
@Override
public ResponseResult addResultSet(TestChannel testChannel) {
String tid=idWorker.nextId()+"";
AutoResultSet autoResultSet=new AutoResultSet();
public String addResultSet(TestChannel testChannel) {
String tid = idWorker.nextId() + "";
AutoResultSet autoResultSet = new AutoResultSet();
autoResultSet.setId(tid);
autoResultSet.setProjectName(testChannel.getName());
autoResultSet.setUser(testChannel.getUser());
autoResultSet.setCreateTime(new Date());
autoResultSet.setUpdateTime(new Date());
autoResultSet.setStatus(0);
AutoResultSet save = autoResultSetDao.save(autoResultSet);
autoResultSetDao.save(autoResultSet);
String in = JSON.toJSONString(testChannel);
TestReport testReport = new TestReport();
testReport.setId(idWorker.nextId()+"");
testReport.setId(idWorker.nextId() + "");
testReport.setResultId(tid);
testReport.setStatus(0);
testReport.setInputReport(in);
testReportService.save(testReport);
CacheManager.putCache(tid,testChannel);
//将数据保存到队列
try {
QueueManager.put(tid);
return ResponseResult.okResult(save);
} catch (Exception e) {
e.printStackTrace();
return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,e.getMessage());
}
return tid;
}
}
......@@ -8,12 +8,19 @@ import com.zjty.autotest.common.action.LabelType;
import com.zjty.autotest.pojo.report.ElementDetail;
import com.zjty.autotest.pojo.report.Measure;
import com.zjty.autotest.pojo.report.Report;
import com.zjty.autotest.pojo.sjq.AutoResultSet;
import com.zjty.autotest.pojo.sjq.EvaReport;
import com.zjty.autotest.pojo.sjq.TestReport;
import com.zjty.autotest.pojo.test.ElementEntry;
import com.zjty.autotest.pojo.test.ElementFeature;
import com.zjty.autotest.pojo.test.Input;
import com.zjty.autotest.pojo.test.Project;
import com.zjty.autotest.service.AutoResultSetService;
import com.zjty.autotest.service.TestReportService;
import com.zjty.autotest.service.TransHelper;
import com.zjty.autotest.util.FileUtil;
import com.zjty.autotest.util.WebDriverUtil;
import com.zjty.autotest.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.jsoup.nodes.Element;
......@@ -25,6 +32,7 @@ import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Sleeper;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.net.www.protocol.file.FileURLConnection;
......@@ -38,17 +46,30 @@ import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static com.alibaba.fastjson.JSON.toJSONString;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
/**
* @author C
*/
@SuppressWarnings("FieldCanBeLocal")
@SuppressWarnings({"FieldCanBeLocal", "SpringAutowiredFieldsWarningInspection"})
@Slf4j
@Service
public class SeleniumExecutor {
@Autowired
TransHelper transHelper;
@Autowired
WebSocketServer webSocketServer;
@Autowired
AutoResultSetService autoResultSetService;
@Autowired
TestReportService testReportService;
@Value("${selenium.executor.wait-time}")
private Long waitTime;
......@@ -82,7 +103,18 @@ public class SeleniumExecutor {
private Boolean isRunning = false;
private String currentTestId;
public Boolean getRunning() {
return isRunning;
}
public String getCurrentTestId() {
return currentTestId;
}
/**
* 当前进行的窗口页
*/
private String currentWindow;
......@@ -92,8 +124,9 @@ public class SeleniumExecutor {
*/
private String currentUrl;
public Report execute(Project project) {
public TestReport execute(Project project, String id) {
isRunning = true;
currentTestId = id;
historyUrls.clear();
urlQueue.clear();
clickElementQueue.clear();
......@@ -113,19 +146,39 @@ public class SeleniumExecutor {
measures.add(measure);
}
currentUrl = urlQueue.poll();
if (isNull(currentUrl)) {
autoResultSetService.updateByid(currentTestId, 1);
}
EvaReport report = transHelper.toEvaReport(project, os, measures);
report.setId(id);
sendWebSocketMeasures(report);
}
driver.quit();
} catch (Exception e) {
log.error("发生预料外的异常.测试结束:" + e);
e.printStackTrace();
isRunning = false;
autoResultSetService.updateByid(currentTestId, 2);
sendWebSocketResult(2, currentTestId);
}
return new Report(
null,
project.getId(),
project.getName(),
project.getBrowser(),
os,
measures
);
driver.quit();
autoResultSetService.updateByid(currentTestId, 1);
sendWebSocketResult(1, currentTestId);
isRunning = false;
EvaReport report = transHelper.toEvaReport(project, os, measures);
TestReport testReport = transHelper.toTestReport(report, id);
testReportService.update(testReport);
return testReport;
}
private void sendWebSocketMeasures(EvaReport report) {
webSocketServer.sendToAll(toJSONString(report));
}
private void sendWebSocketResult(Integer status, String id) {
AutoResultSet resultSet = new AutoResultSet();
resultSet.setStatus(status);
resultSet.setId(id);
webSocketServer.sendToAll(toJSONString(resultSet));
}
public void quit() {
......@@ -343,6 +396,8 @@ public class SeleniumExecutor {
message = "元素布局错误";
success = false;
log.error("元素布局错误");
} catch (StaleElementReferenceException e) {
log.error("元素过期");
} catch (Exception e) {
message = "出现预料之外的错误";
success = false;
......
......@@ -29,144 +29,151 @@ import org.springframework.util.StringUtils;
/**
* 服务层
*
* @author Administrator
*
* @author Administrator
*/
@Service
public class TestReportServiceImpl implements TestReportService {
@Autowired
private TestReportDao testReportDao;
@Autowired
private IdWorker idWorker;
/**
* 查询全部列表
* @return
*/
public List<TestReport> findAll() {
return testReportDao.findAll();
}
/**
* 根据ID查询实体
* @param id
* @return
*/
public TestReport findById(String id) {
return testReportDao.findById(id).get();
}
/**
* 增加
* @param testReport
*/
@Transient
public void add(TestReport testReport) {
testReport.setId( idWorker.nextId()+"" );
testReportDao.save(testReport);
}
@Transient
/**
* 修改
* @param testReport
*/
@Override
public void update(TestReport testReport) {
testReportDao.updateOut(testReport.getOutReport(),testReport.getResultId());
}
/**
* 删除
* @param resultId
*/
@Transient
@Override
public ResponseResult deleteByResultId(String resultId) {
int i = testReportDao.deleteByResultId(resultId);
return ResponseResult.okResult(i);
}
@Transient
@Override
public ResponseResult save(TestReport testReport) {
testReportDao.save(testReport);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
@Transient
@Override
public ResponseResult addInReport(String id, String inReport) {
TestReport testReport=new TestReport();
testReport.setResultId(id);
testReport.setId(idWorker.nextId()+"");
testReport.setInputReport(inReport);
testReport.setOutReport("");
testReportDao.save(testReport);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
@Override
public ResponseResult findByIdInData(String resultId) {
String in = testReportDao.findByInResultId(resultId);
if(StringUtils.isEmpty(in)){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
return ResponseResult.okResult(in);
}
@Override
public TestReport findByResultId(String resultId) {
TestReport testReport = testReportDao.findByResultId(resultId);
return testReport;
}
@Override
public ResponseResult findByIdOutData(String resultId) {
String out = testReportDao.findByOutResultId(resultId);
if(StringUtils.isEmpty(out)){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
return ResponseResult.okResult(out);
}
@Override
public ResponseResult findStatus(Map searchMap) {
Specification<TestReport> specification = createSpecification(searchMap);
List<TestReport> testReports = testReportDao.findAll(specification);
return ResponseResult.okResult(testReports);
}
@Override
public ResponseResult findAllStatus() {
List<Map<String, Object>> allStatus = testReportDao.findAllStatus();
for (Map<String, Object> status : allStatus) {
}
return ResponseResult.okResult(allStatus);
}
/**
* 动态条件构建
* @param searchMap
* @return
*/
private Specification<TestReport> createSpecification(Map searchMap) {
return new Specification<TestReport>() {
@Override
public Predicate toPredicate(Root<TestReport> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicateList = new ArrayList<Predicate>();
if (searchMap.get("resultId") != null && !"".equals(searchMap.get("resultId"))) {
predicateList.add(cb.like(root.get("resultId").as(String.class), "%" + (String) searchMap.get("resultId") + "%"));
}
return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
}
};
}
@Autowired
private TestReportDao testReportDao;
@Autowired
private IdWorker idWorker;
/**
* 查询全部列表
*
* @return
*/
public List<TestReport> findAll() {
return testReportDao.findAll();
}
/**
* 根据ID查询实体
*
* @param id
* @return
*/
public TestReport findById(String id) {
return testReportDao.findById(id).get();
}
/**
* 增加
*
* @param testReport
*/
@Transient
public void add(TestReport testReport) {
testReport.setId(idWorker.nextId() + "");
testReportDao.save(testReport);
}
@Transient
/**
* 修改
* @param testReport
*/
@Override
public void update(TestReport testReport) {
testReportDao.updateOut(testReport.getOutReport(), testReport.getResultId());
}
/**
* 删除
*
* @param resultId
*/
@Transient
@Override
public ResponseResult deleteByResultId(String resultId) {
int i = testReportDao.deleteByResultId(resultId);
return ResponseResult.okResult(i);
}
@Transient
@Override
public ResponseResult save(TestReport testReport) {
testReportDao.save(testReport);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
@Transient
@Override
public ResponseResult addInReport(String id, String inReport) {
TestReport testReport = new TestReport();
testReport.setResultId(id);
testReport.setId(idWorker.nextId() + "");
testReport.setInputReport(inReport);
testReport.setOutReport("");
testReportDao.save(testReport);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
@Override
public ResponseResult findByIdInData(String resultId) {
String in = testReportDao.findByInResultId(resultId);
if (StringUtils.isEmpty(in)) {
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
return ResponseResult.okResult(in);
}
@Override
public TestReport findByResultId(String resultId) {
TestReport testReport = testReportDao.findByResultId(resultId);
return testReport;
}
@Override
public ResponseResult findByIdOutData(String resultId) {
String out = testReportDao.findByOutResultId(resultId);
if (StringUtils.isEmpty(out)) {
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
return ResponseResult.okResult(out);
}
@Override
public ResponseResult findStatus(Map searchMap) {
Specification<TestReport> specification = createSpecification(searchMap);
List<TestReport> testReports = testReportDao.findAll(specification);
return ResponseResult.okResult(testReports);
}
@Override
public ResponseResult findAllStatus() {
List<Map<String, Object>> allStatus = testReportDao.findAllStatus();
for (Map<String, Object> status : allStatus) {
}
return ResponseResult.okResult(allStatus);
}
/**
* 动态条件构建
*
* @param searchMap
* @return
*/
private Specification<TestReport> createSpecification(Map searchMap) {
return new Specification<TestReport>() {
@Override
public Predicate toPredicate(Root<TestReport> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicateList = new ArrayList<Predicate>();
if (searchMap.get("resultId") != null && !"".equals(searchMap.get("resultId"))) {
predicateList.add(cb.like(root.get("resultId").as(String.class), "%" + (String) searchMap.get("resultId") + "%"));
}
return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
}
};
}
}
......@@ -41,13 +41,6 @@ public class WebDriverUtil {
return new FirefoxDriver();
} else if (Objects.equals(browser.toLowerCase(), Browser.CHROME)) {
System.setProperty("webdriver.chrome.driver", WebDriverUtil.CHROME + end);
ChromeOptions options = new ChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
options.addArguments("--headless");
options.addArguments("--disable-gpu");
options.addArguments("--no-sandbox");
return new ChromeDriver();
} else if (Objects.equals(browser.toLowerCase(), Browser.IE)) {
System.setProperty("webdriver.ie.driver", WebDriverUtil.IE + end);
......
package com.zjty.autotest.websocket;
import javax.websocket.Session;
import java.util.concurrent.ConcurrentHashMap;
/**
* <p>Description : autotest
* <p>Date : 2020/5/27 14:45
* <p>@author : C
*/
class WebSocketCache {
/**
* concurrent包的线程安全Map,用来存放每个客户端对应的MyWebSocket对象。
*/
static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();
}
package com.zjty.autotest.websocket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/imserver/{userId}")
import static com.zjty.autotest.websocket.WebSocketCache.webSocketMap;
/**
* @author C
*/
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@ServerEndpoint("/imserver/{id}")
@Component
@Slf4j
public class WebSocketServer {
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收userId
*/
private String userId = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
//加入set中
} else {
webSocketMap.put(userId, this);
//加入set中
addOnlineCount();
//在线数加1
}
log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("用户:" + userId + ",网络异常!!!!!!");
}
public void onOpen(Session session, @PathParam("id") String id) {
webSocketMap.put(id, session);
log.info("建立连接:" + id);
this.sendMessage(id, "连接成功");
log.info("当前连接Map:" + webSocketMap);
}
/**
......@@ -63,12 +34,12 @@ public class WebSocketServer {
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//从set中删除
subOnlineCount();
for (String id : webSocketMap.keySet()) {
if (webSocketMap.get(id).isOpen()) {
webSocketMap.remove(id);
}
}
log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
log.info("连接断开");
}
/**
......@@ -77,69 +48,41 @@ public class WebSocketServer {
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户消息:" + userId + ",报文:" + message);
//可以群发消息
//消息保存到数据库、redis
/*if(StringUtils.isNotBlank(message)){
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUserId",this.userId);
String toUserId=jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
}else{
log.error("请求的userId:"+toUserId+"不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
}catch (Exception e){
e.printStackTrace();
}
}*/
public void onMessage(String message) {
log.info("收到消息:" + message);
}
/**
* @param session
* @param error
* @param error 异常对象
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
public void onError(Throwable error) {
log.error("WebSocket错误,原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送自定义消息
*/
public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
log.info("发送消息到:" + userId + ",报文:" + message);
if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).sendMessage(message);
} else {
log.error("用户" + userId + ",不在线!");
public void sendMessage(String id, String message) {
log.info("发送消息到:" + id + " 内容:" + message);
Session session = webSocketMap.get(id);
try {
if (session.isOpen()) {
session.getBasicRemote().sendText(message);
} else {
webSocketMap.remove(id);
}
} catch (IOException e) {
log.error("推送失败:{}", e);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
public void sendToAll(String message) {
log.info("发送到全部连接:" + webSocketMap);
for (String id : webSocketMap.keySet()) {
sendMessage(id, message);
}
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1"><link rel=icon href=favicon.ico><title>assessment</title><link href=static/css/serviceConfig.531b50e8.css rel=prefetch><link href=static/js/serviceConfig.3e073988.js rel=prefetch><link href=static/css/app.c9629174.css rel=preload as=style><link href=static/css/chunk-vendors.0ffa3bea.css rel=preload as=style><link href=static/js/app.098bb86b.js rel=preload as=script><link href=static/js/chunk-vendors.99d377c1.js rel=preload as=script><link href=static/css/chunk-vendors.0ffa3bea.css rel=stylesheet><link href=static/css/app.c9629174.css rel=stylesheet></head><body><noscript><strong>We're sorry but adapter doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id=app></div><script src=static/js/chunk-vendors.99d377c1.js></script><script src=static/js/app.098bb86b.js></script></body></html>
\ No newline at end of file
<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1"><link rel=icon href=favicon.ico><title>assessment</title><link href=static/css/serviceConfig.921ae081.css rel=prefetch><link href=static/js/serviceConfig.949c2f1d.js rel=prefetch><link href=static/css/app.c9629174.css rel=preload as=style><link href=static/css/chunk-vendors.0ffa3bea.css rel=preload as=style><link href=static/js/app.c483b0aa.js rel=preload as=script><link href=static/js/chunk-vendors.828b9f9e.js rel=preload as=script><link href=static/css/chunk-vendors.0ffa3bea.css rel=stylesheet><link href=static/css/app.c9629174.css rel=stylesheet></head><body><noscript><strong>We're sorry but adapter doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id=app></div><script src=static/js/chunk-vendors.828b9f9e.js></script><script src=static/js/app.c483b0aa.js></script></body></html>
\ No newline at end of file
......@@ -19,7 +19,6 @@ spring.servlet.multipart.max-request-size=500MB
logging.file.path=./log
screenshot-path=/home/tykj/hct/auto/image
selenium.executor.wait-time=2
selenium.executor.fast-mode=false
package com.zjty.autotest;
import com.google.common.collect.Lists;
import com.zjty.autotest.common.action.Browser;
import com.zjty.autotest.pojo.report.Measure;
import com.zjty.autotest.pojo.report.Report;
import com.zjty.autotest.pojo.test.ElementFeature;
import com.zjty.autotest.pojo.test.Input;
import com.zjty.autotest.pojo.test.JavaScriptError;
import com.zjty.autotest.pojo.test.Project;
import com.zjty.autotest.service.impl.SeleniumExecutor;
import com.zjty.autotest.util.WebDriverUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.logging.Logs;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.support.ui.Sleeper;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.Objects;
@Slf4j
@SpringBootTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class AutotestApplicationTests {
@Autowired
......@@ -44,52 +36,66 @@ class AutotestApplicationTests {
@Test
public void execute() throws InterruptedException {
String url = "file:///C:/code/errorTest.html";
// String url = "https://workbook.zjtys.com.cn/#/login";
test1(url);
test3();
}
private void test1(String url){
// GeckoDriver v0.26.0
FirefoxOptions options = new FirefoxOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
// options.setPageLoadStrategy(PageLoadStrategy.EAGER);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
private void test1() {
System.out.println("等待30秒...");
try {
Sleeper.SYSTEM_SLEEPER.sleep(Duration.ofSeconds(30));
} catch (InterruptedException e) {
e.printStackTrace();
}
seleniumExecutor.quit();
System.out.println("关闭测试...");
}
WebDriver driver = new FirefoxDriver(options);
driver.get(url);
driver.findElement(By.xpath("/html/body/button[1]")).click();
driver.findElement(By.xpath("/html/body/button[2]")).click();
driver.findElement(By.xpath("/html/body/button[3]")).click();
driver.findElement(By.xpath("/html/body/button[4]")).click();
driver.findElement(By.xpath("/html/body/button[5]")).click();
for (LogEntry logEntry : driver.manage().logs().get(LogType.BROWSER)) {
System.out.println(String.format("[%s] [%s]", logEntry.getLevel(), logEntry.getMessage()));
private void test2() {
String url1 = "file:///C:/Users/C/Documents/WeChat%20Files/c18042003295/FileStorage/File/2020-03/errorFile/error7.html";
String url2 = "https://www.google.com";
String url3 = "http://www.zjtys.com.cn/zjty/view/home/index.html";
WebDriver driver = new ChromeDriver();
driver.get(url1);
try {
List<LogEntry> entries = driver.manage().logs().get(LogType.BROWSER).getAll();
for (LogEntry entry : entries) {
System.out.println(entry.getMessage());
}
} catch (Exception e) {
log.error("出现异常:" + e);
}
driver.quit();
}
private void test2(String url) {
List<Input> inputs = Lists.newArrayList();
inputs.add(new Input(null, null, null, "caozuoyuan123"));
inputs.add(new Input(null, null, null, "caozuoyuan"));
private void test3() {
String url1 = "file:///C:/Users/C/Documents/WeChat%20Files/c18042003295/FileStorage/File/2020-03/errorFile/error1.html";
String url2 = "https://workbook.zjtys.com.cn/#/login";
String url3 = "http://www.zjtys.com.cn/zjty/view/home/index.html";
String url4 = "https://bbs.colg.cn/forum.php";
String url5 = "https://www.google.com/";
String url6 = "https://mail.qq.com/";
String url7 = "https://git.yfzx.zjtys.com.cn/users/sign_in";
List<Input> inputs = Lists.newArrayList();
inputs.add(new Input(null, null, null, "王永磊"));
inputs.add(new Input(null, null, null, "qwer1234"));
Project project = new Project(
null,
null,
"firefox",
url,
Browser.CHROME,
url1,
false,
inputs
);
Report report = seleniumExecutor.execute(project);
for (Measure measure : report.getMeasures()) {
System.out.println(measure);
}
}
private ElementFeature toFeature(WebElement element) {
return new ElementFeature(
element.getTagName(),
element.getText(),
element.getRect()
);
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论