How to use setExecutingInitSql method of org.evomaster.client.java.controller.EmbeddedSutController class

Best EvoMaster code snippet using org.evomaster.client.java.controller.EmbeddedSutController.setExecutingInitSql

Source:SutController.java Github

copy

Full Screen

...279 throw new RuntimeException("Error: DO NOT SUPPORT MULTIPLE SQL CONNECTION YET");280 DbSpecification emDbClean = getDbSpecifications().get(0);281 if (getConnectionIfExist() == null || !emDbClean.employSmartDbClean) return;282 try {283 setExecutingInitSql(true);284 // clean accessed tables285 Set<String> tableDataToInit = null;286 if (!accessedTables.isEmpty()){287 List<String> tablesToClean = new ArrayList<>();288 getTableToClean(accessedTables, tablesToClean);289 if (!tablesToClean.isEmpty()){290 if (emDbClean.schemaNames != null && !emDbClean.schemaNames.isEmpty()){291 emDbClean.schemaNames.forEach(sch-> DbCleaner.clearDatabase(getConnectionIfExist(), sch, null, tablesToClean, emDbClean.dbType));292 }else293 DbCleaner.clearDatabase(getConnectionIfExist(), null, null, tablesToClean, emDbClean.dbType);294 tableDataToInit = tablesToClean.stream().filter(a-> tableInitSqlMap.keySet().stream().anyMatch(t-> t.equalsIgnoreCase(a))).collect(Collectors.toSet());295 }296 }297 handleInitSql(tableDataToInit, emDbClean);298 }catch (SQLException e) {299 throw new RuntimeException("SQL Init Execution Error: fail to execute "+e);300 }finally {301 setExecutingInitSql(false);302 }303 }304 private void handleInitSql(Collection<String> tableDataToInit, DbSpecification spec) throws SQLException {305 // init db script306 boolean initAll = initSqlScriptAndGetInsertMap(getConnectionIfExist(), spec);307 if (!initAll && tableDataToInit!= null &&!tableDataToInit.isEmpty()){308 tableDataToInit.forEach(a->{309 tableInitSqlMap.keySet().stream().filter(t-> t.equalsIgnoreCase(a)).forEach(t->{310 tableInitSqlMap.get(t).forEach(c->{311 try {312 SqlScriptRunner.execCommand(getConnectionIfExist(), c);313 } catch (SQLException e) {314 throw new RuntimeException("SQL Init Execution Error: fail to execute "+ c + " with error "+e);315 }316 });317 });318 });319 }320 }321 /**322 * collect info about what table are manipulated by evo in order to generate data directly into it323 * @param tables a list of name of tables324 */325 public void addTableToInserted(List<String> tables){326 accessedTables.addAll(tables);327 }328 private void getTableToClean(List<String> accessedTables, List<String> tablesToClean){329 for (String t: accessedTables){330 if (!findInCollectionIgnoreCase(t, tablesToClean).isPresent()){331 if (findInMapIgnoreCase(t, fkMap).isPresent()){332 tablesToClean.add(t);333 List<String> fk = fkMap.entrySet().stream().filter(e->334 findInCollectionIgnoreCase(t, e.getValue()).isPresent()335 && !findInCollectionIgnoreCase(e.getKey(), tablesToClean).isPresent()).map(Map.Entry::getKey).collect(Collectors.toList());336 if (!fk.isEmpty())337 getTableToClean(fk, tablesToClean);338 }else {339 SimpleLogger.uniqueWarn("Cannot find the table "+t+" in ["+String.join(",", fkMap.keySet())+"]");340 }341 }342 }343 }344 private Optional<String> findInCollectionIgnoreCase(String name, Collection<String> list){345 return list.stream().filter(i-> i.equalsIgnoreCase(name)).findFirst();346 }347 private Optional<? extends Map.Entry<String, ?>> findInMapIgnoreCase(String name, Map<String, ?> list){348 return list.entrySet().stream().filter(x-> x.getKey().equalsIgnoreCase(name)).findFirst();349 }350 /**351 *352 * @param dbSpecification contains info of the db connection353 * @return whether the init script is executed354 */355 private boolean initSqlScriptAndGetInsertMap(Connection connection, DbSpecification dbSpecification) throws SQLException {356 if (dbSpecification.initSqlOnResourcePath == null357 && dbSpecification.initSqlScript == null) return false;358 // TODO to handle initSqlMap for multiple connections359 if (tableInitSqlMap.isEmpty()){360 List<String> all = new ArrayList<>();361 if (dbSpecification.initSqlOnResourcePath != null){362 all.addAll(SqlScriptRunnerCached.extractSqlScriptFromResourceFile(dbSpecification.initSqlOnResourcePath));363 }364 if (dbSpecification.initSqlScript != null){365 all.addAll(SqlScriptRunner.extractSql(dbSpecification.initSqlScript));366 }367 if (!all.isEmpty()){368 // collect insert sql commands map, key is table name, and value is a list sql insert commands369 tableInitSqlMap.putAll(SqlScriptRunner.extractSqlTableMap(all));370 // execute all commands371 SqlScriptRunner.runCommands(connection, all);372 return true;373 }374 }375 return false;376 }377 /**378 * Extra information about the SQL Database Schema, if any is present.379 * Note: this is extracted by querying the database itself.380 * So the database must be up and running.381 *382 * @return a DTO with the schema information383 * @see SutHandler#getDbSpecifications384 */385 public final DbSchemaDto getSqlDatabaseSchema() {386 if (schemaDto != null) {387 return schemaDto;388 }389 if (getDbSpecifications() == null || getDbSpecifications().isEmpty()) {390 return null;391 }392 try {393 schemaDto = SchemaExtractor.extract(getConnectionIfExist());394 Objects.requireNonNull(schemaDto);395 schemaDto.employSmartDbClean = doEmploySmartDbClean();396 } catch (Exception e) {397 SimpleLogger.error("Failed to extract the SQL Database Schema: " + e.getMessage());398 return null;399 }400 if (fkMap.isEmpty()){401 schemaDto.tables.forEach(t->{402 fkMap.putIfAbsent(t.name, new ArrayList<>());403 if (t.foreignKeys!=null && !t.foreignKeys.isEmpty()){404 t.foreignKeys.forEach(f->{405 fkMap.get(t.name).add(f.targetTable.toUpperCase());406 });407 }408 });409 }410 return schemaDto;411 }412 /**413 *414 * @return a map from the name of interface to extracted interface415 */416 public final Map<String, InterfaceSchema> getRPCSchema(){417 return rpcInterfaceSchema;418 }419 /**420 *421 * @return a map of auth local method422 */423 public Map<Integer, LocalAuthSetupSchema> getLocalAuthSetupSchemaMap() {424 return localAuthSetupSchemaMap;425 }426 /**427 * extract endpoints info of the RPC interface by reflection based on the specified service interface name428 */429 @Override430 public final void extractRPCSchema(){431 if (objectMapper == null)432 objectMapper = new ObjectMapper();433 if (!rpcInterfaceSchema.isEmpty())434 return;435 if (!(getProblemInfo() instanceof RPCProblem)){436 SimpleLogger.error("Problem ("+getProblemInfo().getClass().getSimpleName()+") is not RPC but request RPC schema.");437 return;438 }439 try {440 RPCEndpointsBuilder.validateCustomizedValueInRequests(getCustomizedValueInRequests());441 RPCEndpointsBuilder.validateCustomizedNotNullAnnotationForRPCDto(specifyCustomizedNotNullAnnotation());442 RPCProblem rpcp = (RPCProblem) getProblemInfo();443 for (String interfaceName: rpcp.getMapOfInterfaceAndClient()){444 InterfaceSchema schema = RPCEndpointsBuilder.build(interfaceName, rpcp.getType(), rpcp.getClient(interfaceName),445 rpcp.skipEndpointsByName!=null? rpcp.skipEndpointsByName.get(interfaceName):null,446 rpcp.skipEndpointsByAnnotation!=null?rpcp.skipEndpointsByAnnotation.get(interfaceName):null,447 rpcp.involveEndpointsByName!=null? rpcp.involveEndpointsByName.get(interfaceName):null,448 rpcp.involveEndpointsByAnnotation!=null? rpcp.involveEndpointsByAnnotation.get(interfaceName):null,449 getInfoForAuthentication(),450 getCustomizedValueInRequests(),451 specifyCustomizedNotNullAnnotation());452 rpcInterfaceSchema.put(interfaceName, schema);453 }454 localAuthSetupSchemaMap.clear();455 Map<Integer, LocalAuthSetupSchema> local = RPCEndpointsBuilder.buildLocalAuthSetup(getInfoForAuthentication());456 if (local!=null && !local.isEmpty())457 localAuthSetupSchemaMap.putAll(local);458 }catch (Exception e){459// SimpleLogger.error("Failed to extract the RPC Schema: " + e.getMessage());460 throw new RuntimeException("Failed to extract the RPC Schema: " + e.getMessage());461 }462 }463 /**464 * parse seeded tests for RPC465 * @return a list of tests, and each test is a list of RCPActionDto466 */467 public List<List<RPCActionDto>> handleSeededTests(){468 if (seedRPCTests() == null || seedRPCTests().isEmpty()) return null;469 if (rpcInterfaceSchema.isEmpty())470 throw new IllegalStateException("empty RPC interface: The RPC interface schemas are not extracted yet");471 List<List<RPCActionDto>> results = new ArrayList<>();472 for (SeededRPCTestDto dto: seedRPCTests()){473 if (dto.rpcFunctions != null && !dto.rpcFunctions.isEmpty()){474 List<RPCActionDto> test = new ArrayList<>();475 for (SeededRPCActionDto actionDto : dto.rpcFunctions){476 InterfaceSchema schema = rpcInterfaceSchema.get(actionDto.interfaceName);477 if (schema != null){478 EndpointSchema actionSchema = schema.getOneEndpointWithSeededDto(actionDto);479 if (actionSchema != null){480 EndpointSchema copy = actionSchema.copyStructure();481 for (int i = 0; i < copy.getRequestParams().size(); i++){482 // TODO need to check if generic type could be handled with jackson483 NamedTypedValue p = copy.getRequestParams().get(i);484 try {485 String stringValue = actionDto.inputParams.get(i);486// Object value = objectMapper.readValue(stringValue, p.getType().getClazz());487 p.setValueBasedOnInstanceOrJson(stringValue);488 } catch (JsonProcessingException e) {489 throw new IllegalStateException(490 String.format("Seeded Test Error: cannot parse the seeded test %s at the parameter %d with error msg: %s", actionDto, i, e.getMessage()));491 }492 }493 test.add(copy.getDto());494 }else {495 throw new IllegalStateException("Seeded Test Error: cannot find the action "+actionDto.functionName);496 }497 } else {498 throw new IllegalStateException("Seeded Test Error: cannot find the interface "+ actionDto.interfaceName);499 }500 }501 results.add(test);502 } else {503 SimpleLogger.warn("Seeded Test: empty RPC function calls for the test "+ dto.testName);504 }505 }506 return results;507 }508 /**509 * Either there is no connection, or, if there is, then it must have P6Spy configured.510 * But this might not apply to all kind controllers511 *512 * @return false if the verification failed513 */514 @Deprecated515 public final boolean verifySqlConnection(){516 return true;517// Connection connection = getConnection();518// if(connection == null519// //check does not make sense for External520// || !(this instanceof EmbeddedSutController)){521// return true;522// }523//524// /*525// bit hacky/brittle, but seems there is no easy way to check if a connection is526// using P6Spy.527// However, the name of driver's package would appear when doing a toString on it528// */529// String info = connection.toString();530//531// return info.contains("p6spy");532 }533 /**534 * Re-initialize all internal data to enable a completely new search phase535 * which should be independent from previous ones536 */537 public abstract void newSearch();538 /**539 * Re-initialize some internal data needed before running a new test540 */541 public final void newTest() {542 actionIndex = -1;543 resetExtraHeuristics();544 extras.clear();545 //clean all accessed table in a test546 accessedTables.clear();547 newTestSpecificHandler();548 // set executingAction state false for newTest549 setExecutingAction(false);550 }551 /**552 * As some heuristics are based on which action (eg HTTP call, or click of button)553 * in the test sequence is executed, and their order, we need to keep track of which554 * action does cover what.555 *556 * @param dto the DTO with the information about the action (eg its index in the test)557 */558 public final void newAction(ActionDto dto) {559 if (dto.index > extras.size()) {560 extras.add(computeExtraHeuristics());561 }562 this.actionIndex = dto.index;563 resetExtraHeuristics();564 newActionSpecificHandler(dto);565 }566 public final void executeHandleLocalAuthenticationSetup(RPCActionDto dto, ActionResponseDto responseDto){567 LocalAuthSetupSchema endpointSchema = new LocalAuthSetupSchema();568 endpointSchema.setValue(dto);569 handleLocalAuthenticationSetup(endpointSchema.getAuthenticationInfo());570 if (dto.responseVariable != null && dto.doGenerateTestScript){571 responseDto.testScript = endpointSchema.newInvocationWithJava(dto.responseVariable, dto.controllerVariable,dto.clientVariable);572 }573 }574 /**575 * execute a RPC request based on the specified dto576 * @param dto is the action DTO to be executed577 */578 public final void executeAction(RPCActionDto dto, ActionResponseDto responseDto) {579 EndpointSchema endpointSchema = getEndpointSchema(dto);580 if (dto.responseVariable != null && dto.doGenerateTestScript){581 try{582 responseDto.testScript = endpointSchema.newInvocationWithJava(dto.responseVariable, dto.controllerVariable,dto.clientVariable);583 }catch (Exception e){584 SimpleLogger.warn("Fail to generate test script"+e.getMessage());585 }586 if (responseDto.testScript ==null)587 SimpleLogger.warn("Null test script for action "+dto.actionName);588 }589 Object response;590 try {591 response = executeRPCEndpoint(dto, false);592 } catch (Exception e) {593 throw new RuntimeException("ERROR: target exception should be caught, but "+ e.getMessage());594 }595 //handle exception596 if (response instanceof Exception){597 try{598 RPCExceptionHandler.handle(response, responseDto, endpointSchema, getRPCType(dto));599 return;600 } catch (Exception e){601 SimpleLogger.error("ERROR: fail to handle exception instance to dto "+ e.getMessage());602 //throw new RuntimeException("ERROR: fail to handle exception instance to dto "+ e.getMessage());603 }604 }605 if (endpointSchema.getResponse() != null){606 if (response != null){607 try{608 // successful execution609 NamedTypedValue resSchema = endpointSchema.getResponse().copyStructureWithProperties();610 resSchema.setValueBasedOnInstance(response);611 responseDto.rpcResponse = resSchema.getDto();612 if (dto.doGenerateAssertions && dto.responseVariable != null)613 responseDto.assertionScript = resSchema.newAssertionWithJava(dto.responseVariable, dto.maxAssertionForDataInCollection);614 else615 responseDto.jsonResponse = objectMapper.writeValueAsString(response);616 } catch (Exception e){617 SimpleLogger.error("ERROR: fail to set successful response instance value to dto "+ e.getMessage());618 //throw new RuntimeException("ERROR: fail to set successful response instance value to dto "+ e.getMessage());619 }620 try {621 responseDto.customizedCallResultCode = categorizeBasedOnResponse(response);622 } catch (Exception e){623 SimpleLogger.error("ERROR: fail to categorize result with implemented categorizeBasedOnResponse "+ e.getMessage());624 //throw new RuntimeException("ERROR: fail to categorize result with implemented categorizeBasedOnResponse "+ e.getMessage());625 }626 }627 }628 }629 private Object executeRPCEndpoint(RPCActionDto dto, boolean throwTargetException) throws Exception {630 Object client = ((RPCProblem)getProblemInfo()).getClient(dto.interfaceId);631 EndpointSchema endpointSchema = getEndpointSchema(dto);632 return executeRPCEndpointCatchTargetException(client, endpointSchema, throwTargetException);633 }634 private Object executeRPCEndpointCatchTargetException(Object client, EndpointSchema endpoint, boolean throwTargetException) throws Exception {635 Object res;636 try {637 res = executeRPCEndpoint(client, endpoint);638 } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {639 throw new RuntimeException("EM RPC REQUEST EXECUTION ERROR: fail to process a RPC request with "+ e.getMessage());640 } catch (InvocationTargetException e) {641 if (throwTargetException)642 throw (Exception) e.getTargetException();643 else644 res = e.getTargetException();645 } catch (Exception e){646 SimpleLogger.error("ERROR: other exception exists "+ e.getMessage());647 if (throwTargetException) throw e;648 else res = e;649 }650 return res;651 }652 @Override653 public Object executeRPCEndpoint(String json) throws Exception{654 try {655 RPCActionDto dto = objectMapper.readValue(json, RPCActionDto.class);656 return executeRPCEndpoint(dto, true);657 } catch (JsonProcessingException e) {658 SimpleLogger.error("Failed to extract the json: " + e.getMessage());659 }660 return null;661 }662 /**663 * execute a RPC request with specified client664 * @param client is the client to execute the endpoint665 * @param endpoint is the endpoint to be executed666 */667 private final Object executeRPCEndpoint(Object client, EndpointSchema endpoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException {668 if (endpoint.getRequestParams().isEmpty()){669 Method method = client.getClass().getDeclaredMethod(endpoint.getName());670 return method.invoke(client);671 }672 Object[] params = new Object[endpoint.getRequestParams().size()];673 Class<?>[] types = new Class<?>[endpoint.getRequestParams().size()];674 try{675 for (int i = 0; i < params.length; i++){676 NamedTypedValue param = endpoint.getRequestParams().get(i);677 params[i] = param.newInstance();678 types[i] = param.getType().getClazz();679 }680 } catch (Exception e){681 throw new RuntimeException("ERROR: fail to instance value of input parameters based on dto/schema, msg error:"+e.getMessage());682 }683 Method method = client.getClass().getDeclaredMethod(endpoint.getName(), types);684 return method.invoke(client, params);685 }686 private EndpointSchema getEndpointSchema(RPCActionDto dto){687 InterfaceSchema interfaceSchema = rpcInterfaceSchema.get(dto.interfaceId);688 EndpointSchema endpointSchema = interfaceSchema.getOneEndpoint(dto).copyStructure();689 endpointSchema.setValue(dto);690 return endpointSchema;691 }692 private RPCType getRPCType(RPCActionDto dto){693 return rpcInterfaceSchema.get(dto.interfaceId).getRpcType();694 }695 public abstract void newTestSpecificHandler();696 public abstract void newActionSpecificHandler(ActionDto dto);697 /**698 * Check if bytecode instrumentation is on.699 *700 * @return true if the instrumentation is on701 */702 public abstract boolean isInstrumentationActivated();703 /**704 * <p>705 * Check if the system under test (SUT) is running and fully initialized706 * </p>707 *708 * <p>709 * How to implement this method depends on the library/framework used710 * to build the application.711 * In Spring applications, this can be done with something like:712 * {@code ctx != null && ctx.isRunning()}, where {@code ctx} is a field where713 * {@code ConfigurableApplicationContext} should be stored when starting714 * the application.715 * </p>716 * @return true if the SUT is running717 */718 public abstract boolean isSutRunning();719 /**720 * <p>721 * A "," separated list of package prefixes or class names.722 * For example, "com.foo.,com.bar.Bar".723 * This is used to specify for which classes we want to measure724 * code coverage.725 * </p>726 *727 * <p>728 * Note: be careful of using something as general as "com."729 * or "org.", as most likely ALL your third-party libraries730 * would be instrumented as well, which could have a severe731 * impact on performance.732 * </p>733 *734 * @return a String representing the packages to cover735 */736 public abstract String getPackagePrefixesToCover();737 /**738 * <p>739 * If the application uses some sort of authentication, these details740 * need to be provided here.741 * Even if EvoMaster can have access to the database, it would not be able742 * to recover hashed passwords.743 * </p>744 *745 * <p>746 * To test the application, there is the need to provide auth for at least 1 user747 * (and more if they have different authorization roles).748 * When EvoMaster generates test cases, it can decide to use the credential of749 * any user provided by this method.750 * </p>751 *752 * <p>753 * What type of info to provide here depends on the auth mechanism, e.g.,754 * Basic or cookie-based (using {@link CookieLoginDto}).755 * To simplify the creation of these DTOs with auth info, you can look756 * at {@link org.evomaster.client.java.controller.AuthUtils}.757 * </p>758 *759 * <p>760 * If the credential are stored in a database, be careful on how the761 * method {@code resetStateOfSUT} is implemented.762 * If you delete all data with {@link DbCleaner}, then you will need as well to763 * recreate the auth details.764 * This can be put in a script, executed then with {@link SqlScriptRunner}.765 * </p>766 *767 * @return a list of valid authentication credentials, or {@code null} if768 * * none is necessary769 */770 public abstract List<AuthenticationDto> getInfoForAuthentication();771 /**772 * <p>773 * If the system under test (SUT) uses a SQL database, we need to have a774 * configured connection to access it.775 * </p>776 *777 * <p>778 * This method is related to {@link SutHandler#resetStateOfSUT}.779 * When accessing a {@code Connection} object to reset the state of780 * the application, we suggest to save it to field (eg when starting the781 * application), and return such field here, e.g., {@code return connection;}.782 * This connection object will be used by EvoMaster to analyze the state of783 * the database to create better test cases.784 * </p>785 *786 * @return {@code null} if the SUT does not use any SQL database787 */788 @Deprecated789 public Connection getConnection(){790 throw new IllegalStateException("This deprecated method should never be called");791 }792 /**793 * If the system under test (SUT) uses a SQL database, we need to specify794 * the driver used to connect, eg. {@code org.h2.Driver}.795 * This is needed for when we intercept SQL commands with P6Spy796 *797 * @return {@code null} if the SUT does not use any SQL database798 * @deprecated this method is no longer needed799 */800 @Deprecated801 public String getDatabaseDriverName(){802 throw new IllegalStateException("This deprecated method should never be called");803 }804 public abstract List<TargetInfo> getTargetInfos(Collection<Integer> ids);805 /**806 * @return additional info for each action in the test.807 * The list is ordered based on the action index.808 */809 public abstract List<AdditionalInfo> getAdditionalInfoList();810 /**811 * <p>812 * Depending of which kind of SUT we are dealing with (eg, REST, GraphQL or SPA frontend),813 * there is different info that must be provided.814 * For example, in a RESTful API, you need to speficy where the OpenAPI/Swagger schema815 * is located.816 * </p>817 *818 * <p>819 * The interface {@link ProblemInfo} provides different implementations, like820 * {@code RestProblem}.821 * You will need to instantiate one of such classes, and return it here in this method.822 * </p>823 * @return an instance of object with all the needed data for the specific addressed problem824 */825 public abstract ProblemInfo getProblemInfo();826 /**827 * Test cases could be outputted in different language (e.g., Java and Kotlin),828 * using different testing libraries (e.g., JUnit 4 or 5).829 * Here, need to specify the default option.830 *831 * @return the format in which the test cases should be generated832 */833 public abstract SutInfoDto.OutputFormat getPreferredOutputFormat();834 public abstract UnitsInfoDto getUnitsInfoDto();835 public abstract void setKillSwitch(boolean b);836 public abstract void setExecutingInitSql(boolean executingInitSql);837 public abstract void setExecutingAction(boolean executingAction);838 public abstract BootTimeInfoDto getBootTimeInfoDto();839 protected BootTimeInfoDto getBootTimeInfoDto(BootTimeObjectiveInfo info){840 if (info == null)841 return null;842 BootTimeInfoDto infoDto = new BootTimeInfoDto();843 infoDto.targets = info.getObjectiveCoverageAtSutBootTime()844 .entrySet().stream().map(e-> new TargetInfoDto(){{845 descriptiveId = e.getKey();846 value = e.getValue();847 }}).collect(Collectors.toList());848 infoDto.externalServicesDto = info.getExternalServiceInfo().stream()849 .map(e -> new ExternalServiceInfoDto(e.getProtocol(), e.getHostname(), e.getRemotePort()))850 .collect(Collectors.toList());...

Full Screen

Full Screen

Source:EmbeddedSutController.java Github

copy

Full Screen

...61 public final void setKillSwitch(boolean b) {62 ExecutionTracer.setKillSwitch(b);63 }64 @Override65 public final void setExecutingInitSql(boolean executingInitSql) {66 ExecutionTracer.setExecutingInitSql(executingInitSql);67 }68 @Override69 public final void setExecutingAction(boolean executingAction){70 ExecutionTracer.setExecutingAction(executingAction);71 }72 @Override73 public BootTimeInfoDto getBootTimeInfoDto() {74 return getBootTimeInfoDto(InstrumentationController.getBootTimeObjectiveInfo());75 }76 @Override77 public final String getExecutableFullPath(){78 return null; //not needed for embedded79 }80}...

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.EmbeddedSutController;2import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;3import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;4import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;5import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;6import org.evomaster.client.java.controller.db.SqlScriptRunner;7import org.evomaster.client.java.controller.internal.db.SqlInsertBuilder;8import org.evomaster.client.java.controller.internal.db.h2.H2Table;9import org.evomaster.client.java.controller.internal.db.h2.H2TableColumn;10import org.evomaster.client.java.controller.internal.db.h2.H2TableName;11import org.evomaster.client.java.controller.internal.db.h2.H2TableSchema;12import org.evomaster.client.java.controller.internal.db.schema.SqlScriptExecutor;13import org.evomaster.client.java.controller.internal.db.schema.Table;14import org.evomaster.client.java.controller.internal.db.schema.TableColumn;15import org.evomaster.client.java.controller.internal.db.schema.TableName;16import org.evomaster.client.java.controller.internal.db.schema.TableSchema;17import org.evomaster.client.java.controller.problem.ProblemInfo;18import org.evomaster.client.java.controller.problem.RestProblem;19import org.evomaster.client.java.controller.problem.RestResourceCalls;20import org.evomaster.client.java.controller.problem.RestResourceInfo;21import org.evomaster.client.java.controller.problem.RestResourceSample;22import org.evomaster.client.java.controller.problem.rest.*;23import org.evomaster.client.java.controller.problem.rest.param.BodyParamInfo;24import org.evomaster.client.java.controller.problem.rest.param.Param;25import org.evomaster.client.java.controller.problem.rest.param.ParamUtil;26import org.evomaster.client.java.controller.problem.rest.param.PathParam;27import org.evomaster.client.java.controller.problem.rest.param.QueryParam;28import org.evomaster.client.java.utils.SimpleLogger;29import org.junit.jupiter.api.AfterAll;30import org.junit.jupiter.api.BeforeAll;31import org.junit.jupiter.api.Test;32import org.junit.jupiter.api.TestInstance;33import java.io.IOException;34import java.util.ArrayList;35import java.util.Arrays;36import java.util.Collections;37import java.util.List;38import java.util.Map;39import java.util.Optional;40import java.util.function.Function;41import java.util.stream.Collectors;42import static org.junit.jupiter.api.Assertions.*;43@TestInstance(TestInstance.Lifecycle.PER_CLASS)44public class EmbeddedSutControllerTest {

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller.api.dto;2import com.fasterxml.jackson.annotation.JsonInclude;3import com.fasterxml.jackson.annotation.JsonProperty;4import com.fasterxml.jackson.annotation.JsonPropertyOrder;5@JsonInclude(JsonInclude.Include.NON_NULL)6@JsonPropertyOrder({7})8public class ExecutingSqlDto {9 @JsonProperty("sql")10 private String sql;11 @JsonProperty("parameters")12 private Object[] parameters;13 @JsonProperty("sql")14 public String getSql() {15 return sql;16 }17 @JsonProperty("sql")18 public void setSql(String sql) {19 this.sql = sql;20 }21 public ExecutingSqlDto withSql(String sql) {22 this.sql = sql;23 return this;24 }25 @JsonProperty("parameters")26 public Object[] getParameters() {27 return parameters;28 }29 @JsonProperty("parameters")30 public void setParameters(Object[] parameters) {31 this.parameters = parameters;32 }33 public ExecutingSqlDto withParameters(Object[] parameters) {34 this.parameters = parameters;35 return this;36 }37}38package org.evomaster.client.java.controller.api.dto;39import com.fasterxml.jackson.annotation.JsonInclude;40import com.fasterxml.jackson.annotation.JsonProperty;41import com.fasterxml.jackson.annotation.JsonPropertyOrder;42@JsonInclude(JsonInclude.Include.NON_NULL)43@JsonPropertyOrder({44})45public class ExecutingSqlDto {46 @JsonProperty("sql")47 private String sql;48 @JsonProperty("parameters")49 private Object[] parameters;50 @JsonProperty("sql")51 public String getSql() {52 return sql;53 }54 @JsonProperty("sql")55 public void setSql(String sql) {56 this.sql = sql;57 }58 public ExecutingSqlDto withSql(String sql) {59 this.sql = sql;60 return this;61 }62 @JsonProperty("parameters")63 public Object[] getParameters() {64 return parameters;65 }66 @JsonProperty("parameters")67 public void setParameters(Object[] parameters) {68 this.parameters = parameters;69 }70 public ExecutingSqlDto withParameters(Object[] parameters) {71 this.parameters = parameters;72 return this;73 }74}

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller.api;2import org.evomaster.client.java.controller.EmbeddedSutController;3import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;4import java.sql.Connection;5import java.sql.SQLException;6import java.util.List;7public class DbController {8 private EmbeddedSutController controller;9 public DbController(EmbeddedSutController controller) {10 this.controller = controller;11 }12 public void setExecutingInitSql(boolean executingInitSql) {13 controller.setExecutingInitSql(executingInitSql);14 }15 public void resetStateOfSUT() {16 controller.resetStateOfSUT();17 }18 public List<SqlScriptDto> getSqlScripts() {19 return controller.getSqlScripts();20 }21 public void setSqlScripts(List<SqlScriptDto> sqlScripts) {22 controller.setSqlScripts(sqlScripts);23 }24 public void executeSqlScript(Connection connection, SqlScriptDto script) throws SQLException {25 controller.executeSqlScript(connection, script);26 }27 public void executeSqlScripts(Connection connection) throws SQLException {28 controller.executeSqlScripts(connection);29 }30}31package org.evomaster.client.java.controller.api;32import org.evomaster.client.java.controller.EmbeddedSutController;33import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;34import java.sql.Connection;35import java.sql.SQLException;36import java.util.List;37public class DbController {38 private EmbeddedSutController controller;39 public DbController(EmbeddedSutController controller) {40 this.controller = controller;41 }42 public void setExecutingInitSql(boolean executingInitSql) {43 controller.setExecutingInitSql(executingInitSql);44 }45 public void resetStateOfSUT() {46 controller.resetStateOfSUT();47 }48 public List<SqlScriptDto> getSqlScripts() {49 return controller.getSqlScripts();50 }51 public void setSqlScripts(List<SqlScriptDto> sqlScripts) {52 controller.setSqlScripts(sqlScripts);53 }54 public void executeSqlScript(Connection connection, SqlScriptDto script) throws SQLException {55 controller.executeSqlScript(connection, script);56 }57 public void executeSqlScripts(Connection connection) throws SQLException {58 controller.executeSqlScripts(connection);59 }60}

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller;2import org.evomaster.client.java.controller.api.dto.SutInfoDto;3import org.evomaster.client.java.controller.internal.SutHandler;4import java.util.List;5public class EmbeddedSutController implements SutController {6 private final SutHandler handler;7 public EmbeddedSutController(SutHandler handler) {8 this.handler = handler;9 }10 public SutInfoDto startSut() {11 return handler.startSut();12 }13 public boolean isSutRunning() {14 return handler.isSutRunning();15 }16 public void resetStateOfSUT() {17 handler.resetStateOfSUT();18 }19 public boolean stopSut() {20 return handler.stopSut();21 }22 public boolean isSutStopped() {23 return handler.isSutStopped();24 }25 public boolean isSutErrorState() {26 return handler.isSutErrorState();27 }28 public boolean isSutInitialized() {29 return handler.isSutInitialized();30 }31 public List<String> getCoverage() {32 return handler.getCoverage();33 }34 public boolean isSutReadyForInput() {35 return handler.isSutReadyForInput();36 }37 public boolean isSutReadyForNewSearch() {38 return handler.isSutReadyForNewSearch();39 }40 public void newSearch() {41 handler.newSearch();42 }43 public boolean isSutTerminated() {44 return handler.isSutTerminated();45 }46 public void terminateSut() {47 handler.terminateSut();48 }49 public void setSutExecutionStarting() {50 handler.setSutExecutionStarting();51 }52 public void setSutExecutionStopping() {53 handler.setSutExecutionStopping();54 }55 public void setExecutingInitSql(boolean executingInitSql) {56 handler.setExecutingInitSql(executingInitSql);57 }58 public void setTestTimeout(int seconds) {59 handler.setTestTimeout(seconds);60 }61 public void setTestClusterTimeout(int

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller;2import org.junit.jupiter.api.Test;3import org.springframework.boot.test.context.SpringBootTest;4import static org.junit.jupiter.api.Assertions.*;5public class EmbeddedSutControllerTest {6 public void testSetExecutingInitSql() {7 EmbeddedSutController embeddedSutController = new EmbeddedSutController();8 embeddedSutController.setExecutingInitSql(true);9 assertTrue(embeddedSutController.isExecutingInitSql());10 }11}12package org.evomaster.client.java.controller;13import org.junit.jupiter.api.Test;14import org.springframework.boot.test.context.SpringBootTest;15import static org.junit.jupiter.api.Assertions.*;16public class EmbeddedSutControllerTest {17 public void testSetIgnoreSqlFailure() {18 EmbeddedSutController embeddedSutController = new EmbeddedSutController();19 embeddedSutController.setIgnoreSqlFailure(true);20 assertTrue(embeddedSutController.isIgnoreSqlFailure());21 }22}23package org.evomaster.client.java.controller;24import org.junit.jupiter.api.Test;25import org.springframework.boot.test.context.SpringBootTest;26import static org.junit.jupiter.api.Assertions.*;27public class EmbeddedSutControllerTest {28 public void testSetMaxSqlRetries() {29 EmbeddedSutController embeddedSutController = new EmbeddedSutController();30 embeddedSutController.setMaxSqlRetries(1);31 assertEquals(1, embeddedSutController.getMaxSqlRetries());32 }33}34package org.evomaster.client.java.controller;35import org.junit.jupiter.api.Test;36import org.springframework.boot.test.context.SpringBootTest;37import static org.junit.jupiter.api.Assertions.*;38public class EmbeddedSutControllerTest {39 public void testSetSqlExecutionTimeout() {40 EmbeddedSutController embeddedSutController = new EmbeddedSutController();41 embeddedSutController.setSqlExecutionTimeout(1);42 assertEquals(1, embeddedSutController.getSqlExecutionTimeout());43 }44}

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1package org.evomaster.core.problem.rest;2import com.foo.rest.examples.spring.db.init.DbInitController;3import org.evomaster.client.java.controller.EmbeddedSutController;4import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseInitializationDto;5import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;6import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;7import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;8import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;9import org.evomaster.client.java.controller.db.DbAction;10import org.evomaster.client.java.controller.db.DbActionResult;11import org.evomaster.client.java.controller.db.SqlScriptRunner;12import org.evomaster.client.java.controller.internal.db.SqlScriptExecutor;13import org.evomaster.client.java.controller.internal.db.h2.H2Initializer;14import org.evomaster.client.java.controller.internal.db.h2.H2SchemaExtractor;15import org.evomaster.client.java.controller.internal.db.h2.H2Table;16import org.evomaster.client.java.controller.internal.db.h2.H2TableIndex;17import org.evomaster.client.java.controller.internal.db.h2.H2TableStructure;18import org.evomaster.client.java.controller.internal.db.h2.H2Utils;19import org.evomaster.client.java.controller.internal.db.h2.H2View;20import org.evomaster.client.java.controller.internal.db.schema.Column;21import org.evomaster.client.java.controller.internal.db.schema.ForeignKey;22import org.evomaster.client.java.controller.internal.db.schema.Schema;23import org.evomaster.client.java.controller.internal.db.schema.Table;24import org.evomaster.client.java.controller.internal.db.schema.View;25import org.evomaster.client.java.controller.internal.db.sql.SqlInsertBuilder;26import org.evomaster.client.java.controller.internal.db.sql.SqlScriptWriter;27import org.evomaster.client.java.controller.internal.db.sql.SqlUpdateBuilder;28import org.evomaster.client.java.controller.internal.db.sql.SqlWhereBuilder;29import org.evomaster.client.java.controller.internal.db.sql.schema.SqlColumn;30import org.evomaster.client.java.controller.internal.db.sql.schema.SqlForeignKey;31import org.evomaster.client.java.controller.internal.db.sql.schema.SqlSchema;32import org.evomaster.client.java.controller.internal.db.sql.schema.SqlTable;33import org.evomaster.client.java.controller.internal.db.sql.schema.SqlView;34import org.evomaster.client.java.controller.internal.db.sql.schema.SqlWhereCondition;35import org.ev

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller;2import java.sql.Connection;3import java.sql.DriverManager;4import java.sql.SQLException;5import java.util.ArrayList;6import java.util.List;7public class EmbeddedSutController {8 private static final String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";9 private static final String JDBC_DRIVER = "org.h2.Driver";10 private static final String JDBC_USERNAME = "sa";11 private static final String JDBC_PASSWORD = "";12 private static final String SQL_FILE = "db.sql";13 private static List<String> initSql = new ArrayList<>();14 public static void main(String[] args) throws Exception {15 initSql.add("CREATE TABLE IF NOT EXISTS table1(id INTEGER, name VARCHAR(255));");16 initSql.add("INSERT INTO table1 VALUES(1, 'name1');");17 initSql.add("INSERT INTO table1 VALUES(2, 'name2');");18 initSql.add("INSERT INTO table1 VALUES(3, 'name3');");19 initSql.add("INSERT INTO table1 VALUES(4, 'name4');");20 initSql.add("INSERT INTO table1 VALUES(5, 'name5');");21 EmbeddedSutController controller = new EmbeddedSutController();22 controller.startSut();23 controller.stopSut();24 }25 public void startSut() throws Exception {26 Class.forName(JDBC_DRIVER);27 Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);28 setExecutingInitSql(true);29 for (String sql : initSql) {30 conn.createStatement().execute(sql);31 }32 setExecutingInitSql(false);33 conn.close();34 }35 public void stopSut() throws SQLException {36 try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD)) {37 conn.createStatement().execute("SHUTDOWN");38 }39 }40 public static void setExecutingInitSql(boolean executingInitSql) {41 EmbeddedSutController.executingInitSql = executingInitSql;42 }43 private static boolean executingInitSql = false;44 public static boolean isExecutingInitSql() {45 return executingInitSql;46 }47}48package org.evomaster.client.java.controller;49import java.sql.Connection;50import java.sql.DriverManager;51import java.sql.ResultSet;52import java.sql.SQLException

Full Screen

Full Screen

setExecutingInitSql

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller.examples;2import org.evomaster.client.java.controller.EmbeddedSutController;3import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseInitializationDto;4import java.sql.SQLException;5public class DatabaseInitializationExample {6 public static void main(String[] args) throws SQLException {7 EmbeddedSutController controller = new EmbeddedSutController();8 DatabaseInitializationDto databaseInitializationDto = new DatabaseInitializationDto();9 databaseInitializationDto.setInitSql("CREATE TABLE IF NOT EXISTS user (id INT PRIMARY KEY, name VARCHAR(100));");10 controller.setExecutingInitSql(databaseInitializationDto);11 controller.startSut();12 controller.stopSut();13 }14}15package org.evomaster.client.java.controller.examples;16import org.evomaster.client.java.controller.EmbeddedSutController;17import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseInitializationDto;18import java.sql.SQLException;19public class DatabaseInitializationExample {20 public static void main(String[] args) throws SQLException {21 EmbeddedSutController controller = new EmbeddedSutController();22 DatabaseInitializationDto databaseInitializationDto = new DatabaseInitializationDto();23 databaseInitializationDto.setInitSql("CREATE TABLE IF NOT EXISTS user (id INT PRIMARY KEY, name VARCHAR(100));");24 controller.setExecutingInitSql(databaseInitializationDto);25 controller.startSut();26 controller.stopSut();27 }28}

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