This is an automated email from the ASF dual-hosted git repository. garydgregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-codec.git
commit 7b34ce4c7fb35c0dfd9386cdbd8b8f04f056f3f7 Author: Gary Gregory <[email protected]> AuthorDate: Sat Nov 21 15:58:47 2026 -0500 Make GitIdentifiers filesystem tests portable Check POSIX support and symbolic-link creation capabilities before running native fixtures, preserving fixture and cleanup failures. Derive expected link hashes from platform-specific target paths. Expand coverage for all 512 POSIX permission combinations, missing symlink privileges, non-POSIX filesystems, and link target formats. Update changes.xml. --- src/changes/changes.xml | 1 + .../codec/digest/GitIdentifiersFileSystemTest.java | 282 ++++++++++++++++++--- .../commons/codec/digest/GitIdentifiersTest.java | 64 +++-- 3 files changed, 300 insertions(+), 47 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 1e0521a3..8201b659 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -68,6 +68,7 @@ The <action> type attribute can be add,update,fix,remove. <action type="fix" dev="ggregory" due-to="Gary Gregory">Stop BaseNCodecInputStream from reading the underlying stream after codec EOF, preventing unnecessary reads and blocking after padding in lenient Base32 and Base64 decoding.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Compute Digest ALL and * standard-input digests in a single pass with bounded buffering, removing the mark/reset input-size limit.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Keep BaseNCodecInputStream.available() positive after codec EOF while output remains buffered.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Make GitIdentifiers filesystem tests account for unavailable POSIX attributes, symbolic-link creation privileges, and platform-specific link target paths.</action> <!-- ADD --> <!-- UPDATE --> <action type="update" dev="ggregory" due-to="Gary Gregory">Bump org.apache.commons:commons-parent from 105 to 107.</action> diff --git a/src/test/java/org/apache/commons/codec/digest/GitIdentifiersFileSystemTest.java b/src/test/java/org/apache/commons/codec/digest/GitIdentifiersFileSystemTest.java index 2b6eaf11..49e3dd8a 100644 --- a/src/test/java/org/apache/commons/codec/digest/GitIdentifiersFileSystemTest.java +++ b/src/test/java/org/apache/commons/codec/digest/GitIdentifiersFileSystemTest.java @@ -18,8 +18,12 @@ package org.apache.commons.codec.digest; import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -27,14 +31,20 @@ import java.io.InputStream; import java.lang.reflect.Proxy; import java.net.URI; import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; import java.nio.file.AccessDeniedException; import java.nio.file.AccessMode; import java.nio.file.CopyOption; import java.nio.file.DirectoryStream; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileStore; import java.nio.file.FileSystem; +import java.nio.file.FileSystemException; +import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.NotDirectoryException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.PathMatcher; @@ -56,19 +66,25 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; +import org.opentest4j.TestAbortedException; /** - * Tests file modes independently of the host file system's permissions and execution access. + * Tests filesystem capability assumptions, file modes, and symbolic links independently of the host filesystem. */ class GitIdentifiersFileSystemTest { /** - * A single-file tree exposing only the operations needed to compute its identifier. Proxies implement the small subset of the Path and attribute - * interfaces used by the tests; unsupported operations fail explicitly. No files or permissions on the host are changed. + * A single-entry tree with configurable attributes and symbolic-link operations. Proxies expose only the Path and attribute operations used by these + * tests; unsupported operations fail explicitly. No files or permissions on the host are changed. */ private static final class TestFileSystem extends FileSystem { @@ -76,7 +92,11 @@ class GitIdentifiersFileSystemTest { private boolean open = true; TestFileSystem(final String permissions, final boolean executable) { - provider = new TestFileSystemProvider(this, permissions, executable); + this(permissions, executable, null); + } + + TestFileSystem(final String permissions, final boolean executable, final String linkTarget) { + provider = new TestFileSystemProvider(this, permissions, executable, linkTarget); } @Override @@ -98,6 +118,8 @@ class GitIdentifiersFileSystemTest { return this; case "getFileName": return name.getFileName(); + case "resolve": + return getPath(name.resolve(args[0].toString()).toString()); case "toString": return name.toString(); default: @@ -133,7 +155,7 @@ class GitIdentifiersFileSystemTest { @Override public boolean isReadOnly() { - return true; + return false; } @Override @@ -158,21 +180,28 @@ class GitIdentifiersFileSystemTest { private final String permissions; private final boolean executable; private final BasicFileAttributes attributes; + private final String linkTarget; + private Exception linkCreationFailure; + private Exception deletionFailure; + private int linksCreated; + private int linksDeleted; - TestFileSystemProvider(final TestFileSystem fileSystem, final String permissions, final boolean executable) { + TestFileSystemProvider(final TestFileSystem fileSystem, final String permissions, final boolean executable, final String linkTarget) { this.fileSystem = fileSystem; this.permissions = permissions; this.executable = executable; + this.linkTarget = linkTarget; final Class<?> attributeType = permissions == null ? BasicFileAttributes.class : PosixFileAttributes.class; attributes = (BasicFileAttributes) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { attributeType }, (proxy, method, args) -> { switch (method.getName()) { case "isDirectory": - case "isSymbolicLink": case "isOther": return false; + case "isSymbolicLink": + return linkTarget != null; case "isRegularFile": - return true; + return linkTarget == null; case "permissions": return PosixFilePermissions.fromString(permissions); case "size": @@ -203,12 +232,25 @@ class GitIdentifiersFileSystemTest { } @Override - public void delete(final Path path) { - throw new UnsupportedOperationException(); + public void createSymbolicLink(final Path link, final Path target, final FileAttribute<?>... attrs) throws IOException { + assertEquals("symlink-capability-probe", link.getFileName().toString()); + assertEquals("symlink-capability-target", target.toString()); + throwIfConfigured(linkCreationFailure); + linksCreated++; + } + + @Override + public void delete(final Path path) throws IOException { + assertEquals("symlink-capability-probe", path.getFileName().toString()); + throwIfConfigured(deletionFailure); + linksDeleted++; } @Override public <V extends FileAttributeView> V getFileAttributeView(final Path path, final Class<V> type, final LinkOption... options) { + if (linkTarget != null) { + assertArrayEquals(new LinkOption[] { LinkOption.NOFOLLOW_LINKS }, options); + } if (type != BasicFileAttributeView.class && (type != PosixFileAttributeView.class || permissions == null)) { return null; } @@ -262,6 +304,7 @@ class GitIdentifiersFileSystemTest { @Override public DirectoryStream<Path> newDirectoryStream(final Path dir, final DirectoryStream.Filter<? super Path> filter) throws IOException { + assertEquals("root", dir.toString(), "A symbolic link must not be traversed as a directory"); final Path file = fileSystem.getPath("file.txt"); final Set<Path> entries = filter.accept(file) ? Collections.singleton(file) : Collections.emptySet(); return new DirectoryStream<Path>() { @@ -284,11 +327,15 @@ class GitIdentifiersFileSystemTest { @Override public InputStream newInputStream(final Path path, final OpenOption... options) { + assertNull(linkTarget, "Symbolic link contents must not be read through the target"); return new ByteArrayInputStream(CONTENT); } @Override public <A extends BasicFileAttributes> A readAttributes(final Path path, final Class<A> type, final LinkOption... options) { + if (linkTarget != null) { + assertArrayEquals(new LinkOption[] { LinkOption.NOFOLLOW_LINKS }, options); + } return type.cast(attributes); } @@ -297,6 +344,18 @@ class GitIdentifiersFileSystemTest { throw new UnsupportedOperationException(); } + @Override + public Path readSymbolicLink(final Path link) { + assertTrue(linkTarget != null, "This fixture must represent a symbolic link"); + // Preserve the provider's exact target text independently of the host's path syntax. + return (Path) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { Path.class }, (proxy, method, args) -> { + if ("toString".equals(method.getName())) { + return linkTarget; + } + throw new UnsupportedOperationException(method.getName()); + }); + } + @Override public void setAttribute(final Path path, final String attribute, final Object value, final LinkOption... options) { throw new UnsupportedOperationException(); @@ -305,45 +364,210 @@ class GitIdentifiersFileSystemTest { private static final byte[] CONTENT = { 'x' }; - private static void assertTreeId(final FileSystem fileSystem, final GitIdentifiers.FileMode mode) throws IOException { - final MessageDigest md = DigestUtils.getSha1Digest(); + private static void assertTreeId(final FileSystem fileSystem, final String algorithm, final GitIdentifiers.FileMode mode) throws IOException { + final MessageDigest md = DigestUtils.getDigest(algorithm); final GitIdentifiers.TreeIdBuilder builder = GitIdentifiers.treeIdBuilder(md); builder.addFile(mode, "file.txt", CONTENT); assertArrayEquals(builder.get(), GitIdentifiers.treeId(md, fileSystem.getPath("root"))); } + static Stream<Arguments> basicFileModes() { + return Stream.of(MessageDigestAlgorithms.SHA_1, MessageDigestAlgorithms.SHA_256) + .flatMap(algorithm -> Stream.of(false, true).map(executable -> Arguments.of(algorithm, executable))); + } + + static Stream<Arguments> posixFileModes() { + return Stream.of(MessageDigestAlgorithms.SHA_1, MessageDigestAlgorithms.SHA_256).flatMap(algorithm -> IntStream.range(0, 512).boxed() + .flatMap(mask -> Stream.of(false, true).map(executable -> { + final char[] permissions = "---------".toCharArray(); + for (int i = 0; i < permissions.length; i++) { + if ((mask & (1 << (8 - i))) != 0) { + permissions[i] = "rwxrwxrwx".charAt(i); + } + } + final GitIdentifiers.FileMode mode = (mask & 0100) == 0 ? GitIdentifiers.FileMode.REGULAR : GitIdentifiers.FileMode.EXECUTABLE; + return Arguments.of(algorithm, new String(permissions), executable, mode); + }))); + } + + static Stream<Arguments> symbolicLinks() { + return Stream.of(MessageDigestAlgorithms.SHA_1, MessageDigestAlgorithms.SHA_256).flatMap(algorithm -> + Stream.of(null, "rw-------", "rwxrwxrwx").flatMap(permissions -> Stream.of(false, true).flatMap(executable -> + Stream.of("file.txt", "subdir/file.txt", "subdir\\file.txt", "../missing.txt", "/target/file", "C:\\target\\file", + "directory", "dir/\u03bb.txt").map(target -> Arguments.of(algorithm, permissions, executable, target))))); + } + + private static void throwIfConfigured(final Exception failure) throws IOException { + if (failure instanceof IOException) { + throw (IOException) failure; + } + if (failure != null) { + throw (RuntimeException) failure; + } + } + + @ParameterizedTest + @ValueSource(strings = { MessageDigestAlgorithms.SHA_1, MessageDigestAlgorithms.SHA_256 }) + void testNativeBlobTestSkipsWithoutSymlinkPrivileges(final String algorithm) throws IOException { + try (TestFileSystem fileSystem = new TestFileSystem(null, false)) { + fileSystem.provider.linkCreationFailure = new AccessDeniedException("probe"); + assertThrows(TestAbortedException.class, + () -> new GitIdentifiersTest().testBlobIdSymlink(algorithm, "subdir/file.txt", false, fileSystem.getPath("root"))); + assertEquals(0, fileSystem.provider.linksCreated); + } + } + + @ParameterizedTest + @MethodSource("org.apache.commons.codec.digest.GitIdentifiersTest#virtualTreeProvider") + void testNativeUnixTreeSkipsWithoutPosix(final String algorithm, final byte[] helloId, final byte[] linkId, final byte[] linkTxtId, + final byte[] runId, final byte[] srcTreeId, final byte[] mainTreeId) throws IOException { + try (TestFileSystem fileSystem = new TestFileSystem(null, false)) { + assertThrows(TestAbortedException.class, () -> new GitIdentifiersTest().testTreeIdPathUnix(algorithm, helloId, linkId, linkTxtId, + runId, srcTreeId, mainTreeId, fileSystem.getPath("root"))); + assertEquals(0, fileSystem.provider.linksCreated, "The POSIX requirement must be checked before creating symbolic links"); + } + } + + @ParameterizedTest + @MethodSource("org.apache.commons.codec.digest.GitIdentifiersTest#virtualTreeProvider") + void testNativeUnixTreeSkipsWithoutSymlinkPrivileges(final String algorithm, final byte[] helloId, final byte[] linkId, final byte[] linkTxtId, + final byte[] runId, final byte[] srcTreeId, final byte[] mainTreeId) throws IOException { + try (TestFileSystem fileSystem = new TestFileSystem("rw-------", false)) { + fileSystem.provider.linkCreationFailure = new FileSystemException("probe", "target", "A required privilege is not held"); + assertThrows(TestAbortedException.class, () -> new GitIdentifiersTest().testTreeIdPathUnix(algorithm, helloId, linkId, linkTxtId, + runId, srcTreeId, mainTreeId, fileSystem.getPath("root"))); + assertEquals(0, fileSystem.provider.linksCreated); + } + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testPosixCapabilityAssumption(final boolean posix) throws IOException { + try (TestFileSystem fileSystem = new TestFileSystem(posix ? "rw-------" : null, false)) { + final Path directory = fileSystem.getPath("root"); + if (posix) { + assertDoesNotThrow(() -> GitIdentifiersTest.assumePosixAttributes(directory)); + } else { + assertThrows(TestAbortedException.class, () -> GitIdentifiersTest.assumePosixAttributes(directory)); + } + assertEquals(0, fileSystem.provider.linksCreated); + } + } + + @ParameterizedTest(name = "{0}, permissions={1}, access={2}, target={3}") + @MethodSource("symbolicLinks") + void testSymbolicLinksWithoutHostSupport(final String algorithm, final String permissions, final boolean executable, final String target) + throws IOException { + try (TestFileSystem fileSystem = new TestFileSystem(permissions, executable, target)) { + final MessageDigest md = DigestUtils.getDigest(algorithm); + final Path link = fileSystem.getPath("file.txt"); + final byte[] expectedBlob = GitIdentifiers.blobId(md, target.getBytes(StandardCharsets.UTF_8)); + assertArrayEquals(expectedBlob, GitIdentifiers.blobId(md, link)); + final GitIdentifiers.TreeIdBuilder builder = GitIdentifiers.treeIdBuilder(md); + builder.addSymbolicLink("file.txt", target); + assertArrayEquals(builder.get(), GitIdentifiers.treeId(md, fileSystem.getPath("root"))); + } + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testSymlinkProbeDoesNotHideCleanupFailures(final boolean posix) throws IOException { + for (final Exception failure : new Exception[] { new IOException("cleanup failed"), new AccessDeniedException("probe"), + new UnsupportedOperationException("cleanup unsupported"), new IllegalStateException("unexpected cleanup failure") }) { + try (TestFileSystem fileSystem = new TestFileSystem(posix ? "rw-------" : null, false)) { + fileSystem.provider.deletionFailure = failure; + assertSame(failure, assertThrows(failure.getClass(), () -> GitIdentifiersTest.assumeSymbolicLinks(fileSystem.getPath("root")))); + assertEquals(1, fileSystem.provider.linksCreated); + assertEquals(0, fileSystem.provider.linksDeleted); + } + } + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testSymlinkProbeDoesNotHideInvalidFixtures(final boolean posix) throws IOException { + for (final Exception failure : new Exception[] { new FileAlreadyExistsException("probe"), new NoSuchFileException("directory"), + new NotDirectoryException("directory"), new IllegalArgumentException("invalid target"), new IllegalStateException("broken provider") }) { + try (TestFileSystem fileSystem = new TestFileSystem(posix ? "rw-------" : null, false)) { + fileSystem.provider.linkCreationFailure = failure; + assertSame(failure, assertThrows(failure.getClass(), () -> GitIdentifiersTest.assumeSymbolicLinks(fileSystem.getPath("root")))); + assertEquals(0, fileSystem.provider.linksCreated); + assertEquals(0, fileSystem.provider.linksDeleted); + } + } + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testSymlinkProbeSkipsUnavailableCapabilities(final boolean posix) throws IOException { + for (final Exception failure : new Exception[] { new UnsupportedOperationException("links unsupported"), new IOException("links unavailable"), + new AccessDeniedException("probe"), new FileSystemException("probe", "target", "A required privilege is not held"), + new SecurityException("link permission denied") }) { + try (TestFileSystem fileSystem = new TestFileSystem(posix ? "rw-------" : null, false)) { + fileSystem.provider.linkCreationFailure = failure; + final TestAbortedException aborted = assertThrows(TestAbortedException.class, + () -> GitIdentifiersTest.assumeSymbolicLinks(fileSystem.getPath("root"))); + assertTrue(aborted.getMessage().contains(failure.toString())); + assertEquals(0, fileSystem.provider.linksCreated); + assertEquals(0, fileSystem.provider.linksDeleted); + } + } + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testSymlinkProbeSucceedsAndCleansUp(final boolean posix) throws IOException { + try (TestFileSystem fileSystem = new TestFileSystem(posix ? "rw-------" : null, false)) { + GitIdentifiersTest.assumeSymbolicLinks(fileSystem.getPath("root")); + assertEquals(1, fileSystem.provider.linksCreated); + assertEquals(1, fileSystem.provider.linksDeleted); + } + } + /** * Execution access without POSIX attributes must not turn an ordinary file into an executable Git entry. */ - @ParameterizedTest - @ValueSource(booleans = { false, true }) - void testTreeIdWithoutPosixPermissions(final boolean executable) throws IOException { + @ParameterizedTest(name = "{0}, access={1}") + @MethodSource("basicFileModes") + void testTreeIdWithoutPosixPermissions(final String algorithm, final boolean executable) throws IOException { try (TestFileSystem fileSystem = new TestFileSystem(null, executable)) { final Path file = fileSystem.getPath("file.txt"); assertNull(Files.getFileAttributeView(file, PosixFileAttributeView.class)); assertEquals(executable, Files.isExecutable(file)); - assertTreeId(fileSystem, GitIdentifiers.FileMode.REGULAR); + assertTreeId(fileSystem, algorithm, GitIdentifiers.FileMode.REGULAR); } } /** - * Only the owner-execute bit determines the Git mode, even when group permissions or an ACL give the current process different execution access. + * Checks all 512 POSIX permission combinations independently of process execution access, using both Git hash algorithms. */ - @ParameterizedTest - @CsvSource({ - "rw-------, false, REGULAR", - "rw-------, true, REGULAR", - "rw-r-xr--, true, REGULAR", - "rw-r--r-x, true, REGULAR", - "rwx------, false, EXECUTABLE", - "rwx------, true, EXECUTABLE" - }) - void testTreeIdWithPosixPermissions(final String permissions, final boolean executable, final GitIdentifiers.FileMode mode) throws IOException { + @ParameterizedTest(name = "{0}, permissions={1}, access={2}, mode={3}") + @MethodSource("posixFileModes") + void testTreeIdWithPosixPermissions(final String algorithm, final String permissions, final boolean executable, final GitIdentifiers.FileMode mode) + throws IOException { try (TestFileSystem fileSystem = new TestFileSystem(permissions, executable)) { final Path file = fileSystem.getPath("file.txt"); assertEquals(PosixFilePermissions.fromString(permissions), Files.getPosixFilePermissions(file)); assertEquals(executable, Files.isExecutable(file)); - assertTreeId(fileSystem, mode); + assertTreeId(fileSystem, algorithm, mode); + } + } + + @ParameterizedTest + @ValueSource(strings = { MessageDigestAlgorithms.SHA_1, MessageDigestAlgorithms.SHA_256 }) + void testZipFileSystemKeepsRegularFileCoverage(final String algorithm, @TempDir final Path tempDir) throws IOException { + Assumptions.assumeTrue(FileSystemProvider.installedProviders().stream().anyMatch(provider -> "jar".equals(provider.getScheme())), + "ZIP filesystem provider is unavailable"); + final URI uri = URI.create("jar:" + tempDir.resolve("tree.zip").toUri()); + try (FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.singletonMap("create", "true"))) { + final Path root = fileSystem.getPath("/"); + Files.write(root.resolve("file.txt"), CONTENT); + assertThrows(TestAbortedException.class, () -> GitIdentifiersTest.assumePosixAttributes(root)); + assertThrows(TestAbortedException.class, () -> GitIdentifiersTest.assumeSymbolicLinks(root)); + final MessageDigest digest = DigestUtils.getDigest(algorithm); + final GitIdentifiers.TreeIdBuilder builder = GitIdentifiers.treeIdBuilder(digest); + builder.addFile(GitIdentifiers.FileMode.REGULAR, "file.txt", CONTENT); + assertArrayEquals(builder.get(), GitIdentifiers.treeId(digest, root)); } } } diff --git a/src/test/java/org/apache/commons/codec/digest/GitIdentifiersTest.java b/src/test/java/org/apache/commons/codec/digest/GitIdentifiersTest.java index 17c98ba2..8adb9f4f 100644 --- a/src/test/java/org/apache/commons/codec/digest/GitIdentifiersTest.java +++ b/src/test/java/org/apache/commons/codec/digest/GitIdentifiersTest.java @@ -26,9 +26,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.util.ArrayList; @@ -130,6 +134,25 @@ class GitIdentifiersTest { */ private static final byte[] MAIN_TREE_ID_SHA256 = hex("58e9a59940e4d2ae7e374b63fedf3b7bba8cfdc60308f64abd066db137300bcd"); + static void assumePosixAttributes(final Path directory) { + Assumptions.assumeTrue(Files.getFileAttributeView(directory, PosixFileAttributeView.class) != null, + "POSIX file attributes are not supported on this filesystem"); + } + + static void assumeSymbolicLinks(final Path directory) throws IOException { + final Path probe = directory.resolve("symlink-capability-probe"); + final Path target = directory.getFileSystem().getPath("symlink-capability-target"); + try { + Files.createSymbolicLink(probe, target); + } catch (final FileAlreadyExistsException | NoSuchFileException | NotDirectoryException e) { + throw e; + } catch (final IOException | UnsupportedOperationException | SecurityException e) { + Assumptions.abort("Symbolic link creation is unavailable: " + e); + } + // A cleanup failure is a test failure, not evidence that symbolic links are unsupported. + Files.delete(probe); + } + static Stream<Arguments> blobIdProvider() { return Stream.of(Arguments.of("DigestUtilsTest/hello.txt", "5f4a83288e67f1be2d6fcdad84165a86c6a970d7"), Arguments.of("DigestUtilsTest/greetings.txt", "6cf4f797455661e61d1ee6913fc29344f5897243"), @@ -149,6 +172,12 @@ class GitIdentifiersTest { return Paths.get(GitIdentifiersTest.class.getClassLoader().getResource(resourceName).toURI()); } + static Stream<Arguments> symlinkProvider() { + return Stream.of(MessageDigestAlgorithms.SHA_1, MessageDigestAlgorithms.SHA_256).flatMap(algorithm -> + Stream.of("subdir", "subdir/file.txt", "subdir/missing.txt").flatMap(target -> + Stream.of(false, true).map(absolute -> Arguments.of(algorithm, target, absolute)))); + } + static Stream<Arguments> virtualTreeProvider() { return Stream.of( Arguments.of(MessageDigestAlgorithms.SHA_1, HELLO_BLOB_ID_SHA1, LINK_BLOB_ID_SHA1, LINK_TXT_BLOB_ID_SHA1, RUN_BLOB_ID_SHA1, @@ -190,19 +219,19 @@ class GitIdentifiersTest { assertArrayEquals(Hex.decodeHex(expectedSha1Hex), GitIdentifiers.blobId(DigestUtils.getSha1Digest(), resourcePath(resourceName))); } - @Test - void testBlobIdSymlink(@TempDir final Path tempDir) throws Exception { + @ParameterizedTest + @MethodSource("symlinkProvider") + void testBlobIdSymlink(final String algorithm, final String targetName, final boolean absolute, @TempDir final Path tempDir) throws Exception { + assumeSymbolicLinks(tempDir); final Path subDir = Files.createDirectory(tempDir.resolve("subdir")); Files.write(subDir.resolve("file.txt"), "hello".getBytes(StandardCharsets.UTF_8)); - try { - final Path linkToDir = Files.createSymbolicLink(tempDir.resolve("link-to-dir"), Paths.get("subdir")); - final Path linkToFile = Files.createSymbolicLink(tempDir.resolve("link-to-file"), Paths.get("subdir/file.txt")); - final MessageDigest sha1 = DigestUtils.getSha1Digest(); - assertArrayEquals(Hex.decodeHex("8bbe8a53790056316b23b7c270f10ab6bf6bb1b4"), GitIdentifiers.blobId(sha1, linkToDir)); - assertArrayEquals(Hex.decodeHex("dfe6ef8392ae13a11ff85419b4fd906d997b6cb7"), GitIdentifiers.blobId(sha1, linkToFile)); - } catch (final UnsupportedOperationException e) { - Assumptions.abort("Symbolic links not supported on this filesystem"); - } + final Path relativeTarget = tempDir.getFileSystem().getPath(targetName); + final Path target = absolute ? tempDir.resolve(relativeTarget) : relativeTarget; + final Path link = Files.createSymbolicLink(tempDir.resolve("link"), target); + final MessageDigest digest = DigestUtils.getDigest(algorithm); + // Path.toString() uses the filesystem's separators, including backslashes on Windows. + assertEquals(target.toString(), Files.readSymbolicLink(link).toString()); + assertArrayEquals(GitIdentifiers.blobId(digest, target.toString().getBytes(StandardCharsets.UTF_8)), GitIdentifiers.blobId(digest, link)); } @Test @@ -417,6 +446,8 @@ class GitIdentifiersTest { @MethodSource("virtualTreeProvider") void testTreeIdPathUnix(final String algorithm, final byte[] helloId, final byte[] linkId, final byte[] linkTxtId, final byte[] runId, final byte[] srcTreeId, final byte[] mainTreeId, final @TempDir Path tempDir) throws Exception { + assumePosixAttributes(tempDir); + assumeSymbolicLinks(tempDir); final MessageDigest md = DigestUtils.getDigest(algorithm); // Files @@ -426,17 +457,14 @@ class GitIdentifiersTest { final Path hello = src.resolve("hello.txt"); final Path run = src.resolve("run.sh"); - // Create the same structure as the virtual tree. - try { - Files.createSymbolicLink(link, Paths.get(LINK_CONTENT)); - Files.createSymbolicLink(linkTxt, Paths.get(LINK_TXT_CONTENT)); - } catch (final UnsupportedOperationException e) { - Assumptions.abort("Symbolic links not supported on this filesystem"); - } + // Create the same structure as the virtual tree after checking the required capabilities. Files.createDirectory(src); Files.write(hello, HELLO_CONTENT); Files.write(run, RUN_CONTENT); + Files.setPosixFilePermissions(hello, PosixFilePermissions.fromString("rw-r--r--")); Files.setPosixFilePermissions(run, PosixFilePermissions.fromString("rwxr-xr-x")); + Files.createSymbolicLink(link, tempDir.getFileSystem().getPath(LINK_CONTENT)); + Files.createSymbolicLink(linkTxt, tempDir.getFileSystem().getPath(LINK_TXT_CONTENT)); // Verify individual blob IDs against pre-computed constants. assertArrayEquals(helloId, GitIdentifiers.blobId(md, hello));
