How to use noKillSwitch method of org.evomaster.client.java.controller.internal.EMController class

Best EvoMaster code snippet using org.evomaster.client.java.controller.internal.EMController.noKillSwitch

Source:EMController.java Github

copy

Full Screen

...36@Path("")37@Produces(Formats.JSON_V1)38public class EMController {39 /**40 * WARNING: make sure to call this inside a noKillSwitch41 */42 private final SutController sutController;43 /**44 * Keep track of the ID of last executed SQL command.45 * This is done to avoid repeating the same command (even if in a POST,46 * it could happen due to bugs in Jersey)47 */48 private volatile Integer lastSqlCommandId = null;49 private String baseUrlOfSUT;50 /**51 * Keep track of all host:port clients connect so far.52 * This is the mainly done for debugging, to check that we are using53 * a single TCP connection, instead of creating new ones at each request.54 *55 * However, we want to check it only during testing56 */57 private static final Set<String> connectedClientsSoFar = new CopyOnWriteArraySet<>();58 private static final String htmlWarning =59 //ah! the beauty and elegance of Java when one just wants read a text resource as a string...60 new Scanner(EMController.class.getResourceAsStream("/warning.html"), "UTF-8").useDelimiter("\\A").next();61 public EMController(SutController sutController) {62 this.sutController = Objects.requireNonNull(sutController);63 }64 private boolean trackRequestSource(HttpServletRequest request){65 String source = request.getRemoteAddr() + ":" + request.getRemotePort();66 connectedClientsSoFar.add(source);67 return true;68 }69 /**70 * Only used for debugging/testing71 *72 * @return host:port of all clients connected so far73 */74 public static Set<String> getConnectedClientsSoFar() {75 return connectedClientsSoFar;76 }77 /**78 * Only used debugging/testing79 */80 public static void resetConnectedClientsSoFar(){81 connectedClientsSoFar.clear();82 }83 @Path("/")84 @GET85 @Produces(MediaType.TEXT_HTML)86 public Response getWarning(){87 return Response.status(400).entity(htmlWarning).build();88 }89 /**90 * This is tricky, and mainly an issue when dealing with embedded driver, where the kill-switch91 * could impact when calling Driver methods using the SUT (eg, ctx.isRunning()).92 */93 private <T> T noKillSwitch(Producer<T> lambda){94 boolean previous = ExecutionTracer.isKillSwitch();95 ExecutionTracer.setKillSwitch(false);96 T t = lambda.call();97 ExecutionTracer.setKillSwitch(previous);98 return t;99 }100 private void noKillSwitch(Runnable lambda){101 boolean previous = ExecutionTracer.isKillSwitch();102 ExecutionTracer.setKillSwitch(false);103 lambda.run();104 ExecutionTracer.setKillSwitch(previous);105 }106 private void noKillSwitchForceCheck(Runnable lambda){107 /*108 Note: bit tricky for External. the calls on ExecutionTracer would have109 no impact, only those on sutController. it is needed for when driver communicates110 with SUT as part of driver operations, eg reset/seed state via an API call, which is111 done for example in Proxyprint. But for all other cases, it can be just an unnecessary112 overhead.113 */114 boolean previous = ExecutionTracer.isKillSwitch();115 sutController.setKillSwitch(false);116 lambda.run();117 sutController.setKillSwitch(previous);118 }119 @Path(ControllerConstants.INFO_SUT_PATH)120 @GET121 public Response getSutInfo(@Context HttpServletRequest httpServletRequest) {122 String connectionHeader = httpServletRequest.getHeader("Connection");123 if( connectionHeader == null124 || !connectionHeader.equalsIgnoreCase("keep-alive")){125 return Response.status(400).entity(WrappedResponseDto126 .withError("Requests should always contain a 'Connection: keep-alive'")).build();127 }128 assert trackRequestSource(httpServletRequest);129 if(! noKillSwitch(() -> sutController.verifySqlConnection())){130 String msg = "SQL drivers are misconfigured. You must use a 'p6spy' wrapper when you " +131 "run the SUT. For example, a database connection URL like 'jdbc:h2:mem:testdb' " +132 "should be changed into 'jdbc:p6spy:h2:mem:testdb'. " +133 "See documentation on how to configure P6Spy.";134 SimpleLogger.error(msg);135 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();136 }137 SutInfoDto dto = new SutInfoDto();138 dto.isSutRunning = noKillSwitch(() -> sutController.isSutRunning());139 dto.baseUrlOfSUT = baseUrlOfSUT;140 dto.infoForAuthentication = noKillSwitch(() -> sutController.getInfoForAuthentication());141 dto.sqlSchemaDto = noKillSwitch(() -> sutController.getSqlDatabaseSchema());142 dto.defaultOutputFormat = noKillSwitch(() -> sutController.getPreferredOutputFormat());143 ProblemInfo info = noKillSwitch(() -> sutController.getProblemInfo());144 if (info == null) {145 String msg = "Undefined problem type in the EM Controller";146 SimpleLogger.error(msg);147 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();148 } else if (info instanceof RestProblem) {149 RestProblem rp = (RestProblem) info;150 dto.restProblem = new RestProblemDto();151 dto.restProblem.swaggerJsonUrl = rp.getSwaggerJsonUrl();152 dto.restProblem.endpointsToSkip = rp.getEndpointsToSkip();153 } else if( info instanceof GraphQlProblem){154 GraphQlProblem p = (GraphQlProblem) info;155 dto.graphQLProblem = new GraphQLProblemDto();156 dto.graphQLProblem.endpoint = p.getEndpoint();157 }else {158 String msg = "Unrecognized problem type: " + info.getClass().getName();159 SimpleLogger.error(msg);160 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();161 }162 dto.unitsInfoDto = noKillSwitch(() -> sutController.getUnitsInfoDto());163 if(dto.unitsInfoDto == null){164 String msg = "Failed to extract units info";165 SimpleLogger.error(msg);166 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();167 }168 return Response.status(200).entity(WrappedResponseDto.withData(dto)).build();169 }170 @Path(ControllerConstants.CONTROLLER_INFO)171 @GET172 public Response getControllerInfoDto(@Context HttpServletRequest httpServletRequest) {173 assert trackRequestSource(httpServletRequest);174 ControllerInfoDto dto = new ControllerInfoDto();175 dto.fullName = noKillSwitch(() -> sutController.getClass().getName());176 dto.isInstrumentationOn = noKillSwitch(() -> sutController.isInstrumentationActivated());177 return Response.status(200).entity(WrappedResponseDto.withData(dto)).build();178 }179 @Path(ControllerConstants.NEW_SEARCH)180 @POST181 public Response newSearch(@Context HttpServletRequest httpServletRequest) {182 assert trackRequestSource(httpServletRequest);183 lastSqlCommandId = null;184 noKillSwitch(() -> sutController.newSearch());185 return Response.status(201).entity(WrappedResponseDto.withNoData()).build();186 }187 @Path(ControllerConstants.RUN_SUT_PATH)188 @PUT189 @Consumes(Formats.JSON_V1)190 public Response runSut(SutRunDto dto, @Context HttpServletRequest httpServletRequest) {191 assert trackRequestSource(httpServletRequest);192 /*193 If start/stop the SUT, we want to disable the killSwitch.194 The reason is it might be on from previous run, and, in such case,195 until we run a first test it would crash the SUT... eg when retrieving196 OpenAPI/GraphQL schema.197 TODO: likely all the noKillSwitch calls here are redundant198 */199 ExecutionTracer.setKillSwitch(false);200 if(sutController.isSutRunning()) {201 sutController.setKillSwitch(false);202 }203 try {204 if (dto.run == null) {205 String msg = "Invalid JSON: 'run' field is required";206 SimpleLogger.warn(msg);207 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();208 }209 boolean sqlHeuristics = dto.calculateSqlHeuristics != null && dto.calculateSqlHeuristics;210 boolean sqlExecution = dto.extractSqlExecutionInfo != null && dto.extractSqlExecutionInfo;211 noKillSwitch(() -> sutController.enableComputeSqlHeuristicsOrExtractExecution(sqlHeuristics, sqlExecution));212 boolean doReset = dto.resetState != null && dto.resetState;213 synchronized (this) {214 if (!dto.run) {215 if (doReset) {216 String msg = "Invalid JSON: cannot reset state and stop service at same time";217 SimpleLogger.warn(msg);218 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();219 }220 //if on, we want to shut down the server221 if (noKillSwitch(() -> sutController.isSutRunning())) {222 noKillSwitch(() -> sutController.stopSut());223 baseUrlOfSUT = null;224 }225 } else {226 /*227 If SUT is not up and running, let's start it228 */229 if (!noKillSwitch(() -> sutController.isSutRunning())) {230 baseUrlOfSUT = noKillSwitch(() -> sutController.startSut());231 if (baseUrlOfSUT == null) {232 //there has been an internal failure in starting the SUT233 String msg = "Internal failure: cannot start SUT based on given configuration";234 SimpleLogger.warn(msg);235 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();236 }237 noKillSwitch(() -> sutController.initSqlHandler());238 } else {239 //TODO as starting should be blocking, need to check240 //if initialized, and wait if not241 }242 /*243 regardless of where it was running or not, need to reset state.244 this is controlled by a boolean, although most likely we ll always245 want to do it246 */247 if (dto.resetState != null && dto.resetState) {248 try{249 /*250 This should not fail... but, as it is user code, it might fail...251 When it does, it is a major issue, as it can leave the system in252 an inconsistent state for the following fitness evaluations.253 So, we always force a newTest, even when reset fails.254 TODO: a current problem is in Proxyprint, in which after REST calls255 it seems there are locks on the DB (this might happen if a transaction256 is started but then not committed). Ideally, in the reset of DBs we should257 force all lock releases, and possibly point any left lock as a potential bug258 */259 noKillSwitchForceCheck(() -> sutController.resetStateOfSUT());260 } finally {261 noKillSwitch(() -> sutController.newTest());262 }263 }264 /*265 Note: here even if we start the SUT, the starting of a "New Search"266 cannot be done here, as in this endpoint we also deal with the reset267 of state. When we reset state for a new test run, we do not want to268 reset all the other data regarding the whole search269 */270 }271 }272 } catch (RuntimeException e) {273 /*274 FIXME: ideally, would not need to do a try/catch on each single endpoint,275 as could configure Jetty/Jackson to log all errors.276 But even after spending hours googling it, haven't managed to configure it277 */278 String msg = e.getMessage();279 SimpleLogger.error(msg, e);280 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();281 }282 return Response.status(204).entity(WrappedResponseDto.withNoData()).build();283 }284 @Path(ControllerConstants.TEST_RESULTS)285 @GET286 public Response getTestResults(287 @QueryParam("ids")288 @DefaultValue("")289 String idList,290 @QueryParam("killSwitch") @DefaultValue("false")291 boolean killSwitch,292 @Context HttpServletRequest httpServletRequest) {293 assert trackRequestSource(httpServletRequest);294 try {295 TestResultsDto dto = new TestResultsDto();296 Set<Integer> ids;297 try {298 ids = Arrays.stream(idList.split(","))299 .filter(s -> !s.trim().isEmpty())300 .map(Integer::parseInt)301 .collect(Collectors.toSet());302 } catch (NumberFormatException e) {303 String msg = "Invalid parameter 'ids': " + e.getMessage();304 SimpleLogger.warn(msg);305 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();306 }307 List<TargetInfo> targetInfos = noKillSwitch(() -> sutController.getTargetInfos(ids));308 if (targetInfos == null) {309 String msg = "Failed to collect target information for " + ids.size() + " ids";310 SimpleLogger.error(msg);311 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();312 }313 targetInfos.forEach(t -> {314 TargetInfoDto info = new TargetInfoDto();315 info.id = t.mappedId;316 info.value = t.value;317 info.descriptiveId = t.descriptiveId;318 info.actionIndex = t.actionIndex;319 dto.targets.add(info);320 });321 /*322 Note: it is important that extra is computed before AdditionalInfo,323 as heuristics on SQL might add new entries to String specializations324 */325 dto.extraHeuristics = noKillSwitch(() -> sutController.getExtraHeuristics());326 List<AdditionalInfo> additionalInfos = noKillSwitch(() -> sutController.getAdditionalInfoList());327 if (additionalInfos != null) {328 additionalInfos.forEach(a -> {329 AdditionalInfoDto info = new AdditionalInfoDto();330 info.queryParameters = new HashSet<>(a.getQueryParametersView());331 info.headers = new HashSet<>(a.getHeadersView());332 info.lastExecutedStatement = a.getLastExecutedStatement();333 info.rawAccessOfHttpBodyPayload = a.isRawAccessOfHttpBodyPayload();334 info.parsedDtoNames = new HashSet<>(a.getParsedDtoNamesView());335 info.stringSpecializations = new LinkedHashMap<>();336 for(Map.Entry<String, Set<StringSpecializationInfo>> entry :337 a.getStringSpecializationsView().entrySet()){338 assert ! entry.getValue().isEmpty();339 List<StringSpecializationInfoDto> list = entry.getValue().stream()340 .map(it -> new StringSpecializationInfoDto(341 it.getStringSpecialization().toString(),342 it.getValue(),343 it.getType().toString()))344 .collect(Collectors.toList());345 info.stringSpecializations.put(entry.getKey(), list);346 }347 dto.additionalInfoList.add(info);348 });349 } else {350 String msg = "Failed to collect additional info";351 SimpleLogger.error(msg);352 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();353 }354 if(killSwitch){355 sutController.setKillSwitch(true);356 }357 return Response.status(200).entity(WrappedResponseDto.withData(dto)).build();358 } catch (RuntimeException e) {359 /*360 FIXME: ideally, would not need to do a try/catch on each single endpoint,361 as could configure Jetty/Jackson to log all errors.362 But even after spending hours googling it, haven't managed to configure it363 */364 String msg = "Thrown exception: " + e.getMessage();365 SimpleLogger.error(msg, e);366 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();367 }368 }369 @Path(ControllerConstants.NEW_ACTION)370 @Consumes(MediaType.APPLICATION_JSON)371 @PUT372 public Response newAction(ActionDto dto, @Context HttpServletRequest httpServletRequest) {373 /*374 Note: as PUT is idempotent, it can be repeated...375 so need to handle such possibility here376 */377 Integer index = dto.index;378 Integer current = sutController.getActionIndex();379 if(index == current){380 SimpleLogger.warn("Repeated PUT on newAction for same index " + index);381 } else {382 assert trackRequestSource(httpServletRequest);383 //this MUST not be inside a noKillSwitch, as it sets to false384 sutController.newAction(dto);385 }386 return Response.status(204).entity(WrappedResponseDto.withNoData()).build();387 }388 @Path(ControllerConstants.DATABASE_COMMAND)389 @Consumes(Formats.JSON_V1)390 @POST391 public Response executeDatabaseCommand(DatabaseCommandDto dto, @Context HttpServletRequest httpServletRequest) {392 Integer id = dto.idCounter;393 if(id != null){394 if(lastSqlCommandId != null && id <= lastSqlCommandId){395 SimpleLogger.warn("SQL command with id " + id + " has not arrived in order. Last received id : " + lastSqlCommandId);396 /*397 if it had insertions, we silently skip doing it twice.398 but a problem here is that we would lose any info on the auto-generated keys :(399 */400 if(dto.insertions != null && !dto.insertions.isEmpty()){401 return Response.status(204).entity(WrappedResponseDto.withNoData()).build();402 }403 }404 lastSqlCommandId = id;405 }406 assert trackRequestSource(httpServletRequest);407 try {408 SimpleLogger.debug("Received database command");409 Connection connection = noKillSwitch(() -> sutController.getConnection());410 if (connection == null) {411 String msg = "No active database connection";412 SimpleLogger.warn(msg);413 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();414 }415 if (dto.command == null && (dto.insertions == null || dto.insertions.isEmpty())) {416 String msg = "No input command";417 SimpleLogger.warn(msg);418 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();419 }420 if (dto.command != null && dto.insertions != null && !dto.insertions.isEmpty()) {421 String msg = "Only 1 command can be specified";422 SimpleLogger.warn(msg);423 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();...

Full Screen

Full Screen

noKillSwitch

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.internal.EMController;2import org.evomaster.client.java.controller.internal.EMControllerKt;3import org.evomaster.client.java.controller.internal.EMControllerKt.*;4EMController.noKillSwitch();5EMController.isNoKillSwitch();6EMController.resetNoKillSwitch();7EMController.killSwitch();8EMController.isKillSwitch();9EMController.resetKillSwitch();10EMController.isRunning();11EMController.reset();12EMController.isStopped();13EMController.stop();14EMController.isPaused();15EMController.pause();16EMController.isResumed();17EMController.resume();18EMController.isInitializing();19EMController.isInitialized();20EMController.isStarting();21EMController.isStarted();22EMController.isStopping();23EMController.isStopped();24EMController.isResuming();25EMController.isResumed();26EMController.isPausing();27EMController.isPaused();28EMController.isKilling();29EMController.isKilled();30EMController.isRestarting();31EMController.isRestarted();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful