-
Notifications
You must be signed in to change notification settings - Fork 31
/
json_test.go
105 lines (90 loc) · 2.61 KB
/
json_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package libbuildpack_test
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/cloudfoundry/libbuildpack"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("JSON", func() {
var (
json *libbuildpack.JSON
tmpDir string
err error
)
BeforeEach(func() {
tmpDir, err = ioutil.TempDir("", "json")
Expect(err).To(BeNil())
json = &libbuildpack.JSON{}
})
AfterEach(func() {
err = os.RemoveAll(tmpDir)
Expect(err).To(BeNil())
})
Describe("Load", func() {
Context("file is valid json", func() {
Context("that starts with BOM", func() {
BeforeEach(func() {
ioutil.WriteFile(filepath.Join(tmpDir, "valid.json"), []byte("\uFEFF"+`{"key": "value"}`), 0666)
})
It("returns an error", func() {
obj := make(map[string]string)
err = json.Load(filepath.Join(tmpDir, "valid.json"), &obj)
Expect(err).To(BeNil())
Expect(obj["key"]).To(Equal("value"))
})
})
Context("that does not start with BOM", func() {
BeforeEach(func() {
ioutil.WriteFile(filepath.Join(tmpDir, "valid.json"), []byte(`{"key": "value"}`), 0666)
})
It("returns an error", func() {
obj := make(map[string]string)
err = json.Load(filepath.Join(tmpDir, "valid.json"), &obj)
Expect(err).To(BeNil())
Expect(obj["key"]).To(Equal("value"))
})
})
})
Context("file is NOT valid json", func() {
BeforeEach(func() {
ioutil.WriteFile(filepath.Join(tmpDir, "invalid.json"), []byte("not valid json"), 0666)
})
It("returns an error", func() {
obj := make(map[string]string)
err = json.Load(filepath.Join(tmpDir, "invalid.json"), &obj)
Expect(err).ToNot(BeNil())
})
})
Context("file does not exist", func() {
It("returns an error", func() {
obj := make(map[string]string)
err = json.Load(filepath.Join(tmpDir, "does_not_exist.json"), &obj)
Expect(err).ToNot(BeNil())
})
})
})
Describe("Write", func() {
Context("directory exists", func() {
It("writes the json to a file ", func() {
obj := map[string]string{
"key": "val",
}
err = json.Write(filepath.Join(tmpDir, "file.json"), obj)
Expect(err).To(BeNil())
Expect(ioutil.ReadFile(filepath.Join(tmpDir, "file.json"))).To(Equal([]byte(`{"key":"val"}`)))
})
})
Context("directory does not exist", func() {
It("creates the directory", func() {
obj := map[string]string{
"key": "val",
}
err = json.Write(filepath.Join(tmpDir, "extradir", "file.json"), obj)
Expect(err).To(BeNil())
Expect(ioutil.ReadFile(filepath.Join(tmpDir, "extradir", "file.json"))).To(Equal([]byte(`{"key":"val"}`)))
})
})
})
})