github.com/sdboyer/gps@v0.16.3/internal/fs/fs_test.go (about) 1 package fs 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "testing" 9 ) 10 11 func isDir(name string) (bool, error) { 12 fi, err := os.Stat(name) 13 if os.IsNotExist(err) { 14 return false, nil 15 } 16 if err != nil { 17 return false, err 18 } 19 if !fi.IsDir() { 20 return false, fmt.Errorf("%q is not a directory", name) 21 } 22 return true, nil 23 } 24 25 func TestCopyDir(t *testing.T) { 26 dir, err := ioutil.TempDir("", "gps") 27 if err != nil { 28 t.Fatal(err) 29 } 30 defer os.RemoveAll(dir) 31 32 srcdir := filepath.Join(dir, "src") 33 if err := os.MkdirAll(srcdir, 0755); err != nil { 34 t.Fatal(err) 35 } 36 37 srcf, err := os.Create(filepath.Join(srcdir, "myfile")) 38 if err != nil { 39 t.Fatal(err) 40 } 41 42 contents := "hello world" 43 if _, err := srcf.Write([]byte(contents)); err != nil { 44 t.Fatal(err) 45 } 46 srcf.Close() 47 48 destdir := filepath.Join(dir, "dest") 49 if err := CopyDir(srcdir, destdir); err != nil { 50 t.Fatal(err) 51 } 52 53 dirOK, err := isDir(destdir) 54 if err != nil { 55 t.Fatal(err) 56 } 57 if !dirOK { 58 t.Fatalf("expected %s to be a directory", destdir) 59 } 60 61 destf := filepath.Join(destdir, "myfile") 62 destcontents, err := ioutil.ReadFile(destf) 63 if err != nil { 64 t.Fatal(err) 65 } 66 67 if contents != string(destcontents) { 68 t.Fatalf("expected: %s, got: %s", contents, string(destcontents)) 69 } 70 71 srcinfo, err := os.Stat(srcf.Name()) 72 if err != nil { 73 t.Fatal(err) 74 } 75 76 destinfo, err := os.Stat(destf) 77 if err != nil { 78 t.Fatal(err) 79 } 80 81 if srcinfo.Mode() != destinfo.Mode() { 82 t.Fatalf("expected %s: %#v\n to be the same mode as %s: %#v", srcf.Name(), srcinfo.Mode(), destf, destinfo.Mode()) 83 } 84 } 85 86 func TestCopyFile(t *testing.T) { 87 dir, err := ioutil.TempDir("", "gps") 88 if err != nil { 89 t.Fatal(err) 90 } 91 defer os.RemoveAll(dir) 92 93 srcf, err := os.Create(filepath.Join(dir, "srcfile")) 94 if err != nil { 95 t.Fatal(err) 96 } 97 98 contents := "hello world" 99 if _, err := srcf.Write([]byte(contents)); err != nil { 100 t.Fatal(err) 101 } 102 srcf.Close() 103 104 destf := filepath.Join(dir, "destf") 105 if err := CopyFile(srcf.Name(), destf); err != nil { 106 t.Fatal(err) 107 } 108 109 destcontents, err := ioutil.ReadFile(destf) 110 if err != nil { 111 t.Fatal(err) 112 } 113 114 if contents != string(destcontents) { 115 t.Fatalf("expected: %s, got: %s", contents, string(destcontents)) 116 } 117 118 srcinfo, err := os.Stat(srcf.Name()) 119 if err != nil { 120 t.Fatal(err) 121 } 122 123 destinfo, err := os.Stat(destf) 124 if err != nil { 125 t.Fatal(err) 126 } 127 128 if srcinfo.Mode() != destinfo.Mode() { 129 t.Fatalf("expected %s: %#v\n to be the same mode as %s: %#v", srcf.Name(), srcinfo.Mode(), destf, destinfo.Mode()) 130 } 131 }