github.com/cloudberrydb/gpbackup@v1.0.3-0.20240118031043-5410fd45eed6/utils/io_test.go (about) 1 package utils_test 2 3 import ( 4 "io/ioutil" 5 "os" 6 7 "github.com/cloudberrydb/gp-common-go-libs/operating" 8 "github.com/cloudberrydb/gp-common-go-libs/testhelper" 9 "github.com/cloudberrydb/gpbackup/utils" 10 11 . "github.com/onsi/ginkgo/v2" 12 . "github.com/onsi/gomega" 13 ) 14 15 var _ = Describe("utils/io tests", func() { 16 Describe("MustPrintf", func() { 17 It("writes to a writable file", func() { 18 utils.MustPrintf(buffer, "%s", "text") 19 Expect(string(buffer.Contents())).To(Equal("text")) 20 }) 21 It("panics on error", func() { 22 defer testhelper.ShouldPanicWithMessage("write /dev/stdin:") 23 utils.MustPrintf(os.Stdin, "text") 24 }) 25 }) 26 Describe("MustPrintln", func() { 27 It("writes to a writable file", func() { 28 utils.MustPrintln(buffer, "text") 29 Expect(string(buffer.Contents())).To(Equal("text\n")) 30 }) 31 It("panics on error", func() { 32 defer testhelper.ShouldPanicWithMessage("write /dev/stdin:") 33 utils.MustPrintln(os.Stdin, "text") 34 }) 35 }) 36 Describe("Close", func() { 37 var file *utils.FileWithByteCount 38 It("does nothing if the FileWithByteCount's closer is nil", func() { 39 file = utils.NewFileWithByteCount(buffer) 40 file.Close() 41 file.MustPrintf("message") 42 }) 43 It("closes the FileWithByteCount and makes it read-only if it has a filename", func() { 44 _ = os.Remove("testfile") 45 defer os.Remove("testfile") 46 file = utils.NewFileWithByteCountFromFile("testfile") 47 file.Close() 48 defer testhelper.ShouldPanicWithMessage("write testfile: file already closed: Unable to write to file") 49 file.MustPrintf("message") 50 }) 51 }) 52 Describe("CopyFile", func() { 53 var sourceFilePath = "/tmp/test_file.txt" 54 var destFilePath = "/tmp/dest_test_file.txt" 55 56 BeforeEach(func() { 57 _ = os.Remove(sourceFilePath) 58 _ = os.Remove(destFilePath) 59 }) 60 AfterEach(func() { 61 _ = os.Remove(sourceFilePath) 62 _ = os.Remove(destFilePath) 63 }) 64 It("copies source file to dest file", func() { 65 _ = ioutil.WriteFile(sourceFilePath, []byte{1, 2, 3, 4}, 0777) 66 67 err := utils.CopyFile(sourceFilePath, destFilePath) 68 69 Expect(err).ToNot(HaveOccurred()) 70 contents, _ := ioutil.ReadFile(destFilePath) 71 Expect(contents).To(Equal([]byte{1, 2, 3, 4})) 72 }) 73 It("returns an err when cannot read source file", func() { 74 operating.System.Stat = func(f string) (os.FileInfo, error) { 75 return nil, nil 76 } 77 78 err := utils.CopyFile(sourceFilePath, destFilePath) 79 80 Expect(err).To(HaveOccurred()) 81 }) 82 It("returns an error when no source file exists", func() { 83 err := utils.CopyFile(sourceFilePath, destFilePath) 84 85 Expect(err).To(HaveOccurred()) 86 }) 87 }) 88 })