1package util_test
2
3import (
4	"os"
5
6	"code.cloudfoundry.org/credhub-cli/util"
7
8	. "github.com/onsi/ginkgo"
9	. "github.com/onsi/gomega"
10
11	"runtime"
12
13	credhub_errors "code.cloudfoundry.org/credhub-cli/errors"
14	"code.cloudfoundry.org/credhub-cli/test"
15)
16
17var _ = Describe("Util", func() {
18	Describe("#ReadFileOrStringFromField", func() {
19		Context("when the file does not exist", func() {
20			It("returns the original value", func() {
21				readContents, err := util.ReadFileOrStringFromField("Foo")
22				Expect(readContents).To(Equal("Foo"))
23				Expect(err).To(BeNil())
24			})
25
26			It("handles newlines in the value", func() {
27				readContents, err := util.ReadFileOrStringFromField(`foo\nbar`)
28				Expect(readContents).To(Equal("foo\nbar"))
29				Expect(err).To(BeNil())
30			})
31		})
32
33		Context("when the file is readable", func() {
34			It("reads a file into memory", func() {
35				tempDir := test.CreateTempDir("filesForTesting")
36				fileContents := "My Test String"
37				filename := test.CreateCredentialFile(tempDir, "file.txt", fileContents)
38				readContents, err := util.ReadFileOrStringFromField(filename)
39				Expect(readContents).To(Equal(fileContents))
40				Expect(err).To(BeNil())
41				os.RemoveAll(tempDir)
42			})
43		})
44
45		if runtime.GOOS != "windows" {
46			Context("when the file is not readable", func() {
47				It("returns an error message if a file cannot be read", func() {
48					tempDir := test.CreateTempDir("filesForTesting")
49					fileContents := "My Test String"
50					filename := test.CreateCredentialFile(tempDir, "file.txt", fileContents)
51					err := os.Chmod(filename, 0222)
52					Expect(err).To(BeNil())
53					readContents, err := util.ReadFileOrStringFromField(filename)
54					Expect(readContents).To(Equal(""))
55					Expect(err).To(MatchError(credhub_errors.NewFileLoadError()))
56				})
57			})
58		}
59	})
60
61	Describe("#AddDefaultSchemeIfNecessary", func() {
62		It("adds the default scheme (https://) to a server which has none", func() {
63			transformedUrl := util.AddDefaultSchemeIfNecessary("foo.com:8080")
64			Expect(transformedUrl).To(Equal("https://foo.com:8080"))
65		})
66
67		It("does not add the default scheme if one is already there", func() {
68			transformedUrl := util.AddDefaultSchemeIfNecessary("ftp://foo.com:8080")
69			Expect(transformedUrl).To(Equal("ftp://foo.com:8080"))
70		})
71	})
72})
73