|
| 1 | +package datadog.common.filesystem; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 5 | + |
| 6 | +import datadog.environment.JavaVirtualMachine; |
| 7 | +import java.io.File; |
| 8 | +import java.io.IOException; |
| 9 | +import java.security.Permission; |
| 10 | +import org.junit.jupiter.api.Test; |
| 11 | +import org.junit.jupiter.api.condition.DisabledIf; |
| 12 | + |
| 13 | +public class FilesTest { |
| 14 | + |
| 15 | + private SecurityManager originalSM; |
| 16 | + |
| 17 | + @Test |
| 18 | + void existsReturnsTrueWhenFileExistsAndIsAccessible() throws IOException { |
| 19 | + File file = File.createTempFile("test", "txt"); |
| 20 | + file.deleteOnExit(); |
| 21 | + |
| 22 | + assertTrue(Files.exists(file)); |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + void existsReturnsFalseWhenFileDoesNotExist() throws IOException { |
| 27 | + File file = File.createTempFile("missing", "txt"); |
| 28 | + assertTrue(file.delete()); // ensure it does not exist |
| 29 | + |
| 30 | + assertFalse(Files.exists(file)); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + @DisabledIf("isJava18OrLater") |
| 35 | + void existsReturnsFalseWhenSecurityManagerForbidsFileAccess() throws IOException { |
| 36 | + File file = File.createTempFile("test", "txt"); |
| 37 | + file.deleteOnExit(); |
| 38 | + |
| 39 | + // --- install restrictive SecurityManager only in this test --- |
| 40 | + SecurityManager originalSM = System.getSecurityManager(); |
| 41 | + |
| 42 | + System.setSecurityManager( |
| 43 | + new SecurityManager() { |
| 44 | + @Override |
| 45 | + public void checkRead(String filePath) { |
| 46 | + // Deny only THIS file so classloading still works |
| 47 | + if (filePath.equals(file.getAbsolutePath())) { |
| 48 | + throw new SecurityException("Access denied"); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + @Override |
| 53 | + public void checkPermission(Permission perm) { |
| 54 | + // allow everything else |
| 55 | + } |
| 56 | + |
| 57 | + @Override |
| 58 | + public void checkPermission(Permission perm, Object context) { |
| 59 | + // allow everything else |
| 60 | + } |
| 61 | + }); |
| 62 | + |
| 63 | + try { |
| 64 | + boolean result = Files.exists(file); |
| 65 | + assertFalse(result); |
| 66 | + } finally { |
| 67 | + // --- restore original security manager --- |
| 68 | + System.setSecurityManager(originalSM); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + static boolean isJava18OrLater() { |
| 73 | + return JavaVirtualMachine.isJavaVersionAtLeast(18); |
| 74 | + } |
| 75 | +} |
0 commit comments