/
TempDirectory.java
370 lines (322 loc) · 12.4 KB
/
TempDirectory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
* Copyright 2015-2021 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package org.junit.jupiter.engine.extension;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.util.stream.Collectors.joining;
import static org.junit.jupiter.api.io.CleanupMode.ALWAYS;
import static org.junit.jupiter.api.io.CleanupMode.DEFAULT;
import static org.junit.jupiter.api.io.CleanupMode.NEVER;
import static org.junit.jupiter.api.io.CleanupMode.ON_SUCCESS;
import static org.junit.jupiter.engine.config.JupiterConfiguration.TEMP_DIR_SCOPE_PROPERTY_NAME;
import static org.junit.platform.commons.util.AnnotationUtils.findAnnotatedFields;
import static org.junit.platform.commons.util.ReflectionUtils.makeAccessible;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Predicate;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionConfigurationException;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store.CloseableResource;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.io.CleanupMode;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.engine.config.EnumConfigurationParameterConverter;
import org.junit.jupiter.engine.config.JupiterConfiguration;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.support.AnnotationSupport;
import org.junit.platform.commons.util.ExceptionUtils;
import org.junit.platform.commons.util.ReflectionUtils;
/**
* {@code TempDirectory} is a JUnit Jupiter extension that creates and cleans
* up temporary directories if field in a test class or a parameter in a
* lifecycle method or test method is annotated with {@code @TempDir}.
*
* <p>Consult the Javadoc for {@link TempDir} for details on the contract.
*
* @since 5.4
* @see TempDir
* @see Files#createTempDirectory
*/
class TempDirectory implements BeforeAllCallback, BeforeEachCallback, ParameterResolver {
private static final Namespace NAMESPACE = Namespace.create(TempDirectory.class);
private static final String KEY = "temp.dir";
private static final String TEMP_DIR_PREFIX = "junit";
private final JupiterConfiguration configuration;
public TempDirectory(JupiterConfiguration configuration) {
this.configuration = configuration;
}
/**
* Perform field injection for non-private, {@code static} fields (i.e.,
* class fields) of type {@link Path} or {@link File} that are annotated with
* {@link TempDir @TempDir}.
*/
@Override
public void beforeAll(ExtensionContext context) {
injectStaticFields(context, context.getRequiredTestClass());
}
/**
* Perform field injection for non-private, non-static fields (i.e.,
* instance fields) of type {@link Path} or {@link File} that are annotated
* with {@link TempDir @TempDir}.
*/
@Override
public void beforeEach(ExtensionContext context) {
context.getRequiredTestInstances().getAllInstances() //
.forEach(instance -> injectInstanceFields(context, instance));
}
private void injectStaticFields(ExtensionContext context, Class<?> testClass) {
injectFields(context, null, testClass, ReflectionUtils::isStatic);
}
private void injectInstanceFields(ExtensionContext context, Object instance) {
injectFields(context, instance, instance.getClass(), ReflectionUtils::isNotStatic);
}
private void injectFields(ExtensionContext context, Object testInstance, Class<?> testClass,
Predicate<Field> predicate) {
findAnnotatedFields(testClass, TempDir.class, predicate).forEach(field -> {
assertSupportedType("field", field.getType());
try {
CleanupMode mode = findCleanupModeForField(field);
makeAccessible(field).set(testInstance, getPathOrFile(field, field.getType(), mode, context));
}
catch (Throwable t) {
ExceptionUtils.throwAsUncheckedException(t);
}
});
}
/**
* Determine if the {@link Parameter} in the supplied {@link ParameterContext}
* is annotated with {@link TempDir @TempDir}.
*/
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
boolean annotated = parameterContext.isAnnotated(TempDir.class);
if (annotated && parameterContext.getDeclaringExecutable() instanceof Constructor) {
throw new ParameterResolutionException(
"@TempDir is not supported on constructor parameters. Please use field injection instead.");
}
return annotated;
}
/**
* Resolve the current temporary directory for the {@link Parameter} in the
* supplied {@link ParameterContext}.
*/
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
Class<?> parameterType = parameterContext.getParameter().getType();
assertSupportedType("parameter", parameterType);
CleanupMode cleanupMode = findCleanupModeForParameter(parameterContext);
return getPathOrFile(parameterContext.getParameter(), parameterType, cleanupMode, extensionContext);
}
private CleanupMode findCleanupModeForParameter(ParameterContext parameterContext) {
CleanupMode cleanupMode = null;
Optional<TempDir> optional = parameterContext.findAnnotation(TempDir.class);
if (optional.isPresent()) {
cleanupMode = optional.get().cleanup();
}
if (cleanupMode == null || cleanupMode == DEFAULT) {
cleanupMode = ALWAYS;
}
return cleanupMode;
}
private CleanupMode findCleanupModeForField(Field field) {
CleanupMode cleanupMode = null;
Optional<TempDir> optional = AnnotationSupport.findAnnotation(field, TempDir.class);
if (optional.isPresent()) {
cleanupMode = optional.get().cleanup();
}
if (cleanupMode == null || cleanupMode == DEFAULT) {
cleanupMode = configuration.getDefaultTempDirCleanupMode();
}
return cleanupMode;
}
private void assertSupportedType(String target, Class<?> type) {
if (type != Path.class && type != File.class) {
throw new ExtensionConfigurationException("Can only resolve @TempDir " + target + " of type "
+ Path.class.getName() + " or " + File.class.getName() + " but was: " + type.getName());
}
}
private Object getPathOrFile(AnnotatedElement sourceElement, Class<?> type, CleanupMode cleanupMode,
ExtensionContext extensionContext) {
Namespace namespace = getScope(extensionContext) == Scope.PER_DECLARATION //
? NAMESPACE.append(sourceElement) //
: NAMESPACE;
Path path = extensionContext.getStore(namespace) //
.getOrComputeIfAbsent(KEY, __ -> createTempDir(cleanupMode, extensionContext), CloseablePath.class) //
.get();
return (type == Path.class) ? path : path.toFile();
}
private Scope getScope(ExtensionContext context) {
return context.getRoot().getStore(NAMESPACE).getOrComputeIfAbsent( //
Scope.class, //
__ -> new EnumConfigurationParameterConverter<>(Scope.class, "@TempDir scope") //
.get(TEMP_DIR_SCOPE_PROPERTY_NAME, context::getConfigurationParameter, Scope.PER_DECLARATION), //
Scope.class //
);
}
static CloseablePath createTempDir(CleanupMode cleanupMode, ExtensionContext executionContext) {
try {
return new CloseablePath(Files.createTempDirectory(TEMP_DIR_PREFIX), cleanupMode, executionContext);
}
catch (Exception ex) {
throw new ExtensionConfigurationException("Failed to create default temp directory", ex);
}
}
static class CloseablePath implements CloseableResource {
private static final Logger logger = LoggerFactory.getLogger(CloseablePath.class);
private final Path dir;
private final CleanupMode cleanupMode;
private final ExtensionContext executionContext;
CloseablePath(Path dir, CleanupMode cleanupMode, ExtensionContext executionContext) {
this.dir = dir;
this.cleanupMode = cleanupMode;
this.executionContext = executionContext;
}
Path get() {
return dir;
}
@Override
public void close() throws IOException {
if (cleanupMode == NEVER
|| (cleanupMode == ON_SUCCESS && executionContext.getExecutionException().isPresent())) {
logger.info(() -> "Skipping cleanup of temp dir " + dir + " due to cleanup mode configuration.");
return;
}
SortedMap<Path, IOException> failures = deleteAllFilesAndDirectories();
if (!failures.isEmpty()) {
throw createIOExceptionWithAttachedFailures(failures);
}
}
private SortedMap<Path, IOException> deleteAllFilesAndDirectories() throws IOException {
if (Files.notExists(dir)) {
return Collections.emptySortedMap();
}
SortedMap<Path, IOException> failures = new TreeMap<>();
resetPermissions(dir);
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (!dir.equals(CloseablePath.this.dir)) {
resetPermissions(dir);
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
// IOException includes `AccessDeniedException` thrown by non-readable or non-executable flags
resetPermissionsAndTryToDeleteAgain(file, exc);
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
return deleteAndContinue(file);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return deleteAndContinue(dir);
}
private FileVisitResult deleteAndContinue(Path path) {
try {
Files.delete(path);
}
catch (NoSuchFileException ignore) {
// ignore
}
catch (DirectoryNotEmptyException exception) {
failures.put(path, exception);
}
catch (IOException exception) {
// IOException includes `AccessDeniedException` thrown by non-readable or non-executable flags
resetPermissionsAndTryToDeleteAgain(path, exception);
}
return CONTINUE;
}
private void resetPermissionsAndTryToDeleteAgain(Path path, IOException exception) {
try {
resetPermissions(path);
if (Files.isDirectory(path)) {
Files.walkFileTree(path, this);
}
else {
Files.delete(path);
}
}
catch (Exception suppressed) {
exception.addSuppressed(suppressed);
failures.put(path, exception);
}
}
});
return failures;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static void resetPermissions(Path path) {
File file = path.toFile();
file.setReadable(true);
file.setWritable(true);
if (Files.isDirectory(path)) {
file.setExecutable(true);
}
}
private IOException createIOExceptionWithAttachedFailures(SortedMap<Path, IOException> failures) {
// @formatter:off
String joinedPaths = failures.keySet().stream()
.map(this::tryToDeleteOnExit)
.map(this::relativizeSafely)
.map(String::valueOf)
.collect(joining(", "));
// @formatter:on
IOException exception = new IOException("Failed to delete temp directory " + dir.toAbsolutePath()
+ ". The following paths could not be deleted (see suppressed exceptions for details): "
+ joinedPaths);
failures.values().forEach(exception::addSuppressed);
return exception;
}
private Path tryToDeleteOnExit(Path path) {
try {
path.toFile().deleteOnExit();
}
catch (UnsupportedOperationException ignore) {
}
return path;
}
private Path relativizeSafely(Path path) {
try {
return dir.relativize(path);
}
catch (IllegalArgumentException e) {
return path;
}
}
}
enum Scope {
PER_CONTEXT,
PER_DECLARATION
}
}