Unit test files left in place

@teleivo I kindly need your advice on this ticket TRUNK-5875 . In BaseContextSensitiveTest there’s a part of the code that looks like this:

File tempappdir = File.createTempFile("appdir-for-unit-tests-", "");
tempappdir.delete(); // so we can make it into a directory
tempappdir.mkdir(); // turn it into a directory
tempappdir.deleteOnExit(); // clean up when we're done with tests

which is suspected to be the problem being that deleteOnExit() doesn’t properly clean-up a directory. To fix this we need to change to something like this:

final File tempappdir = File.createTempFile("appdir-for-unit-tests-", "");
tempappdir.delete(); // so we can make it into a directory
tempappdir.mkdir(); // turn it into a directory
// clean up when we're done with tests
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
	try {
		FileUtils.deleteDirectory(tempappdir);
	}
	catch (IOException ignored) {
	}
}));

Where FileUtils is the Apache commons-io version of FileUtils and the same fix needs to be applied to a couple of other place in the code that temporarily create an appdir-for-unit-tests directory.Just wondering if there is a better way to handle this in JUnit 5 which we are migrating to ?

2 Likes

Since these are JUnit base test classes we could in JUnit 4 use a @Rule https://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html

JUnit 5 has no Rules anymore and solves this using https://junit.org/junit5/docs/5.4.0/api/org/junit/jupiter/api/io/TempDir.html

We currently have 2 base classes one for JUnit 4 one for JUnit 5. That is necessary so that module developers can gradually migrate. I assume the issue exists for both base classes.

We might run into the issue discussed here tests failing in core on Windows that tests start failing because JUnit is not able to delete the directory. This happens when our code or tests do not release their connection to files in the temp dir. But let’s see :slight_smile:

1 Like

Thanks for the feedback.

Can someone point me to BaseContextSensitiveTest for JUnit5 or something similar please?

Are you looking for this? https://github.com/openmrs/openmrs-core/blob/master/api/src/test/java/org/openmrs/test/jupiter/BaseContextSensitiveTest.java

Thanks so so much!

@dkayiwa I can access BaseContextSensitiveTest for JUnit5 on a master branch pretty well but when I switch to my local branch it disappears.What could be the cause?

Did you try? git pull --rebase upstream master

I did but I wouldn’t mind doing it again.

@dkayiwa its sorted! thanks.