Skip to content

Commit

Permalink
fixes #14
Browse files Browse the repository at this point in the history
  • Loading branch information
rmpestano committed Feb 27, 2016
1 parent ac8a9ba commit 4151fda
Show file tree
Hide file tree
Showing 8 changed files with 189 additions and 9 deletions.
14 changes: 11 additions & 3 deletions core/src/main/java/com/github/dbunit/rules/DBUnitRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
import java.sql.Connection;
import java.sql.SQLException;

import static org.junit.Assert.fail;

/**
* Created by rafael-pestano on 22/07/2015.
*/
Expand Down Expand Up @@ -91,9 +89,19 @@ public void evaluate() throws Throwable {
try {
executor.executeStatements(model.getExecuteStatementsAfter());
} catch (Exception e) {
LoggerFactory.getLogger(getClass().getName()).error(currentMethod + "() - Could not createDataSet statements after:" + e.getMessage(), e);
LoggerFactory.getLogger(getClass().getName()).error(currentMethod + "() - Could not execute statements after:" + e.getMessage(), e);
}
}//end execute statements
if (model != null && model.getExecuteScriptsAfter() != null && model.getExecuteScriptsAfter().length > 0) {
try {
for (int i = 0; i < model.getExecuteScriptsAfter().length; i++) {
executor.executeScript(model.getExecuteScriptsAfter()[i]);
}
} catch (Exception e) {
LoggerFactory.getLogger(getClass().getName()).error(currentMethod + "() - Could not execute scriptsAfter:" + e.getMessage(), e);
}
}//end execute scripts

if(model.isCleanAfter()){
executor.clearDatabase(model);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,29 @@
boolean disableConstraints() default false;

/**
* @return a list of jdbc statements to createDataSet before test
* @return a list of jdbc statements to execute before test
*
*/
String[] executeStatementsBefore() default {};

/**
* @return a list of jdbc statements to createDataSet after test
* @return a list of jdbc statements to execute after test
*/
String[] executeStatementsAfter() default {};

/**
* @return a list of sql script files to execute before test.
* Note that commands inside sql file must be separated by ';'
*
*/
String[] executeScriptsBefore() default {};

/**
* @return a list of sql script files to execute after test.
* Note that commands inside sql file must be separated by ';'
*/
String[] executeScriptsAfter() default {};

/**
* @return if true DBUnit rules will try to delete database before test in a 'smart way'
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class DataSetModel {
private String[] tableOrdering = {};
private String[] executeStatementsBefore = {};
private String[] executeStatementsAfter = {};
private String[] executeScriptsBefore = {};
private String[] executeScriptsAfter = {};


public DataSetModel() {
Expand Down Expand Up @@ -71,6 +73,16 @@ public DataSetModel executeStatementsAfter(String[] executeStatementsAfter) {
return this;
}

public DataSetModel executeScripsBefore(String[] executeScriptsBefore) {
this.executeScriptsBefore = executeScriptsBefore;
return this;
}

public DataSetModel executeScriptsAfter(String[] executeScriptsAfter) {
this.executeScriptsAfter = executeScriptsAfter;
return this;
}

/**
* name of dataset executor for the given dataset. If not specified the default one will be used.
*
Expand All @@ -91,9 +103,11 @@ public DataSetModel from(DataSet dataSet) {
disableConstraints(dataSet.disableConstraints()).
executorId(dataSet.executorId()).
executeStatementsBefore(dataSet.executeStatementsBefore()).
executeScripsBefore(dataSet.executeScriptsBefore()).
cleanBefore(dataSet.cleanBefore()).
cleanAfter(dataSet.cleanAfter()).
executeStatementsAfter(dataSet.executeStatementsAfter());
executeStatementsAfter(dataSet.executeStatementsAfter()).
executeScriptsAfter(dataSet.executeScriptsAfter());
} else{
throw new RuntimeException("Cannot create DataSetModel from Null DataSet");
}
Expand All @@ -102,7 +116,6 @@ public DataSetModel from(DataSet dataSet) {




public String getName() {
return name;
}
Expand Down Expand Up @@ -131,6 +144,14 @@ public String[] getExecuteStatementsAfter() {
return executeStatementsAfter;
}

public String[] getExecuteScriptsBefore() {
return executeScriptsBefore;
}

public String[] getExecuteScriptsAfter() {
return executeScriptsAfter;
}

public String getExecutorId() {
return executorId;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.github.dbunit.rules.dataset;

import java.io.File;
import java.io.InputStream;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
Expand Down Expand Up @@ -101,6 +103,12 @@ public void createDataSet(DataSetModel dataSetModel) {
if (dataSetModel.getExecuteStatementsBefore() != null && dataSetModel.getExecuteStatementsBefore().length > 0) {
executeStatements(dataSetModel.getExecuteStatementsBefore());
}

if (dataSetModel.getExecuteScriptsBefore() != null && dataSetModel.getExecuteScriptsBefore().length > 0) {
for (int i = 0; i < dataSetModel.getExecuteScriptsBefore().length; i++) {
executeScript(dataSetModel.getExecuteScriptsBefore()[i]);
}
}
for (String dataSet : dataSets) {
dataSetName = dataSet.trim();
String extension = dataSetName.substring(dataSetName.lastIndexOf('.') + 1).toLowerCase();
Expand Down Expand Up @@ -326,6 +334,61 @@ private List<String> getTableNames(Connection con) {
}
}

public void executeScript(String scriptPath){
URL resource = Thread.currentThread().getContextClassLoader().getResource(scriptPath.trim());

This comment has been minimized.

Copy link
@Toilal

Toilal Feb 29, 2016

Contributor

Any reason to use context classloader instead of current class loader ? (getClass().getResource(...))

String absolutePath = "";
if(resource != null){
absolutePath = resource.getPath();
} else{
resource = Thread.currentThread().getContextClassLoader().getResource("scripts/"+scriptPath.trim());
if(resource != null){
absolutePath = resource.getPath();
}
}
if(resource == null){
throw new RuntimeException(String.format("Could not find script %s in classpath",scriptPath));
}

File scriptFile = new File(Paths.get(absolutePath).toUri());

String[] scriptsStatements = readScriptStatements(scriptFile);
if(scriptsStatements != null && scriptsStatements.length > 0){
executeStatements(scriptsStatements);
}
}

private String[] readScriptStatements(File scriptFile) {
RandomAccessFile rad = null;
int lineNum = 0;
try {
rad = new RandomAccessFile(scriptFile,"r");
String line;
List<String> scripts = new ArrayList<>();
while ((line = rad.readLine()) != null) {
//a line can have multiple scripts separated by ;
String[] lineScripts = line.split(";");
for (int i = 0; i < lineScripts.length; i++) {
scripts.add(lineScripts[i]);
}
lineNum++;
}
return scripts.toArray(new String[scripts.size()]);
} catch (Exception e) {
log.warn(String.format("Could not read script file %s. Error in line %d.",scriptFile.getAbsolutePath(),lineNum),e);
return null;
} finally {
if(rad != null){
try {
rad.close();
} catch (IOException e) {
log.warn("Could not close script file "+scriptFile.getAbsolutePath());

}
}
}

}

@Override
public void setDataSetModel(DataSetModel dataSetModel) {
this.dataSetModel = dataSetModel;
Expand Down
68 changes: 68 additions & 0 deletions core/src/test/java/com/github/dbunit/rules/ScriptsIt.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.github.dbunit.rules;

import com.github.dbunit.rules.api.dataset.DataSet;
import com.github.dbunit.rules.api.dataset.SeedStrategy;
import com.github.dbunit.rules.model.User;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import javax.persistence.EntityManager;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;

/**
* Created by pestano on 27/02/16.
*/
@RunWith(JUnit4.class)
public class ScriptsIt {

@Rule
public EntityManagerProvider emProvider = EntityManagerProvider.instance("rules-it");

@Rule
public DBUnitRule dbUnitRule = DBUnitRule.instance(emProvider.getConnection());

@BeforeClass
public static void before() {
EntityManager em = EntityManagerProvider.instance("rules-it").em();
em.getTransaction().begin();
em.createNativeQuery("INSERT INTO USER VALUES (6,'user6')").executeUpdate();
em.flush();
em.getTransaction().commit();
List<User> users = em.createQuery("select u from User u").getResultList();
assertThat(users).isNotNull().hasSize(1);
}

@Test
@DataSet(value = "yml/users.yml", executeScriptsBefore = {"users.sql","tweets.sql"},
executeScriptsAfter = "after.sql", strategy = SeedStrategy.INSERT)//NEED to be INSERT because clean will delete users inserted in script
public void shouldExecuteScriptsBefore() {
User userFromSqlScript = new User(10);
List<User> users = listUsers("select u from User u where u.id = 6");
assertThat(users).isNotNull().hasSize(0);//user insert in @Before was deleted by users.sql script
users = listUsers("select u from User u");
assertThat(users).isNotNull().hasSize(3)// two from users.yaml dataset and one from users.sql script
.contains(userFromSqlScript);
}

private List<User> listUsers(String sql) {
return EntityManagerProvider.instance("rules-it").em().createQuery(sql).getResultList();
}

@AfterClass
public static void after() {
List<User> users = EntityManagerProvider.instance("rules-it").em().createQuery("select u from User u").getResultList();
if (users == null || users.size() != 1) {
fail("We should have 1 user after test execution");
}
User user = users.get(0);//after script deletes all users and insert one
assertThat(user.getName()).isNotNull().isEqualTo("user-after");
}

}
4 changes: 4 additions & 0 deletions core/src/test/resources/scripts/after.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
DELETE FROM Follower;
DELETE FROM Tweet;
DELETE FROM User;
INSERT INTO USER VALUES (99,'user-after');
1 change: 1 addition & 0 deletions core/src/test/resources/scripts/tweets.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO Tweet (id,content,user_id) VALUES (10,'tweet10',10)
2 changes: 2 additions & 0 deletions core/src/test/resources/scripts/users.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DELETE FROM User;
INSERT INTO USER VALUES (10,'user10');

0 comments on commit 4151fda

Please sign in to comment.