Skip to content

Commit

Permalink
Merge pull request #1314 from mherman22/DictionaryTest
Browse files Browse the repository at this point in the history
(test) Add tests for the Dictionary Service methods
  • Loading branch information
mozzy11 authored Nov 19, 2024
2 parents 9d1c280 + 175987e commit 2914aa4
Show file tree
Hide file tree
Showing 5 changed files with 375 additions and 29 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,12 @@
<version>${springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.7.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
Expand Down
141 changes: 136 additions & 5 deletions src/test/java/org/openelisglobal/BaseWebContextSensitiveTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,59 @@
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.junit.runner.RunWith;
import java.io.InputStream;
import java.util.*;
import javax.sql.DataSource;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@ContextConfiguration(classes = { BaseTestConfig.class, AppTestConfig.class })
@WebAppConfiguration
@TestPropertySource("classpath:common.properties")
@ActiveProfiles("test")
public abstract class BaseWebContextSensitiveTest {
public abstract class BaseWebContextSensitiveTest extends AbstractTransactionalJUnit4SpringContextTests {

@Autowired
protected WebApplicationContext webApplicationContext;

@Autowired
private DataSource dataSource;

protected MockMvc mockMvc;

protected void setUp() {
private Map<String, IDataSet> originalStateCache;

private List<String[]> tablesToRestore;

protected BaseWebContextSensitiveTest() {
this.originalStateCache = new HashMap<>();
this.tablesToRestore = new ArrayList<>();
}

protected BaseWebContextSensitiveTest(List<String[]> tablesToRestore) {
this.originalStateCache = new HashMap<>();
this.tablesToRestore = tablesToRestore != null ? tablesToRestore : new ArrayList<>();
}

protected void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}

Expand All @@ -44,4 +72,107 @@ public <T> T mapFromJson(String json, Class<T> clazz) throws IOException {
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
return objectMapper.readValue(json, clazz);
}

/**
* Executes a dataset with state management - preserves and restores the
* original state of affected tables after execution.
*/
protected void executeDataSetWithStateManagement(String datasetFilename) throws Exception {
if (datasetFilename == null) {
throw new NullPointerException("Please provide test dataset file to execute!");
}

IDatabaseConnection connection = null;
try {
connection = new DatabaseConnection(dataSource.getConnection());
DatabaseConfig config = connection.getConfig();
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);

IDataSet newDataSet = loadDataSet(datasetFilename);
String[] tableNames = newDataSet.getTableNames();

// Backup current state of affected tables
IDataSet currentState = connection.createDataSet(tableNames);
originalStateCache.put(Arrays.toString(tableNames), currentState);
tablesToRestore.add(tableNames);

executeDataSet(datasetFilename);
} finally {
if (connection != null) {
connection.close();
}
}
}

/**
* This method will be called after each transaction to restore the database
* state
*/
@AfterTransaction
@SuppressWarnings("unused")
protected void restoreDatabase() throws Exception {
try {
for (String[] tableNames : tablesToRestore) {
String key = Arrays.toString(tableNames);
IDataSet originalState = originalStateCache.get(key);
if (originalState != null) {
IDatabaseConnection connection = null;
try {
connection = new DatabaseConnection(dataSource.getConnection());
DatabaseConfig config = connection.getConfig();
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);

DatabaseOperation.CLEAN_INSERT.execute(connection, originalState);
} finally {
if (connection != null) {
connection.close();
}
}
originalStateCache.remove(key);
}
}
} finally {
originalStateCache.clear();
tablesToRestore.clear();
}
}

/**
* Loads a dataset from an XML file.
*/
private IDataSet loadDataSet(String datasetFilename) throws Exception {
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(datasetFilename)) {
if (inputStream == null) {
throw new IllegalArgumentException("Dataset file '" + datasetFilename + "' not found in classpath");
}
return new FlatXmlDataSet(inputStream);
}
}

/**
* Executes a dataset from an XML file.
*/
protected void executeDataSet(String datasetFilename) throws Exception {
if (datasetFilename == null) {
throw new NullPointerException("please provide test dataset file to execute!");
}

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(datasetFilename);
try (inputStream) {
if (inputStream == null) {
throw new IllegalArgumentException("Dataset file '" + datasetFilename + "' not found in classpath");
}
IDatabaseConnection connection = new DatabaseConnection(dataSource.getConnection());

DatabaseConfig config = connection.getConfig();
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
IDataSet dataset = new FlatXmlDataSet(inputStream);

try {
DatabaseOperation.REFRESH.execute(connection, dataset);
} finally {
connection.close();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
import org.openelisglobal.dictionarycategory.valueholder.DictionaryCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.web.servlet.MvcResult;

@Rollback
public class DictionaryMenuRestControllerTest extends BaseWebContextSensitiveTest {

@Autowired
Expand All @@ -32,8 +34,9 @@ public class DictionaryMenuRestControllerTest extends BaseWebContextSensitiveTes

@Before
@Override
public void setUp() {
public void setUp() throws Exception {
super.setUp();
executeDataSetWithStateManagement("testdata/dictionary.xml");
}

@Test
Expand All @@ -47,9 +50,10 @@ public void getDictionaryMenuList_shouldReturnDictionaryMenu() throws Exception
List<DictionaryMenuForm> menuList = Arrays.asList(super.mapFromJson(content, DictionaryMenuForm[].class));
assertThat(menuList.get(0).getMenuList().get(0).getId(), is("1"));
assertThat(menuList.get(0).getMenuList().get(0).getIsActive(), is("Y"));
assertThat(menuList.get(0).getMenuList().get(0).getDictEntry(), is("INFLUENZA VIRUS A RNA DETECTED"));
assertThat(menuList.get(0).getMenuList().get(0).getSortOrder(), is(100));
assertThat(menuList.get(0).getMenuList().get(0).getDictionaryCategory().getCategoryName(), is("CG"));
assertThat(menuList.get(0).getMenuList().get(0).getDictEntry(), is("Dictionary Entry 1"));
assertThat(menuList.get(0).getMenuList().get(0).getSortOrder(), is(1));
assertThat(menuList.get(0).getMenuList().get(0).getDictionaryCategory().getCategoryName(),
is("Category Name 1"));
}

@Test
Expand All @@ -64,26 +68,6 @@ public void fetchDictionaryCategories_shouldFetchDictionaryDescriptions() throws
assertThat(menuList, notNullValue());
}

// TODO: To be looked into later

// @Test
// public void createDictionary_shouldSuccessfullyCreateDictionary() throws
// Exception {
// Dictionary dictionary = createDictionaryObject();
// String toJson = super.mapToJson(dictionary);
//
// MvcResult mvcResult = super.mockMvc.perform(
// post("/rest/dictionary")
// .accept(MediaType.APPLICATION_JSON_VALUE)
// .contentType(MediaType.APPLICATION_JSON_VALUE)
// .content(toJson)).andReturn();
//
// int status = mvcResult.getResponse().getStatus();
// assertEquals(201, status);
// String content = mvcResult.getResponse().getContentAsString();
// assertEquals(content, "Dictionary created successfully");
// }

@Test
public void showDeleteDictionary_shouldSuccessfullyDeleteDictionary() throws Exception {
MvcResult getMenu = super.mockMvc.perform(get("/rest/DictionaryMenu").accept(MediaType.APPLICATION_JSON_VALUE)
Expand Down
Loading

0 comments on commit 2914aa4

Please sign in to comment.