-
Notifications
You must be signed in to change notification settings - Fork 76
/
file_writer_test.go
99 lines (77 loc) · 2.32 KB
/
file_writer_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
// Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudinit
import (
"io/fs"
"io/ioutil"
"os"
"path"
"strconv"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("FileWriter", func() {
var (
workDir string
err error
)
BeforeEach(func() {
workDir, err = ioutil.TempDir("", "file_writer_ut")
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
err := os.RemoveAll(workDir)
Expect(err).NotTo(HaveOccurred())
})
It("Should create a directory if it does not exists", func() {
err := FileWriter{}.MkdirIfNotExists(workDir)
Expect(err).NotTo(HaveOccurred())
})
It("Should not create a directory if it already exists", func() {
err := FileWriter{}.MkdirIfNotExists(workDir)
Expect(err).NotTo(HaveOccurred())
err = FileWriter{}.MkdirIfNotExists(workDir)
Expect(err).NotTo(HaveOccurred())
})
It("Should create and write to file", func() {
filePermission := 0777
file := Files{
Path: path.Join(workDir, "file1.txt"),
Encoding: "",
Owner: "",
Permissions: strconv.FormatInt(int64(filePermission), 8),
Content: "some-content",
Append: false,
}
err := FileWriter{}.MkdirIfNotExists(workDir)
Expect(err).NotTo(HaveOccurred())
err = FileWriter{}.WriteToFile(&file)
Expect(err).NotTo(HaveOccurred())
buffer, err := ioutil.ReadFile(file.Path)
Expect(err).NotTo(HaveOccurred())
Expect(string(buffer)).To(Equal(file.Content))
stats, err := os.Stat(file.Path)
Expect(err).NotTo(HaveOccurred())
Expect(stats.Mode()).To(Equal(fs.FileMode(filePermission)))
})
It("Should append content to file when append mode is enabled", func() {
fileOriginContent := "some-file-content-1"
file := Files{
Path: path.Join(workDir, "file3.txt"),
Encoding: "",
Owner: "",
Permissions: "",
Content: "some-content-2",
Append: true,
}
err := FileWriter{}.MkdirIfNotExists(workDir)
Expect(err).NotTo(HaveOccurred())
err = ioutil.WriteFile(file.Path, []byte(fileOriginContent), 0644)
Expect(err).NotTo(HaveOccurred())
err = FileWriter{}.WriteToFile(&file)
Expect(err).NotTo(HaveOccurred())
buffer, err := ioutil.ReadFile(file.Path)
Expect(err).NotTo(HaveOccurred())
Expect(string(buffer)).To(Equal(fileOriginContent + file.Content))
})
})