IMI-Application/src/test/java/de/vanitasvitae/imi/codes/persistence/FileRepositoryTest.java

90 lines
3.1 KiB
Java

package de.vanitasvitae.imi.codes.persistence;
import static junit.framework.TestCase.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.Stack;
import de.vanitasvitae.imi.codes.input.InvalidOptionException;
import de.vanitasvitae.imi.codes.types.StudyNumber;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class FileRepositoryTest {
private static FileRepository repository;
@BeforeClass
public static void setup() {
// Create a temporary test directory in %TEMP%/imicodes
File systemTemp = new File(System.getProperty("java.io.tmpdir"));
File tempDir = new File(systemTemp, "imicodes");
repository = new FileRepository(tempDir);
}
/**
* Test, if the {@link FileRepository} correctly stores and returns values to/from file, and if hard coded values
* are respected the first time they are used.
*
* @throws InvalidOptionException NOT expected.
* @throws IOException hopefully NOT expected (the temp dir should be readable)
*/
@Test
public void testReadWriteSampleNumbers() throws InvalidOptionException, IOException {
StudyNumber studyNumber = new StudyNumber("abc");
assertEquals("An unknown study number must return 0 as next sample number",
0, repository.getNextSampleCode(studyNumber));
// The written next sample code must be returned next time
int next = 34;
repository.setNextSampleCode(studyNumber, next);
assertEquals("The written next sample number must be read next time.",
next, repository.getNextSampleCode(studyNumber));
// The FileRepository contains 35 as hard coded sample number for study "AAA".
StudyNumber hardCoded = new StudyNumber("AAA");
assertEquals("The hard coded value must be returned the first time its being read.",
35, repository.getNextSampleCode(hardCoded));
repository.setNextSampleCode(hardCoded, 89);
assertEquals("If the hard coded value is overwritten, the new value must be read.",
89, repository.getNextSampleCode(hardCoded));
}
@AfterClass
public static void tearDown() {
// Delete the temporary directory which was set up earlier.
deleteDirectory(repository.getBaseDirectory());
}
/**
* Recursively delete a directory and its contents.
*
* @param root root directory
*/
private static void deleteDirectory(File root) {
if (!root.exists()) {
return;
}
File[] currList;
Stack<File> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
if (stack.lastElement().isDirectory()) {
currList = stack.lastElement().listFiles();
if (currList != null && currList.length > 0) {
for (File curr : currList) {
stack.push(curr);
}
} else {
stack.pop().delete();
}
} else {
stack.pop().delete();
}
}
}
}