Closed
Description
On macOS, temp-directories are symlinked to /private/var
, which may cause unexpected results when testing code that handles symlinks.
Taking the following example:
package main
import (
"os"
"path/filepath"
"testing"
)
func TestSymLink(t *testing.T) {
tmpDir := t.TempDir()
srcPath := filepath.Join(tmpDir, "/source")
dstPath := filepath.Join(tmpDir, "/symlinked")
if err := os.Mkdir(srcPath, 0o777); err != nil {
t.Errorf("failed to create directory: %s", err)
}
if err := os.Symlink(srcPath, dstPath); err != nil {
t.Errorf("failed to create symlink: %s", err)
}
t.Run("using original tmpDir", func(t *testing.T) {
p, err := filepath.EvalSymlinks(dstPath)
if err != nil {
t.Error(err)
}
if p != srcPath {
t.Errorf("expected %q, got %q", srcPath, p)
}
})
t.Run("using actual tmpDir", func(t *testing.T) {
// On macOS, tmp itself is symlinked, so resolve this one upfront.
realTmpDir, err := filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
realSrcPath := filepath.Join(realTmpDir, "/source")
p, err := filepath.EvalSymlinks(dstPath)
if err != nil {
t.Error(err)
}
if p != realSrcPath {
t.Errorf("expected %q, got %q", realSrcPath, p)
}
})
}
Running the test shows that the "using original tmpDir" test fails;
go test -v .
=== RUN TestSymLink
=== RUN TestSymLink/using_original_tmpDir
sys_test.go:131: expected "/var/folders/6f/tz5jf4nn1_n5jb0ctrrw5p2w0000gn/T/TestSymLink727570636/001/source", got "/private/var/folders/6f/tz5jf4nn1_n5jb0ctrrw5p2w0000gn/T/TestSymLink727570636/001/source"
=== RUN TestSymLink/using_actual_tmpDir
--- FAIL: TestSymLink (0.00s)
--- FAIL: TestSymLink/using_original_tmpDir (0.00s)
--- PASS: TestSymLink/using_actual_tmpDir (0.00s)
FAIL
While this may be "expected", and it's possible to work around this, it's cumbersome (and easy to overlook) to have to resolve the actual path for t.TempDir()
for tests that may expect the path returned to be the actual path.
Proposal
Make t.TempDir()
resolve and return the actual path.