github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/util/file_test.go (about) 1 package util 2 3 import ( 4 "github.com/stretchr/testify/assert" 5 "os" 6 "path/filepath" 7 "testing" 8 ) 9 10 func TestPathExist(t *testing.T) { 11 path, err := filepath.Abs(filepath.Join("/tmp", "path", "lotusdb-1")) 12 assert.Nil(t, err) 13 path2, err := filepath.Abs(filepath.Join("/tmp", "path", "lotusdb-2")) 14 assert.Nil(t, err) 15 16 err = os.MkdirAll(path, os.ModePerm) 17 assert.Nil(t, err) 18 defer func() { 19 err := os.RemoveAll(filepath.Join("/tmp", "path")) 20 assert.Nil(t, err) 21 }() 22 23 existedFile, err := filepath.Abs(filepath.Join("/tmp", "path", "lotusdb-file1")) 24 assert.Nil(t, err) 25 noExistedFile, err := filepath.Abs(filepath.Join("/tmp", "path", "lotusdb-file2")) 26 assert.Nil(t, err) 27 f, err := os.OpenFile(existedFile, os.O_CREATE, 0644) 28 assert.Nil(t, err) 29 defer func() { 30 _ = f.Close() 31 }() 32 33 type args struct { 34 path string 35 } 36 tests := []struct { 37 name string 38 args args 39 want bool 40 }{ 41 { 42 "path exist", args{path: path}, true, 43 }, 44 { 45 "path not exist", args{path: path2}, false, 46 }, 47 { 48 "file exist", args{path: existedFile}, true, 49 }, 50 { 51 "file not exist", args{path: noExistedFile}, false, 52 }, 53 } 54 55 for _, tt := range tests { 56 t.Run(tt.name, func(t *testing.T) { 57 if got := PathExist(tt.args.path); got != tt.want { 58 t.Errorf("PathExist() = %v, want %v", got, tt.want) 59 } 60 }) 61 } 62 } 63 64 func TestCopyDir(t *testing.T) { 65 path, err := filepath.Abs(filepath.Join("/tmp", "test-copy-path")) 66 assert.Nil(t, err) 67 destPath, err := filepath.Abs(filepath.Join("/tmp", "test-copy-path-dest")) 68 assert.Nil(t, err) 69 70 subpath1 := path + string(os.PathSeparator) + "sub1" 71 subpath2 := path + string(os.PathSeparator) + "sub2" 72 subFile := path + string(os.PathSeparator) + "sub-file" 73 74 err = os.MkdirAll(subpath1, os.ModePerm) 75 assert.Nil(t, err) 76 err = os.MkdirAll(subpath2, os.ModePerm) 77 assert.Nil(t, err) 78 f, err := os.OpenFile(subFile, os.O_CREATE, os.ModePerm) 79 assert.Nil(t, err) 80 defer func() { 81 _ = f.Close() 82 _ = os.RemoveAll(path) 83 _ = os.RemoveAll(destPath) 84 }() 85 86 err = CopyDir(path, destPath) 87 assert.Nil(t, err) 88 } 89 90 func TestCopyFile(t *testing.T) { 91 path := filepath.Join("/tmp", "path", "lotusdb-1") 92 err := os.MkdirAll(path, os.ModePerm) 93 assert.Nil(t, err) 94 defer func() { 95 _ = os.RemoveAll(filepath.Join("/tmp", "path")) 96 }() 97 98 file := filepath.Join(path, "001.vlog") 99 f, err := os.OpenFile(file, os.O_CREATE, 0644) 100 assert.Nil(t, err) 101 102 err = CopyFile(file, path+"/001.vlog-bak") 103 assert.Nil(t, err) 104 105 _ = f.Close() 106 }