How to use doEmploySmartDbClean method of org.evomaster.client.java.controller.internal.SutController class

Best EvoMaster code snippet using org.evomaster.client.java.controller.internal.SutController.doEmploySmartDbClean

Source:SutController.java Github

copy

Full Screen

...211 /**212 *213 * @return whether to employ smart db clean214 */215 public final boolean doEmploySmartDbClean(){216 return getDbSpecifications() != null217 && !getDbSpecifications().isEmpty() && getDbSpecifications().get(0).employSmartDbClean;218 }219 public final void resetExtraHeuristics() {220 sqlHandler.reset();221 }222 public final List<ExtraHeuristicsDto> getExtraHeuristics() {223 if (extras.size() == actionIndex) {224 extras.add(computeExtraHeuristics());225 }226 return new ArrayList<>(extras);227 }228 public final ExtraHeuristicsDto computeExtraHeuristics() {229 ExtraHeuristicsDto dto = new ExtraHeuristicsDto();230 if(sqlHandler.isCalculateHeuristics() || sqlHandler.isExtractSqlExecution()){231 /*232 TODO refactor, once we move SQL analysis into Core233 */234 List<AdditionalInfo> list = getAdditionalInfoList();235 if(!list.isEmpty()) {236 AdditionalInfo last = list.get(list.size() - 1);237 last.getSqlInfoData().stream().forEach(it -> {238// String sql = it.getCommand();239 try {240 sqlHandler.handle(it);241 } catch (Exception e){242 SimpleLogger.error("FAILED TO HANDLE SQL COMMAND: " + it.getCommand());243 assert false; //we should try to handle all cases in our tests244 }245 });246 }247 }248 if(sqlHandler.isCalculateHeuristics()) {249 sqlHandler.getDistances().stream()250 .map(p ->251 new HeuristicEntryDto(252 HeuristicEntryDto.Type.SQL,253 HeuristicEntryDto.Objective.MINIMIZE_TO_ZERO,254 p.sqlCommand,255 p.distance256 ))257 .forEach(h -> dto.heuristics.add(h));258 }259 if (sqlHandler.isCalculateHeuristics() || sqlHandler.isExtractSqlExecution()){260 ExecutionDto executionDto = sqlHandler.getExecutionDto();261 dto.databaseExecutionDto = executionDto;262 // set accessed table263 if (executionDto != null){264 accessedTables.addAll(executionDto.deletedData);265 accessedTables.addAll(executionDto.insertedData.keySet());266// accessedTables.addAll(executionDto.queriedData.keySet());267 accessedTables.addAll(executionDto.insertedData.keySet());268 accessedTables.addAll(executionDto.updatedData.keySet());269 }270 }271 return dto;272 }273 /**274 * perform smart db clean by cleaning the data in accessed table275 */276 public final void cleanAccessedTables(){277 if (getDbSpecifications() == null || getDbSpecifications().isEmpty()) return;278 if (getDbSpecifications().size() > 1)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 }...

Full Screen

Full Screen

doEmploySmartDbClean

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.internal.SutController;2import org.evomaster.client.java.controller.internal.db.DbCleaner;3import org.evomaster.client.java.controller.internal.db.SqlScriptRunner;4public void initClass() throws Exception {5 SutController.getInstance().doEmploySmartDbClean(6 new DbCleaner(7 new SqlScriptRunner(8 SutController.getInstance().getSutHandler().getDatabaseDriver(),9 SutController.getInstance().getSutHandler().getDatabaseName(),10 SutController.getInstance().getSutHandler().getDatabaseUsername(),11 SutController.getInstance().getSutHandler().getDatabasePassword(),12 SutController.getInstance().getSutHandler().getDatabasePort(),13 SutController.getInstance().getSutHandler().getDatabaseSchema(),14 SutController.getInstance().getSutHandler().getDatabaseHost(),15 SutController.getInstance().getSutHandler().getDatabaseDialect()16 SutController.getInstance().getSutHandler().getDatabaseInitializationSql()17 );18}19import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;20import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;

Full Screen

Full Screen

doEmploySmartDbClean

Using AI Code Generation

copy

Full Screen

1public void cleanDatabase(){2 SutController controller = SutController.getInstance();3 controller.doEmploySmartDbClean("db");4}5public void resetSut(){6 SutController controller = SutController.getInstance();7 controller.doResetStateOfSUT();8}

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.

Run EvoMaster automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful