Skip to content

Commit

Permalink
fixes #43
Browse files Browse the repository at this point in the history
  • Loading branch information
rmpestano committed Sep 8, 2016
1 parent e559e72 commit 5a067d2
Show file tree
Hide file tree
Showing 12 changed files with 319 additions and 43 deletions.
22 changes: 11 additions & 11 deletions core/src/main/java/com/github/dbunit/rules/DBUnitRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ public void evaluate() throws Throwable {
currentMethod = description.getMethodName();
DataSet dataSet = resolveDataSet(description);
if (dataSet != null) {
final DataSetConfig model = new DataSetConfig().from(dataSet);
final String datasetExecutorId = model.getExecutorId();
final DataSetConfig dataSetConfig = new DataSetConfig().from(dataSet);
final String datasetExecutorId = dataSetConfig.getExecutorId();
DBUnitConfig dbUnitConfig = resolveDBUnitConfig(description);
LeakHunter leakHunter = null;
boolean executorNameIsProvided = datasetExecutorId != null && !"".equals(datasetExecutorId.trim());
Expand All @@ -75,13 +75,13 @@ public void evaluate() throws Throwable {
}
try {
executor.setDBUnitConfig(dbUnitConfig);
executor.createDataSet(model);
executor.createDataSet(dataSetConfig);
} catch (final Exception e) {
throw new RuntimeException("Could not create dataset due to following error " + e.getMessage(), e);
}
boolean isTransactional = false;
try {
isTransactional = model.isTransactional() && isEntityManagerActive();
isTransactional = dataSetConfig.isTransactional() && isEntityManagerActive();
if (isTransactional) {
em().getTransaction().begin();
}
Expand Down Expand Up @@ -112,17 +112,17 @@ public void evaluate() throws Throwable {
throw e;
} finally {

if (model != null && model.getExecuteStatementsAfter() != null && model.getExecuteStatementsAfter().length > 0) {
if (dataSetConfig != null && dataSetConfig.getExecuteStatementsAfter() != null && dataSetConfig.getExecuteStatementsAfter().length > 0) {
try {
executor.executeStatements(model.getExecuteStatementsAfter());
executor.executeStatements(dataSetConfig.getExecuteStatementsAfter());
} catch (Exception 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) {
if (dataSetConfig != null && dataSetConfig.getExecuteScriptsAfter() != null && dataSetConfig.getExecuteScriptsAfter().length > 0) {
try {
for (int i = 0; i < model.getExecuteScriptsAfter().length; i++) {
executor.executeScript(model.getExecuteScriptsAfter()[i]);
for (int i = 0; i < dataSetConfig.getExecuteScriptsAfter().length; i++) {
executor.executeScript(dataSetConfig.getExecuteScriptsAfter()[i]);
}
} catch (Exception e) {
if (e instanceof DatabaseUnitException) {
Expand All @@ -132,8 +132,8 @@ public void evaluate() throws Throwable {
}
}//end execute scripts

if (model.isCleanAfter()) {
executor.clearDatabase(model);
if (dataSetConfig.isCleanAfter()) {
executor.clearDatabase(dataSetConfig);
}
}
} else {
Expand Down
95 changes: 68 additions & 27 deletions junit5/src/main/java/com/github/dbunit/junit5/DBUnitExtension.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
import com.github.dbunit.rules.dataset.DataSetExecutorImpl;
import com.github.dbunit.rules.leak.LeakHunterException;
import com.github.dbunit.rules.leak.LeakHunterFactory;
import org.dbunit.DatabaseUnitException;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExtensionContext;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
Expand All @@ -27,9 +29,9 @@
* Created by pestano on 27/08/16.
*/
public class DBUnitExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {

private static final String EXECUTOR_STORE = "executor";
private static final String MODEL_STORE = "model";
private static final String DATASET_CONFIG_STORE = "datasetConfig";
private static final String LEAK_STORE = "leakHunter";
private static final String CONNECTION_BEFORE_STORE = "openConnectionsBefore";

Expand All @@ -40,11 +42,12 @@ public void beforeTestExecution(TestExtensionContext testExtensionContext) throw
return;
}

ConnectionHolder connectionHolder = findTestConnection(testExtensionContext);

if (isEntityManagerActive()) {
em().clear();
}

ConnectionHolder connectionHolder = findTestConnection(testExtensionContext);

DataSet annotation = testExtensionContext.getTestMethod().get().getAnnotation(DataSet.class);
if (annotation == null) {
Expand All @@ -63,8 +66,8 @@ public void beforeTestExecution(TestExtensionContext testExtensionContext) throw

ExtensionContext.Namespace namespace = getExecutorNamespace(testExtensionContext);//one executor per test class
testExtensionContext.getStore(namespace).put(EXECUTOR_STORE, executor);
testExtensionContext.getStore(namespace).put(MODEL_STORE, dasetConfig);
if(dbUnitConfig.isLeakHunter()){
testExtensionContext.getStore(namespace).put(DATASET_CONFIG_STORE, dasetConfig);
if (dbUnitConfig.isLeakHunter()) {
LeakHunter leakHunter = LeakHunterFactory.from(connectionHolder.getConnection());
testExtensionContext.getStore(namespace).put(LEAK_STORE, leakHunter);
testExtensionContext.getStore(namespace).put(CONNECTION_BEFORE_STORE, leakHunter.openConnections());
Expand All @@ -75,6 +78,7 @@ public void beforeTestExecution(TestExtensionContext testExtensionContext) throw
} catch (final Exception e) {
throw new RuntimeException(String.format("Could not create dataset for test method %s due to following error " + e.getMessage(), testExtensionContext.getTestMethod().get().getName()), e);
}

boolean isTransactional = dasetConfig.isTransactional() && isEntityManagerActive();
if (isTransactional) {
em().getTransaction().begin();
Expand All @@ -95,31 +99,68 @@ private boolean shouldCompareDataSet(TestExtensionContext testExtensionContext)
@Override
public void afterTestExecution(TestExtensionContext testExtensionContext) throws Exception {
DBUnitConfig dbUnitConfig = DBUnitConfig.from(testExtensionContext.getTestMethod().get());
if(dbUnitConfig.isLeakHunter()){
ExtensionContext.Namespace executorNamespace = getExecutorNamespace(testExtensionContext);
LeakHunter leakHunter = testExtensionContext.getStore(executorNamespace).get(LEAK_STORE,LeakHunter.class);
int openConnectionsBefore = testExtensionContext.getStore(executorNamespace).get(CONNECTION_BEFORE_STORE,Integer.class);
int openConnectionsAfter = leakHunter.openConnections();
if(openConnectionsAfter > openConnectionsBefore){
throw new LeakHunterException(testExtensionContext.getTestMethod().get().getName(),openConnectionsAfter - openConnectionsBefore);
ExtensionContext.Namespace executorNamespace = getExecutorNamespace(testExtensionContext);
try {
if (dbUnitConfig != null && dbUnitConfig.isLeakHunter()) {
LeakHunter leakHunter = testExtensionContext.getStore(executorNamespace).get(LEAK_STORE, LeakHunter.class);
int openConnectionsBefore = testExtensionContext.getStore(executorNamespace).get(CONNECTION_BEFORE_STORE, Integer.class);
int openConnectionsAfter = leakHunter.openConnections();
if (openConnectionsAfter > openConnectionsBefore) {
throw new LeakHunterException(testExtensionContext.getTestMethod().get().getName(), openConnectionsAfter - openConnectionsBefore);
}

}

}
if (shouldCompareDataSet(testExtensionContext)) {
ExpectedDataSet expectedDataSet = testExtensionContext.getTestMethod().get().getAnnotation(ExpectedDataSet.class);
if (expectedDataSet == null) {
//try to infer from class level annotation
expectedDataSet = testExtensionContext.getTestClass().get().getAnnotation(ExpectedDataSet.class);
if (shouldCompareDataSet(testExtensionContext)) {
ExpectedDataSet expectedDataSet = testExtensionContext.getTestMethod().get().getAnnotation(ExpectedDataSet.class);
if (expectedDataSet == null) {
//try to infer from class level annotation
expectedDataSet = testExtensionContext.getTestClass().get().getAnnotation(ExpectedDataSet.class);
}
if (expectedDataSet != null) {
ExtensionContext.Namespace namespace = getExecutorNamespace(testExtensionContext);//one executor per test class
DataSetExecutor executor = testExtensionContext.getStore(namespace).get(EXECUTOR_STORE, DataSetExecutor.class);
DataSetConfig datasetConfig = testExtensionContext.getStore(namespace).get(DATASET_CONFIG_STORE, DataSetConfig.class);
boolean isTransactional = datasetConfig.isTransactional() && isEntityManagerActive();
if (isTransactional) {
em().getTransaction().commit();
}
executor.compareCurrentDataSetWith(new DataSetConfig(expectedDataSet.value()).disableConstraints(true), expectedDataSet.ignoreCols());
}
}
if (expectedDataSet != null) {
ExtensionContext.Namespace namespace = getExecutorNamespace(testExtensionContext);//one executor per test class
DataSetExecutor executor = testExtensionContext.getStore(namespace).get(EXECUTOR_STORE, DataSetExecutor.class);
DataSetConfig datasetConfig = testExtensionContext.getStore(namespace).get(MODEL_STORE, DataSetConfig.class);
boolean isTransactional = datasetConfig.isTransactional() && isEntityManagerActive();
if (isTransactional) {
em().getTransaction().commit();
} finally {
DataSetConfig dataSetConfig = testExtensionContext.getStore(executorNamespace).get(DATASET_CONFIG_STORE, DataSetConfig.class);
if (dataSetConfig == null) {
return;
}
DataSetExecutor executor = testExtensionContext.getStore(executorNamespace).get(EXECUTOR_STORE, DataSetExecutor.class);
if (dataSetConfig.getExecuteStatementsAfter() != null && dataSetConfig.getExecuteStatementsAfter().length > 0) {
try {
for (int i = 0; i < dataSetConfig.getExecuteScriptsAfter().length; i++) {
executor.executeScript(dataSetConfig.getExecuteScriptsAfter()[i]);
}
} catch (Exception e) {
if (e instanceof DatabaseUnitException) {
throw e;
}
LoggerFactory.getLogger(getClass().getName()).error(testExtensionContext.getTestMethod().get().getName() + "() - Could not execute scriptsAfter:" + e.getMessage(), e);
}
}//end execute scripts

if (dataSetConfig.getExecuteScriptsAfter() != null && dataSetConfig.getExecuteScriptsAfter().length > 0) {
try {
for (int i = 0; i < dataSetConfig.getExecuteScriptsAfter().length; i++) {
executor.executeScript(dataSetConfig.getExecuteScriptsAfter()[i]);
}
} catch (Exception e) {
if (e instanceof DatabaseUnitException) {
throw e;
}
LoggerFactory.getLogger(getClass().getName()).error(testExtensionContext.getTestMethod().get().getName() + "() - Could not execute scriptsAfter:" + e.getMessage(), e);
}
executor.compareCurrentDataSetWith(new DataSetConfig(expectedDataSet.value()).disableConstraints(true), expectedDataSet.ignoreCols());
}//end execute scripts

if (dataSetConfig.isCleanAfter()) {
executor.clearDatabase(dataSetConfig);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.github.dbunit.junit5;

import com.github.dbunit.junit5.model.User;
import com.github.dbunit.rules.api.connection.ConnectionHolder;
import com.github.dbunit.rules.api.dataset.DataSet;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

import java.util.List;

import static com.github.dbunit.rules.util.EntityManagerProvider.em;
import static com.github.dbunit.rules.util.EntityManagerProvider.instance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;

/**
* Created by pestano on 26/02/16.
*/
@ExtendWith(DBUnitExtension.class)
@RunWith(JUnitPlatform.class)
public class CleanBeforeAfterIt {

private ConnectionHolder connectionHolder = () ->
instance("junit5-pu").connection();


@BeforeAll
public static void before(){
em("junit5-pu").getTransaction().begin();
em().createNativeQuery("DELETE FROM USER").executeUpdate();
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);

}

@AfterAll
public static void after(){
List<User> users = em().createQuery("select u from User u").getResultList();
if(users != null && !users.isEmpty()){
fail("users should be empty");
}
}


@Test
@DataSet(value = "users.yml", cleanBefore = true, cleanAfter = true)
public void shouldCleanDatabaseBefore() {
List<User> users = em().createQuery("select u from User u").getResultList();
assertThat(users).isNotNull().hasSize(2);//dataset has 2 users, user inserted in @Before must not be present
User userInsertedInBefore = new User(6);//user inserted in @before has id 6
assertThat(users).doesNotContain(userInsertedInBefore);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
//tag::declaration[]
@ExtendWith(DBUnitExtension.class) //<1>
@RunWith(JUnitPlatform.class) //<2>
public class DBUnitJUnit5Test {
public class DBUnitJUnit5It {

//end::declaration[]

Expand All @@ -42,7 +42,7 @@ public void shouldListUsers() {
//end::test[]

@Test
@DataSet(cleanBefore=true) //avoid conflict with other tests
@DataSet(cleanBefore=true,cleanAfter = true) //avoid conflict with other tests
public void shouldInsertUser() {
User user = new User();
user.setName("user");
Expand All @@ -56,7 +56,7 @@ public void shouldInsertUser() {
}

@Test
@DataSet("users.yml") //no need for clean before because DBUnit uses CLEAN_INSERT seeding strategy which clears involved tables before seeding
@DataSet(value="users.yml",cleanAfter = true) //no need for clean before because DBUnit uses CLEAN_INSERT seeding strategy which clears involved tables before seeding
public void shouldUpdateUser() {
User user = (User) em().createQuery("select u from User u where u.id = 1").getSingleResult();
assertThat(user).isNotNull();
Expand All @@ -71,7 +71,7 @@ public void shouldUpdateUser() {
}

@Test
@DataSet(value = "users.yml", transactional = true)
@DataSet(value = "users.yml", transactional = true, cleanAfter = true)
@ExpectedDataSet("expectedUser.yml")
public void shouldDeleteUser() {
User user = (User) em().createQuery("select u from User u where u.id = 1").getSingleResult();
Expand All @@ -81,6 +81,13 @@ public void shouldDeleteUser() {
}


@Test
public void shouldNotSeedDatabaseListUsers() {
List<User> users = em().createQuery("select u from User u").getResultList();
assertThat(users).isEmpty();
}


public User getUser(Long id){
return (User) em().createQuery("select u from User u where u.id = :id").
setParameter("id", id).getSingleResult();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
*/
@ExtendWith(DBUnitExtension.class)
@RunWith(JUnitPlatform.class)
public class DBUnitJUnit5WithMethodConnectionHolderTest {
public class DBUnitJUnit5WithMethodConnectionHolderIt {

//DBUnitExtension will get connection by reflection so either declare a field or a method with ConncetionHolder as return typr
private ConnectionHolder getConnection(){
Expand Down
Loading

0 comments on commit 5a067d2

Please sign in to comment.