Skip to content

Commit 47cd8a5

Browse files
committed
B Make TestUtils thread safe
TestUtils class uses the global variable getSourceDirectory to register a function to change the current test source directory. This may raise a race condition among tests running concurrently, so let's give each thread its own private copy of the variable.
1 parent bb5668e commit 47cd8a5

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

approvaltests-util/src/main/java/com/spun/util/tests/TestUtils.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,26 +26,27 @@
2626

2727
public class TestUtils
2828
{
29-
private static Random random;
30-
private static Function2<Class, String, File> getSourceDirectory = ClassUtils::getSourceDirectory;
29+
private static Random random;
30+
private static final ThreadLocal<Function2<Class, String, File>> getSourceDirectory = ThreadLocal
31+
.withInitial(() -> ClassUtils::getSourceDirectory);
3132
public static SourceDirectoryRestorer registerSourceDirectoryFinder(
3233
Function2<Class, String, File> sourceDirectoryFinder)
3334
{
3435
SourceDirectoryRestorer c = new SourceDirectoryRestorer();
35-
TestUtils.getSourceDirectory = sourceDirectoryFinder;
36+
TestUtils.getSourceDirectory.set(sourceDirectoryFinder);
3637
return c;
3738
}
3839
public static class SourceDirectoryRestorer implements AutoCloseable
3940
{
4041
private final Function2<Class, String, File> original;
4142
public SourceDirectoryRestorer()
4243
{
43-
this.original = TestUtils.getSourceDirectory;
44+
this.original = TestUtils.getSourceDirectory.get();
4445
}
4546
@Override
4647
public void close()
4748
{
48-
TestUtils.getSourceDirectory = original;
49+
TestUtils.getSourceDirectory.set(original);
4950
}
5051
}
5152
public static File getFile(String startingDir)
@@ -210,7 +211,7 @@ private static StackTraceReflectionResult getInfo(StackTraceElement element) thr
210211
String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
211212
className = handleInnerClasses(className);
212213
String fileName = element.getFileName();
213-
File dir = getSourceDirectory.call(ObjectUtils.loadClass(fullClassName), fileName);
214+
File dir = getSourceDirectory.get().call(ObjectUtils.loadClass(fullClassName), fileName);
214215
String methodName = unrollLambda(element.getMethodName());
215216
return new StackTraceReflectionResult(dir, className, fullClassName, methodName);
216217
}

0 commit comments

Comments
 (0)