Best EvoMaster code snippet using org.evomaster.client.java.controller.db.SqlScriptRunner.shouldExecuteInsert
Source:SqlScriptRunner.java
...308 public static void execScript(Connection conn, String script, List<String> tablesToInsert) throws SQLException {309 if (tablesToInsert == null || tablesToInsert.isEmpty()) return;310 List<String> commands = extractSql(script);311 for (String command : commands){312 if(shouldExecuteInsert(command, tablesToInsert)){313 execCommand(conn, command+";");314 }315 }316 }317 /**318 *319 * @param script is a SQL script320 * @return a list of SQL commands based on the script321 */322 public static List<String> extractSql(String script){323 String[] commands = script.split(";");324 return Arrays.stream(commands).filter(325 s-> !s.replaceAll("\r\n","") // on Windows326 .replaceAll("\n","") // on Unix327 .isEmpty()).map(s-> s+";").collect(Collectors.toList());328 }329 /**330 * extract a map from table name to a list of SQL INSERT commands for initializing data into the table331 * @param commands a list of SQL commands to be extracted332 * @return the map from table name (key) to a list of SQL INSERT commands (values) on the table333 */334 public static Map<String, List<String>> extractSqlTableMap(List<String> commands){335 Map<String, List<String>> tableSqlMap = new HashMap<>();336 for (String command: commands){337 if (ParserUtils.isInsert(command)){338 Insert stmt = (Insert) ParserUtils.asStatement(command);339 Table table = stmt.getTable();340 tableSqlMap.putIfAbsent(table.getName(), new ArrayList<>());341 tableSqlMap.get(table.getName()).add(command+";");342 }343 }344 return tableSqlMap;345 }346 public static QueryResult execCommand(Connection conn, String command) throws SQLException {347 return execCommand(conn, command, false);348 }349 public static QueryResult execCommand(Connection conn, String command, boolean instrumented) throws SQLException {350 Statement statement = conn.createStatement();351 SimpleLogger.debug("Executing DB command:");352 SimpleLogger.debug(command);353 try {354 if(!instrumented) {355 statement.execute(command);356 } else {357 /*358 this is needed only in the tests for EM itself... note that we cannot359 instrument classes in the org.evomaster package360 */361 StatementClassReplacement.execute(statement, command);362 }363 } catch (SQLException e) {364 statement.close();365 String errText = String.format("Error executing '%s': %s", command, e.getMessage());366 throw new SQLException(errText, e);367 }368 ResultSet result = statement.getResultSet();369 QueryResult queryResult = new QueryResult(result);370 statement.close();371 return queryResult;372 }373 private static boolean shouldExecuteInsert(String command, List<String> tablesToInsert){374 if (!ParserUtils.isInsert(command)) return true;375 if (tablesToInsert == null || tablesToInsert.isEmpty()) return false;376 Insert stmt = (Insert) ParserUtils.asStatement(command);377 Table table = stmt.getTable();378 return table!= null && tablesToInsert.stream().anyMatch(t-> t.equalsIgnoreCase(table.getName()));379 }380}...
shouldExecuteInsert
Using AI Code Generation
1public class ExampleTest extends EMTestBase {2 public void testRun() throws Exception {3 RestAssuredMockMvc.given()4 .contentType(ContentType.JSON)5 .accept(ContentType.JSON)6 .body(new ObjectMapper().writeValueAsString(new ExampleDto("aValue")))7 .post("/example")8 .then()9 .statusCode(HttpStatus.OK.value());10 String sql = "INSERT INTO example (id, value) VALUES (1, 'anotherValue')";11 SqlScriptRunner.shouldExecuteInsert(sql);12 RestAssuredMockMvc.given()13 .accept(ContentType.JSON)14 .get("/example/1")15 .then()16 .statusCode(HttpStatus.OK.value())17 .body("value", equalTo("anotherValue"));18 }19}20public class ExampleEMTest extends EMTestBase {21 public void testRun() throws Exception {22 RestAssuredMockMvc.given()23 .contentType(ContentType.JSON)24 .accept(ContentType.JSON)25 .body(new ObjectMapper().writeValueAsString(new ExampleDto("aValue")))26 .post("/example")27 .then()28 .statusCode(HttpStatus.OK.value());29 String sql = "INSERT INTO example (id, value) VALUES (1, 'anotherValue')";30 SqlScriptRunner.shouldExecuteInsert(sql);31 RestAssuredMockMvc.given()32 .accept(ContentType.JSON)33 .get("/example/1")34 .then()35 .statusCode(HttpStatus.OK.value())36 .body("value", equalTo("anotherValue"));37 }38}39public class ExampleEMTest extends EMTestBase {40 public void testRun() throws Exception {41 RestAssuredMockMvc.given()42 .contentType(ContentType.JSON)43 .accept(ContentType.JSON)44 .body(new ObjectMapper().writeValueAsString(new ExampleDto("aValue")))45 .post("/example")46 .then()47 .statusCode(HttpStatus.OK.value());48 String sql = "INSERT INTO example (id, value) VALUES (1, 'anotherValue')";49 SqlScriptRunner.shouldExecuteInsert(sql);
shouldExecuteInsert
Using AI Code Generation
1import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto2import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto3import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto4import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType5import org.evomaster.client.java.controller.api.dto.database.schema.TableDto6import org.evomaster.client.java.controller.internal.db.SqlScriptRunner7import org.evomaster.client.java.controller.internal.db.SqlScriptRunnerImpl8import org.evomaster.client.java.controller.internal.db.schema.SqlScriptExecutor9import org.evomaster.client.java.controller.internal.db.schema.SqlScriptExecutorImpl10import org.junit.jupiter.api.Assertions.assertEquals11import org.junit.jupiter.api.Assertions.assertTrue12import org.junit.jupiter.api.Test13import org.slf4j.LoggerFactory14import javax.sql.DataSource15class SqlScriptRunnerTest {16 companion object {17 private val log = LoggerFactory.getLogger(SqlScriptRunnerTest::class.java)18 }19 private fun init(dataSource: DataSource, databaseType: DatabaseType) {20 executor = SqlScriptExecutorImpl(dataSource, databaseType)21 runner = SqlScriptRunnerImpl(executor!!)22 }23 fun testInsert() {24 val ds = TestContainersHelper.getDataSource("mysql:8.0.21")25 init(ds, DatabaseType.MYSQL)26 val table = TableDto("t", listOf("id", "name"), listOf("int", "varchar(255)"))27 executor!!.createTable(table)28 val script = SqlScriptDto(29 "insert into t values(1, 'foo'), (2, 'bar')",30 listOf(31 InsertionDto("t", listOf("id", "name"), listOf("1", "'foo'")),32 InsertionDto("t", listOf("id", "name"), listOf("2", "'bar'"))33 runner!!.shouldExecuteInsert(script)34 val commands = executor!!.getExecutedDatabaseCommands()35 assertEquals(2, commands.size)36 assertEquals("insert into t values(
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!