Search code examples
javadirectoryoperating-systemsymlink

Symlink path always starts from /private/


I wrote a function that creates a symlink to a specific directory inside a given parent directory. It does not create the link directly, but rather create a tmp link, and then move that tmp link to the desired path, as move operation is atomic while overwrite is not.

public static void updateMySymlink(final Path parentDir, final String targetDirName) {
    final Path targetPath = parentDir.resolve(targetDirName);
    final Path tempPath = parentDir.resolve("tmp");
    final Path symlinkPath = parentDir.resolve("mySymlink");
    Files.createSymbolicLink(tempPath, targetPath);
    Files.move(tempPath, symlinkPath, ATOMIC_MOVE);
}

When I try to unit-test this, I wrote a test like:

@Test
public void testSymlinkCreation() {
    final Path targetPath = localRepoPath.resolve("target");
    final Path symlinkPath = localRepoPath.resolve("mySymlink");
    FileUtils.forceMkdir(targetPath.toFile());
    updateMySymlink(localRepoPath, "testCommitId1"); // static method
    assertThat(targetPath).isEqualTo(symlinkPath.toRealPath());
}

This test fails with the message:

org.junit.ComparisonFailure: expected:</[private/]tmp/testDirToCreate-...> but was:</[]tmp/testDirToCreate-...>

No matter how the input paths changes, this private/ stays the same. I tried asserting for the absolutePaths or for the paths after normalization but it still failed for the same error.

My question is, where is this private/ is coming from?


Solution

  • Figured out the issue was that I'm using .toRealPath() only on the symlinkPath. Modifying the assertion to:

    assertThat(targetPath.toRealPath()).isEqualTo(symlinkPath.toRealPath());
    

    solved the problem.