-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils_test.go
More file actions
510 lines (409 loc) · 12.5 KB
/
utils_test.go
File metadata and controls
510 lines (409 loc) · 12.5 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
package utils_test
import (
"io"
"net"
"os"
"path/filepath"
"regexp"
"testing"
"github.com/CodeLieutenant/utils"
"github.com/stretchr/testify/require"
)
func TestCreateLogFile(t *testing.T) {
t.Parallel()
req := require.New(t)
path := "./test-logs/log.json"
file, err := utils.CreateLogFile(path)
t.Cleanup(func() {
if file != nil {
_ = file.Close()
}
_ = os.RemoveAll("./test-logs")
})
req.NoError(err)
req.NotNil(file)
req.FileExists(path)
}
func TestFileExistsSuccess(t *testing.T) {
// Arrange
t.Parallel()
req := require.New(t)
path := "./log.json"
file, err := utils.CreateLogFile(path)
t.Cleanup(func() {
if file != nil {
_ = file.Close()
}
_ = os.Remove(path)
})
// Act
exists := utils.FileExists(path)
// Assert
req.NoError(err)
req.NotNil(file)
req.True(exists)
}
func TestFileExistsNoFile(t *testing.T) {
// Arrange
t.Parallel()
req := require.New(t)
path := "./file-does-not-exist.json"
// Act
exists := utils.FileExists(path)
// Assert
req.False(exists)
}
func TestCreateDirectory(t *testing.T) {
t.Parallel()
req := require.New(t)
testDir := filepath.Join(t.TempDir(), "test-dir")
path, err := utils.CreateDirectory(testDir, 0o744)
req.NoError(err)
req.Equal(testDir, path)
req.DirExists(testDir)
}
func TestGetAbsolutePath_RelativeAbsoluteAndError(t *testing.T) {
// This test changes the working directory; do not run in parallel.
req := require.New(t)
origWD, err := os.Getwd()
req.NoError(err)
t.Cleanup(func() { t.Chdir(origWD) })
tmp := t.TempDir()
t.Chdir(tmp)
rel := "sub/dir/file.txt"
got, err := utils.GetAbsolutePath(rel)
req.NoError(err)
req.True(filepath.IsAbs(got))
req.Equal(filepath.Join(tmp, rel), got)
// Absolute path should be returned as-is
got2, err := utils.GetAbsolutePath(tmp)
req.NoError(err)
req.Equal(tmp, got2)
t.Chdir(tmp)
req.NoError(os.RemoveAll(tmp))
_, err = utils.GetAbsolutePath("anything")
req.Error(err)
}
func TestCreateDirectoryFromFile_SuccessAndError(t *testing.T) {
// Not parallel due to working directory manipulation
req := require.New(t)
origWD, err := os.Getwd()
req.NoError(err)
defer func() { _ = os.Chdir(origWD) }()
tmp, err := os.MkdirTemp("", "cdf-*")
req.NoError(err)
defer func() { _ = os.RemoveAll(tmp) }()
p := filepath.Join(tmp, "nested", "file.log")
ret, err := utils.CreateDirectoryFromFile(p, 0o755)
req.NoError(err)
req.Equal(p, ret)
req.DirExists(filepath.Dir(p))
// Error path via invalid CWD
req.NoError(os.Chdir(tmp))
req.NoError(os.RemoveAll(tmp))
_, err = utils.CreateDirectoryFromFile("file.txt", 0o755)
req.Error(err)
// Restore
req.NoError(os.Chdir(origWD))
}
func TestCreateFile_CreateReopenAndError(t *testing.T) {
// Not parallel due to CWD manipulation
req := require.New(t)
origWD, err := os.Getwd()
req.NoError(err)
defer func() { _ = os.Chdir(origWD) }()
tmp, err := os.MkdirTemp("", "cf-*")
req.NoError(err)
defer func() {
_ = os.RemoveAll(tmp)
}()
p := filepath.Join(tmp, "logs", "app.log")
f, err := utils.CreateFile(p, os.O_WRONLY|os.O_APPEND, 0o755, 0o644)
req.NoError(err)
req.NotNil(f)
_, _ = f.WriteString("hello")
req.NoError(f.Close())
// Re-open existing file with read-only
f2, err := utils.CreateFile(p, os.O_RDONLY, 0o755, 0o644)
req.NoError(err)
defer func() { _ = f2.Close() }()
b, err := io.ReadAll(f2)
req.NoError(err)
req.Equal("hello", string(b))
req.NoError(f2.Close())
// Error path via invalid CWD so CreateDirectoryFromFile fails
req.NoError(os.Chdir(tmp))
req.NoError(os.RemoveAll(tmp))
_, err = utils.CreateFile("rel.log", os.O_RDONLY, 0o755, 0o644)
req.Error(err)
// Restore
req.NoError(os.Chdir(origWD)) //nolint:usetesting
}
func TestGenerateRandomPassword(t *testing.T) {
t.Parallel()
req := require.New(t)
// Length below minimum defaults to 12
pw, err := utils.GenerateRandomPassword(6)
req.NoError(err)
req.Len(pw, 12)
// Should contain at least one from each set and be random-ish
lower := regexp.MustCompile(`[a-z]`)
upper := regexp.MustCompile(`[A-Z]`)
digit := regexp.MustCompile(`[0-9]`)
special := regexp.MustCompile(`[!@#$%^&*()\-_=+\[\]{}|;:,.<>?]`)
req.True(lower.MatchString(pw))
req.True(upper.MatchString(pw))
req.True(digit.MatchString(pw))
req.True(special.MatchString(pw))
// Another length
pw2, err := utils.GenerateRandomPassword(20)
req.NoError(err)
req.Len(pw2, 20)
req.NotEqual(pw, pw2)
}
func TestUnsafeConversions(t *testing.T) {
// Safe to run in parallel
t.Parallel()
req := require.New(t)
orig := "Hello, 世界!"
b := utils.UnsafeBytes(orig)
req.Equal(len(orig), len(b))
back := utils.UnsafeString(b)
req.Equal(orig, back)
}
func TestWorkingDir(t *testing.T) {
// Cannot run in parallel - depends on stable working directory
req := require.New(t)
wd := utils.WorkingDir(t)
req.NotEmpty(wd)
req.Equal(wd, utils.WorkingDir(t))
}
func TestProjectRootDirAndCache(t *testing.T) {
// Cannot run in parallel - depends on stable working directory
req := require.New(t)
root1 := utils.ProjectRootDir(t)
req.NotEmpty(root1)
// Second call should hit cache path
root2 := utils.ProjectRootDir(t)
req.Equal(root1, root2)
}
func TestFindFileGoMod(t *testing.T) {
// Cannot run in parallel - depends on stable working directory
req := require.New(t)
// First, ensure we can find the project root
root := utils.ProjectRootDir(t)
req.NotEmpty(root)
// Verify go.mod exists in the root directory
goModPath := filepath.Join(root, "go.mod")
req.FileExists(goModPath)
// Now test FindFile for go.mod
dir := utils.FindFile(t, "go.mod")
req.Equal(root, dir)
}
func TestFindFile_CurrentDirHit(t *testing.T) {
// Not parallel as we create/remove a file in the package dir
req := require.New(t)
wd := utils.WorkingDir(t)
tmpFile := filepath.Join(wd, "__tmp_test_marker__")
f, err := os.Create(tmpFile)
req.NoError(err)
_ = f.Close()
t.Cleanup(func() { _ = os.Remove(tmpFile) })
dir := utils.FindFile(t, filepath.Base(tmpFile))
req.Equal(wd, dir)
}
func TestGenerateRandomPassword_ErrorHandling(t *testing.T) {
t.Parallel()
req := require.New(t)
// Test with very short length (should default to 12)
pw, err := utils.GenerateRandomPassword(1)
req.NoError(err)
req.Len(pw, 12)
// Test with 0 length (should default to 12)
pw, err = utils.GenerateRandomPassword(0)
req.NoError(err)
req.Len(pw, 12)
// Test with negative length (should default to 12)
pw, err = utils.GenerateRandomPassword(-5)
req.NoError(err)
req.Len(pw, 12)
// Test with exact minimum length
pw, err = utils.GenerateRandomPassword(8)
req.NoError(err)
req.Len(pw, 8)
}
func TestCreateDirectory_ErrorCases(t *testing.T) {
t.Parallel()
req := require.New(t)
// Test with invalid path characters (this might not fail on all systems)
// but we can test basic functionality
tmp, err := os.MkdirTemp("", "test-create-dir-*")
req.NoError(err)
defer func() { _ = os.RemoveAll(tmp) }()
// Test creating nested directories
nestedPath := filepath.Join(tmp, "level1", "level2", "level3")
created, err := utils.CreateDirectory(nestedPath, 0o755)
req.NoError(err)
req.Equal(nestedPath, created)
req.DirExists(nestedPath)
// Test creating directory that already exists
created2, err := utils.CreateDirectory(nestedPath, 0o755)
req.NoError(err)
req.Equal(nestedPath, created2)
}
func TestCreateFile_ErrorCases(t *testing.T) {
req := require.New(t)
tmp, err := os.MkdirTemp("", "test-create-file-*")
req.NoError(err)
defer func() { _ = os.RemoveAll(tmp) }()
// Test creating file with non-existent parent directories
filePath := filepath.Join(tmp, "deep", "nested", "path", "file.txt")
file, err := utils.CreateFile(filePath, os.O_RDWR|os.O_CREATE, 0o755, 0o644)
req.NoError(err)
req.NotNil(file)
_ = file.Close()
req.FileExists(filePath)
// Test opening existing file with different flags
file2, err := utils.CreateFile(filePath, os.O_RDONLY, 0o755, 0o644)
req.NoError(err)
req.NotNil(file2)
_ = file2.Close()
// Test with write-only flag
file3, err := utils.CreateFile(filePath, os.O_WRONLY, 0o755, 0o644)
req.NoError(err)
req.NotNil(file3)
_ = file3.Close()
}
func TestCreateDirectoryFromFile_EdgeCases(t *testing.T) {
t.Parallel()
req := require.New(t)
tmp, err := os.MkdirTemp("", "test-create-dir-from-file-*")
req.NoError(err)
defer func() { _ = os.RemoveAll(tmp) }()
// Test with file path that has multiple levels
filePath := filepath.Join(tmp, "a", "b", "c", "d", "file.log")
created, err := utils.CreateDirectoryFromFile(filePath, 0o755)
req.NoError(err)
req.Equal(filePath, created)
req.DirExists(filepath.Dir(filePath))
// Test with relative path
origWD, err := os.Getwd()
req.NoError(err)
defer func() { _ = os.Chdir(origWD) }()
req.NoError(os.Chdir(tmp))
relativeFile := "relative/path/file.txt"
created2, err := utils.CreateDirectoryFromFile(relativeFile, 0o755)
req.NoError(err)
req.True(filepath.IsAbs(created2))
req.DirExists(filepath.Dir(created2))
}
func TestWorkingDir_ErrorHandling(t *testing.T) {
// This test needs to be run in isolation as it manipulates the working directory
req := require.New(t)
// Create a temporary directory
tmp, err := os.MkdirTemp("", "test-working-dir-*")
req.NoError(err)
defer func() { _ = os.RemoveAll(tmp) }()
// Change to the temporary directory
origWD, err := os.Getwd()
req.NoError(err)
defer func() { _ = os.Chdir(origWD) }()
req.NoError(os.Chdir(tmp))
// Get working directory (should work)
wd := utils.WorkingDir(t)
req.Equal(tmp, wd)
}
// Test that demonstrates the GetLocalIP and GetLocalIPs error handling
func TestGetLocalIP_ErrorPath(t *testing.T) {
t.Parallel()
// This test is tricky because we can't easily mock net.InterfaceAddrs()
// But we can test the current behavior
req := require.New(t)
ip := utils.GetLocalIP()
// Should either be empty (if no interfaces) or a valid IP
if ip != "" {
parsedIP := net.ParseIP(ip)
req.NotNil(parsedIP)
req.True(parsedIP.To4() != nil) // Should be IPv4
}
}
func TestGetLocalIPs_ErrorPath(t *testing.T) {
t.Parallel()
req := require.New(t)
ips := utils.GetLocalIPs()
// Should either be nil/empty (if no interfaces) or contain valid IPs
for _, ip := range ips {
parsedIP := net.ParseIP(ip)
req.NotNil(parsedIP)
req.True(parsedIP.To4() != nil) // Should be IPv4
}
}
// Additional edge case tests for better coverage
func TestCreateFile_StatError(t *testing.T) {
t.Parallel()
req := require.New(t)
tmp, err := os.MkdirTemp("", "test-create-file-stat-*")
req.NoError(err)
defer func() { _ = os.RemoveAll(tmp) }()
// Test creating a file that doesn't exist yet
filePath := filepath.Join(tmp, "new-file.txt")
file, err := utils.CreateFile(filePath, os.O_RDWR|os.O_CREATE, 0o755, 0o644)
req.NoError(err)
req.NotNil(file)
_ = file.Close()
// Test opening the same file again (should not recreate)
file2, err := utils.CreateFile(filePath, os.O_RDWR, 0o755, 0o644)
req.NoError(err)
req.NotNil(file2)
_ = file2.Close()
}
func TestGenerateRandomPassword_LengthEdgeCases(t *testing.T) {
t.Parallel()
req := require.New(t)
// Test various lengths to ensure we hit all code paths
testCases := []int{4, 7, 8, 12, 16, 32, 100}
for _, length := range testCases {
pw, err := utils.GenerateRandomPassword(length)
req.NoError(err)
expectedLength := length
if length < 8 {
expectedLength = 12 // Default minimum
}
req.Len(pw, expectedLength)
// Verify password contains at least one character from each set for longer passwords
if expectedLength >= 8 {
req.Regexp(`[a-z]`, pw) // lowercase
req.Regexp(`[A-Z]`, pw) // uppercase
req.Regexp(`[0-9]`, pw) // numbers
req.Regexp(`[!@#$%^&*()\-_=+\[\]{}|;:,.<>?]`, pw) // special chars
}
}
}
func TestFindFile_ReadDirError(t *testing.T) {
// This test checks that FindFile works correctly when searching
// for a file that exists in a parent directory
req := require.New(t)
// Save original working directory
origWD, err := os.Getwd()
req.NoError(err)
defer func() { _ = os.Chdir(origWD) }()
projectRoot := utils.ProjectRootDir(t)
// Create a temporary subdirectory
subDir := filepath.Join(projectRoot, "temp-test-subdir")
req.NoError(os.MkdirAll(subDir, 0o755))
defer func() { _ = os.RemoveAll(subDir) }()
// Change to the subdirectory
req.NoError(os.Chdir(subDir))
// Find go.mod which should be in the parent directory
found := utils.FindFile(t, "go.mod")
req.Equal(projectRoot, found)
}
func TestWorkingDir_Success(t *testing.T) {
t.Parallel()
req := require.New(t)
wd1 := utils.WorkingDir(t)
wd2 := utils.WorkingDir(t)
req.Equal(wd1, wd2)
req.NotEmpty(wd1)
req.True(filepath.IsAbs(wd1))
}