github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/configuration/config_disk_persistor_test.go (about) 1 package configuration_test 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "os" 7 8 . "code.cloudfoundry.org/cli/cf/configuration" 9 . "github.com/onsi/ginkgo" 10 . "github.com/onsi/gomega" 11 ) 12 13 var _ = Describe("DiskPersistor", func() { 14 var ( 15 tmpDir string 16 tmpFile *os.File 17 diskPersistor DiskPersistor 18 ) 19 20 BeforeEach(func() { 21 var err error 22 23 tmpDir = os.TempDir() 24 25 tmpFile, err = ioutil.TempFile(tmpDir, "tmp_file") 26 Expect(err).ToNot(HaveOccurred()) 27 28 diskPersistor = NewDiskPersistor(tmpFile.Name()) 29 }) 30 31 AfterEach(func() { 32 os.Remove(tmpFile.Name()) 33 }) 34 35 Describe(".Delete", func() { 36 It("Deletes the correct file", func() { 37 tmpFile.Close() 38 diskPersistor.Delete() 39 40 file, err := os.Stat(tmpFile.Name()) 41 Expect(file).To(BeNil()) 42 Expect(err).To(HaveOccurred()) 43 }) 44 }) 45 46 Describe(".Save", func() { 47 It("Writes the json file to the correct filepath", func() { 48 d := &data{Info: "save test"} 49 50 err := diskPersistor.Save(d) 51 Expect(err).ToNot(HaveOccurred()) 52 53 dataBytes, err := ioutil.ReadFile(tmpFile.Name()) 54 Expect(err).ToNot(HaveOccurred()) 55 Expect(string(dataBytes)).To(ContainSubstring(d.Info)) 56 }) 57 }) 58 59 Describe(".Load", func() { 60 It("Will load an empty json file", func() { 61 d := &data{} 62 63 err := diskPersistor.Load(d) 64 Expect(err).ToNot(HaveOccurred()) 65 Expect(d.Info).To(Equal("")) 66 }) 67 68 It("Will load a json file with specific keys", func() { 69 d := &data{} 70 71 err := ioutil.WriteFile(tmpFile.Name(), []byte(`{"Info":"test string"}`), 0700) 72 Expect(err).ToNot(HaveOccurred()) 73 74 err = diskPersistor.Load(d) 75 Expect(err).ToNot(HaveOccurred()) 76 Expect(d.Info).To(Equal("test string")) 77 }) 78 }) 79 }) 80 81 type data struct { 82 Info string 83 } 84 85 func (d *data) JSONMarshalV3() ([]byte, error) { 86 return json.MarshalIndent(d, "", " ") 87 } 88 89 func (d *data) JSONUnmarshalV3(data []byte) error { 90 return json.Unmarshal(data, d) 91 }