Skip to content

Commit 4becd8b

Browse files
committed
Refactored file-generation_test.go to improve & add tests for directory creation & file writing scenarios
Signed-off-by: Alokzh <zhalok24@gmail.com>
1 parent ce1440f commit 4becd8b

1 file changed

Lines changed: 130 additions & 135 deletions

File tree

util/file-generation_test.go

Lines changed: 130 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -1,201 +1,196 @@
11
package util
22

33
import (
4+
"errors"
45
"os"
5-
"path/filepath"
66
"testing"
7+
8+
"github.com/stretchr/testify/assert"
9+
"github.com/stretchr/testify/require"
710
)
811

912
func TestCreateDirectoryPath(t *testing.T) {
10-
t.Parallel()
11-
12-
testDir := filepath.Join(os.TempDir(), "kubeslice-test-"+t.Name())
13-
t.Cleanup(func() {
14-
os.RemoveAll(testDir)
15-
})
16-
1713
tests := []struct {
18-
name string
19-
path string
14+
name string
15+
path string
16+
statErr error
17+
mkdirErr error
18+
expectFatal bool
19+
fatalContains string
2020
}{
2121
{
22-
name: "Create simple directory",
23-
path: "simple-dir",
22+
name: "directory already exists",
23+
path: "/existing/path",
24+
statErr: nil,
25+
},
26+
{
27+
name: "directory does not exist - creates successfully",
28+
path: "/new/path",
29+
statErr: os.ErrNotExist,
2430
},
2531
{
26-
name: "Create nested directories",
27-
path: filepath.Join("nested", "deep", "deeper", "deepest"),
32+
name: "mkdir fails - permission denied",
33+
path: "/restricted/path",
34+
statErr: os.ErrNotExist,
35+
mkdirErr: os.ErrPermission,
36+
expectFatal: true,
37+
fatalContains: "Failed to create kubeslice directory",
2838
},
2939
{
30-
name: "Create directory with special characters",
31-
path: "special-chars-dir_123",
40+
name: "mkdir fails - disk full",
41+
path: "/new/path",
42+
statErr: os.ErrNotExist,
43+
mkdirErr: errors.New("no space left on device"),
44+
expectFatal: true,
45+
fatalContains: "Failed to create kubeslice directory",
3246
},
3347
{
34-
name: "Handle directory that already exists",
35-
path: "existing-dir",
48+
name: "stat returns non-ErrNotExist error - no mkdir attempted",
49+
path: "/some/path",
50+
statErr: errors.New("disk error"),
3651
},
3752
}
3853

39-
for _, tc := range tests {
40-
tc := tc // Capture range variable for parallel execution
41-
t.Run(tc.name, func(t *testing.T) {
42-
t.Parallel()
54+
for _, tt := range tests {
55+
t.Run(tt.name, func(t *testing.T) {
56+
cleanup := NewTestEnvironment()
4357

44-
targetPath := filepath.Join(testDir, tc.path)
58+
fakeFS := FileSystem.(*FakeFileSystem)
59+
fakeOutput := Output.(*FakeOutput)
4560

46-
if tc.name == "Handle directory that already exists" {
47-
if err := os.MkdirAll(targetPath, os.ModePerm); err != nil {
48-
t.Fatalf("Failed to setup test: %v", err)
49-
}
61+
mkdirCalled := false
62+
fakeFS.StatFunc = func(name string) (os.FileInfo, error) {
63+
assert.Equal(t, tt.path, name)
64+
return nil, tt.statErr
65+
}
66+
67+
fakeFS.MkdirAllFunc = func(path string, perm os.FileMode) error {
68+
mkdirCalled = true
69+
assert.Equal(t, tt.path, path)
70+
assert.Equal(t, os.ModePerm, perm)
71+
return tt.mkdirErr
5072
}
5173

52-
CreateDirectoryPath(targetPath)
74+
CreateDirectoryPath(tt.path)
5375

54-
info, err := os.Stat(targetPath)
55-
if err != nil {
56-
t.Errorf("CreateDirectoryPath() failed to create directory: %v", err)
57-
return
76+
if tt.expectFatal {
77+
require.NotEmpty(t, fakeOutput.FatalCalls, "Expected Fatalf to be called")
78+
assert.Contains(t, fakeOutput.FatalCalls[0], tt.fatalContains)
79+
} else {
80+
assert.Empty(t, fakeOutput.FatalCalls, "Did not expect Fatalf to be called")
5881
}
59-
if !info.IsDir() {
60-
t.Errorf("CreateDirectoryPath() created a file instead of directory")
82+
83+
if tt.statErr == os.ErrNotExist {
84+
assert.True(t, mkdirCalled, "Expected MkdirAll to be called")
85+
} else if tt.statErr != nil {
86+
assert.False(t, mkdirCalled, "Did not expect MkdirAll to be called when Stat returns non-ErrNotExist error")
6187
}
88+
89+
cleanup()
6290
})
6391
}
6492
}
6593

6694
func TestDumpFile(t *testing.T) {
67-
t.Parallel()
68-
69-
testDir := filepath.Join(os.TempDir(), "kubeslice-test-"+t.Name())
70-
if err := os.MkdirAll(testDir, os.ModePerm); err != nil {
71-
t.Fatalf("Failed to create test directory: %v", err)
72-
}
73-
t.Cleanup(func() {
74-
os.RemoveAll(testDir)
75-
})
76-
7795
tests := []struct {
78-
name string
79-
content string
80-
filename string
96+
name string
97+
template string
98+
filename string
99+
writeErr error
100+
expectFatal bool
101+
fatalContains string
81102
}{
82103
{
83-
name: "Write simple text file",
84-
content: "Hello, World!",
85-
filename: "test-simple.txt",
104+
name: "writes simple text successfully",
105+
template: "Hello, World!",
106+
filename: "/test/file.txt",
86107
},
87108
{
88-
name: "Write multi-line content",
89-
content: `Line 1
90-
Line 2
91-
Line 3`,
92-
filename: "test-multiline.txt",
93-
},
94-
{
95-
name: "Write YAML content",
96-
content: `apiVersion: v1
109+
name: "writes multi-line YAML successfully",
110+
template: `apiVersion: v1
97111
kind: ConfigMap
98112
metadata:
99-
name: test-config
100-
data:
101-
key1: value1
102-
key2: value2`,
103-
filename: "test-config.yaml",
113+
name: test-config`,
114+
filename: "/test/config.yaml",
104115
},
105116
{
106-
name: "Write empty content",
107-
content: "",
108-
filename: "test-empty.txt",
117+
name: "writes empty content successfully",
118+
template: "",
119+
filename: "/test/empty.txt",
109120
},
110121
{
111-
name: "Write JSON content",
112-
content: `{
122+
name: "writes JSON content successfully",
123+
template: `{
113124
"name": "test",
114-
"version": "1.0.0",
115-
"description": "test file"
125+
"version": "1.0.0"
116126
}`,
117-
filename: "test-config.json",
127+
filename: "/test/config.json",
128+
},
129+
{
130+
name: "writes content with special characters",
131+
template: "Special: @#$%^&*()_+-=[]{}|;':\",./<>?",
132+
filename: "/test/special.txt",
118133
},
119134
{
120-
name: "Overwrite existing file",
121-
content: "New content",
122-
filename: "test-overwrite.txt",
135+
name: "write fails - permission denied",
136+
template: "test content",
137+
filename: "/restricted/file.txt",
138+
writeErr: os.ErrPermission,
139+
expectFatal: true,
140+
fatalContains: "Failed to write /restricted/file.txt",
123141
},
124142
{
125-
name: "Write to nested directory",
126-
content: "Nested content",
127-
filename: filepath.Join("nested", "dir", "test-nested.txt"),
143+
name: "write fails - disk full",
144+
template: "test content",
145+
filename: "/test/file.txt",
146+
writeErr: errors.New("no space left on device"),
147+
expectFatal: true,
148+
fatalContains: "Failed to write",
128149
},
129150
{
130-
name: "Write file with special characters in content",
131-
content: "Special chars: @#$%^&*()_+-=[]{}|;':\",./<>?",
132-
filename: "test-special-chars.txt",
151+
name: "write fails - invalid path",
152+
template: "test content",
153+
filename: "/invalid\x00path/file.txt",
154+
writeErr: errors.New("invalid argument"),
155+
expectFatal: true,
156+
fatalContains: "Failed to write",
133157
},
134158
}
135159

136-
for _, tc := range tests {
137-
tc := tc // Capture range variable for parallel execution
138-
t.Run(tc.name, func(t *testing.T) {
139-
t.Parallel()
160+
for _, tt := range tests {
161+
t.Run(tt.name, func(t *testing.T) {
162+
cleanup := NewTestEnvironment()
140163

141-
targetFile := filepath.Join(testDir, tc.filename)
164+
fakeFS := FileSystem.(*FakeFileSystem)
165+
fakeOutput := Output.(*FakeOutput)
142166

143-
if tc.name == "Overwrite existing file" {
144-
if err := os.MkdirAll(filepath.Dir(targetFile), os.ModePerm); err != nil {
145-
t.Fatalf("Failed to create directory: %v", err)
146-
}
147-
if err := os.WriteFile(targetFile, []byte("Old content"), 0644); err != nil {
148-
t.Fatalf("Failed to setup test: %v", err)
149-
}
150-
}
167+
fakeFS.WriteFileFunc = func(filename string, data []byte, perm os.FileMode) error {
168+
assert.Equal(t, tt.filename, filename)
169+
assert.Equal(t, []byte(tt.template), data)
170+
assert.Equal(t, os.FileMode(0644), perm)
151171

152-
if tc.name == "Write to nested directory" {
153-
if err := os.MkdirAll(filepath.Dir(targetFile), os.ModePerm); err != nil {
154-
t.Fatalf("Failed to create nested directory: %v", err)
172+
if tt.writeErr != nil {
173+
return tt.writeErr
155174
}
156-
}
157-
158-
DumpFile(tc.content, targetFile)
159175

160-
actualContent, err := os.ReadFile(targetFile)
161-
if err != nil {
162-
t.Errorf("DumpFile() failed to create file: %v", err)
163-
return
164-
}
165-
if string(actualContent) != tc.content {
166-
t.Errorf("DumpFile() content mismatch\nwant: %q\ngot: %q", tc.content, string(actualContent))
176+
fakeFS.WrittenFiles[filename] = data
177+
return nil
167178
}
168179

169-
info, err := os.Stat(targetFile)
170-
if err == nil && info.IsDir() {
171-
t.Errorf("DumpFile() created a directory instead of a file")
172-
}
173-
})
174-
}
175-
}
176-
177-
func TestDumpFile_CreatesFileWithCorrectPermissions(t *testing.T) {
178-
t.Parallel()
179-
180-
testDir := filepath.Join(os.TempDir(), "kubeslice-test-"+t.Name())
181-
if err := os.MkdirAll(testDir, os.ModePerm); err != nil {
182-
t.Fatalf("Failed to create test directory: %v", err)
183-
}
184-
t.Cleanup(func() {
185-
os.RemoveAll(testDir)
186-
})
180+
DumpFile(tt.template, tt.filename)
187181

188-
targetFile := filepath.Join(testDir, "test-permissions.txt")
182+
if tt.expectFatal {
183+
require.NotEmpty(t, fakeOutput.FatalCalls, "Expected Fatalf to be called")
184+
assert.Contains(t, fakeOutput.FatalCalls[0], tt.fatalContains)
185+
} else {
186+
assert.Empty(t, fakeOutput.FatalCalls, "Did not expect Fatalf to be called")
189187

190-
DumpFile("test content", targetFile)
191-
192-
info, err := os.Stat(targetFile)
193-
if err != nil {
194-
t.Fatalf("Failed to stat file: %v", err)
195-
}
188+
content, exists := fakeFS.WrittenFiles[tt.filename]
189+
require.True(t, exists, "File should have been written")
190+
assert.Equal(t, tt.template, string(content))
191+
}
196192

197-
mode := info.Mode()
198-
if mode&0600 == 0 {
199-
t.Errorf("File should be readable and writable by owner, got mode: %v", mode)
193+
cleanup()
194+
})
200195
}
201196
}

0 commit comments

Comments
 (0)