github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/testutil/testdir_test.go (about) 1 package testutil 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 ) 8 9 func TestTempDir_DirIsValid(t *testing.T) { 10 dir := TempDir(t) 11 12 stat, err := os.Stat(dir) 13 if err != nil { 14 t.Errorf("TestDir returns %q which cannot be stated", dir) 15 } 16 if !stat.IsDir() { 17 t.Errorf("TestDir returns %q which is not a dir", dir) 18 } 19 } 20 21 func TestTempDir_DirHasSymlinksResolved(t *testing.T) { 22 dir := TempDir(t) 23 24 resolved, err := filepath.EvalSymlinks(dir) 25 if err != nil { 26 panic(err) 27 } 28 if dir != resolved { 29 t.Errorf("TestDir returns %q, but it resolves to %q", dir, resolved) 30 } 31 } 32 33 func TestTempDir_CleanupRemovesDirRecursively(t *testing.T) { 34 c := &cleanuper{} 35 dir := TempDir(c) 36 37 err := os.WriteFile(filepath.Join(dir, "a"), []byte("test"), 0600) 38 if err != nil { 39 panic(err) 40 } 41 42 c.runCleanups() 43 if _, err := os.Stat(dir); err == nil { 44 t.Errorf("Dir %q still exists after cleanup", dir) 45 } 46 } 47 48 func TestChdir(t *testing.T) { 49 dir := TempDir(t) 50 original := getWd() 51 52 c := &cleanuper{} 53 Chdir(c, dir) 54 55 after := getWd() 56 if after != dir { 57 t.Errorf("pwd is now %q, want %q", after, dir) 58 } 59 60 c.runCleanups() 61 restored := getWd() 62 if restored != original { 63 t.Errorf("pwd restored to %q, want %q", restored, original) 64 } 65 } 66 67 func TestApplyDir_CreatesFiles(t *testing.T) { 68 InTempDir(t) 69 70 ApplyDir(Dir{ 71 "a": "a content", 72 "b": "b content", 73 }) 74 75 testFileContent(t, "a", "a content") 76 testFileContent(t, "b", "b content") 77 } 78 79 func TestApplyDir_CreatesDirectories(t *testing.T) { 80 InTempDir(t) 81 82 ApplyDir(Dir{ 83 "d": Dir{ 84 "d1": "d1 content", 85 "d2": "d2 content", 86 "dd": Dir{ 87 "dd1": "dd1 content", 88 }, 89 }, 90 }) 91 92 testFileContent(t, "d/d1", "d1 content") 93 testFileContent(t, "d/d2", "d2 content") 94 testFileContent(t, "d/dd/dd1", "dd1 content") 95 } 96 97 func TestApplyDir_AllowsExistingDirectories(t *testing.T) { 98 InTempDir(t) 99 100 ApplyDir(Dir{"d": Dir{}}) 101 ApplyDir(Dir{"d": Dir{"a": "content"}}) 102 103 testFileContent(t, "d/a", "content") 104 } 105 106 func getWd() string { 107 dir, err := os.Getwd() 108 if err != nil { 109 panic(err) 110 } 111 dir, err = filepath.EvalSymlinks(dir) 112 if err != nil { 113 panic(err) 114 } 115 return dir 116 } 117 118 func testFileContent(t *testing.T, filename string, wantContent string) { 119 t.Helper() 120 content, err := os.ReadFile(filename) 121 if err != nil { 122 t.Errorf("Could not read %v: %v", filename, err) 123 return 124 } 125 if string(content) != wantContent { 126 t.Errorf("File %v is %q, want %q", filename, content, wantContent) 127 } 128 }