Repository navigation
Expand file tree
/
Copy pathfileutils_test.go
More file actions
532 lines (433 loc) · 15.6 KB
/
Copy pathfileutils_test.go
File metadata and controls
532 lines (433 loc) · 15.6 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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
package fileutils
import (
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/go-pkgz/fileutils/enum"
)
func TestExistsFile(t *testing.T) {
assert.True(t, IsFile("testfiles/file1.txt"))
assert.False(t, IsFile("testfiles/file-not-found.txt"))
assert.False(t, IsFile(""))
assert.False(t, IsFile(".."))
assert.False(t, IsFile("testfiles"))
}
func TestExistsDir(t *testing.T) {
assert.True(t, IsDir("testfiles"))
assert.False(t, IsDir("testfiles/file1.txt"))
assert.False(t, IsDir(""))
assert.True(t, IsDir(".."))
assert.True(t, IsDir("."))
assert.False(t, IsDir("testfiles-nop"))
}
func TestExistsStatError(t *testing.T) {
t.Run("invalid path", func(t *testing.T) {
invalidPath := "invalid\x00path"
_, err := os.Stat(invalidPath)
require.Error(t, err)
require.False(t, os.IsNotExist(err), "this path must produce a stat error other than not-exist")
assert.False(t, IsFile(invalidPath))
assert.False(t, IsDir(invalidPath))
})
t.Run("unreadable parent directory", func(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root bypasses directory permissions")
}
locked := filepath.Join(t.TempDir(), "locked")
require.NoError(t, os.Mkdir(locked, 0o700))
target := filepath.Join(locked, "file.txt")
require.NoError(t, os.WriteFile(target, []byte("test content"), 0o600))
require.NoError(t, os.Chmod(locked, 0o000))
t.Cleanup(func() { _ = os.Chmod(locked, 0o700) })
_, err := os.Stat(target)
require.Error(t, err)
require.False(t, os.IsNotExist(err), "this path must produce a permission error, not not-exist")
assert.False(t, IsFile(target))
assert.False(t, IsDir(target))
})
}
func TestCopyFile(t *testing.T) {
tmpDir := t.TempDir()
// create source file with specific mode
srcFile := filepath.Join(tmpDir, "src.txt")
err := os.WriteFile(srcFile, []byte("test content"), 0o600)
require.NoError(t, err)
// get source info for comparison
srcInfo, err := os.Stat(srcFile)
require.NoError(t, err)
// copy file
dstFile := filepath.Join(tmpDir, "dst.txt")
err = CopyFile(srcFile, dstFile)
require.NoError(t, err)
// verify content
content, err := os.ReadFile(dstFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
// verify mode
dstInfo, err := os.Stat(dstFile)
require.NoError(t, err)
assert.Equal(t, srcInfo.Mode(), dstInfo.Mode())
// verify error cases
err = CopyFile("notfound.txt", dstFile)
assert.Error(t, err)
assert.Contains(t, err.Error(), "can't stat")
err = CopyFile(srcFile, "/dev/null")
assert.Error(t, err)
}
func TestCopyFileToItself(t *testing.T) {
t.Run("same path", func(t *testing.T) {
srcFile := filepath.Join(t.TempDir(), "src.txt")
require.NoError(t, os.WriteFile(srcFile, []byte("test content"), 0o600))
err := CopyFile(srcFile, srcFile)
require.Error(t, err)
assert.Contains(t, err.Error(), "to itself")
// the source must survive intact
content, err := os.ReadFile(srcFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
})
t.Run("hard link alias", func(t *testing.T) {
tmpDir := t.TempDir()
srcFile := filepath.Join(tmpDir, "src.txt")
require.NoError(t, os.WriteFile(srcFile, []byte("test content"), 0o600))
linkFile := filepath.Join(tmpDir, "link.txt")
require.NoError(t, os.Link(srcFile, linkFile))
err := CopyFile(srcFile, linkFile)
require.Error(t, err)
assert.Contains(t, err.Error(), "to itself")
content, err := os.ReadFile(srcFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
})
t.Run("symlink alias", func(t *testing.T) {
tmpDir := t.TempDir()
srcFile := filepath.Join(tmpDir, "src.txt")
require.NoError(t, os.WriteFile(srcFile, []byte("test content"), 0o600))
linkFile := filepath.Join(tmpDir, "link.txt")
require.NoError(t, os.Symlink(srcFile, linkFile))
err := CopyFile(srcFile, linkFile)
require.Error(t, err)
assert.Contains(t, err.Error(), "to itself")
content, err := os.ReadFile(srcFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
})
t.Run("copy dir onto itself", func(t *testing.T) {
tmpDir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(tmpDir, "f.txt"), []byte("test content"), 0o600))
err := CopyDir(tmpDir, tmpDir)
require.Error(t, err)
assert.Contains(t, err.Error(), "to itself")
content, err := os.ReadFile(filepath.Join(tmpDir, "f.txt")) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
})
}
func TestCopyFileOverwrite(t *testing.T) {
t.Run("replaces content and mode", func(t *testing.T) {
tmpDir := t.TempDir()
srcFile := filepath.Join(tmpDir, "src.txt")
require.NoError(t, os.WriteFile(srcFile, []byte("new"), 0o600))
// pre-existing destination, longer content and a different mode
dstFile := filepath.Join(tmpDir, "dst.txt")
require.NoError(t, os.WriteFile(dstFile, []byte("much longer old content"), 0o644))
require.NoError(t, os.Chmod(dstFile, 0o644))
require.NoError(t, CopyFile(srcFile, dstFile))
content, err := os.ReadFile(dstFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "new", string(content), "leftover bytes from the old destination")
dstInfo, err := os.Stat(dstFile)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), dstInfo.Mode().Perm())
})
t.Run("mode not filtered by umask", func(t *testing.T) {
tmpDir := t.TempDir()
srcFile := filepath.Join(tmpDir, "src.txt")
require.NoError(t, os.WriteFile(srcFile, []byte("test content"), 0o600))
require.NoError(t, os.Chmod(srcFile, 0o666))
dstFile := filepath.Join(tmpDir, "dst.txt")
require.NoError(t, CopyFile(srcFile, dstFile))
dstInfo, err := os.Stat(dstFile)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o666), dstInfo.Mode().Perm())
})
}
func TestListFiles(t *testing.T) {
list, err := ListFiles("testfiles")
require.NoError(t, err)
assert.Equal(t, []string{"testfiles/d1/d21/file21_d21.txt", "testfiles/d1/d21/file22_d21.txt",
"testfiles/d1/file1_d1.txt", "testfiles/file1.txt"}, list)
_, err = ListFiles("testfiles.bad")
assert.Error(t, err)
}
func TestCopyDir(t *testing.T) {
defer func() { _ = os.RemoveAll("/tmp/copydir.test") }()
err := CopyDir("testfiles", "/tmp/copydir.test")
require.NoError(t, err)
list, err := ListFiles("/tmp/copydir.test")
assert.NoError(t, err)
assert.Equal(t, []string{"/tmp/copydir.test/d1/d21/file21_d21.txt", "/tmp/copydir.test/d1/d21/file22_d21.txt",
"/tmp/copydir.test/d1/file1_d1.txt", "/tmp/copydir.test/file1.txt"}, list)
err = CopyDir("testfiles-no", "/tmp/copydir.test")
assert.Error(t, err)
err = CopyDir("testfiles", "/dev/null")
assert.Error(t, err)
t.Log(err)
}
func TestTempFileName(t *testing.T) {
r1, err := TempFileName("", "something-*.txt")
require.NoError(t, err)
t.Log(r1)
assert.Contains(t, r1, "something-")
assert.Contains(t, r1, ".txt")
r2, err := TempFileName("", "something-*.txt")
require.NoError(t, err)
t.Log(r2)
assert.NotEqual(t, r1, r2)
r3, err := TempFileName("somedir", "something-*.txt")
require.NoError(t, err)
t.Log(r3)
assert.True(t, strings.HasPrefix(r3, "somedir/"))
r4, err := TempFileName("somedir", "something-")
require.NoError(t, err)
t.Log(r4)
assert.True(t, strings.HasPrefix(r4, "somedir/something-"))
}
func TestSanitizePath(t *testing.T) {
tbl := []struct {
inp, out string
}{
{"aaaa", "aaaa"},
{"aaaa?bb", "aaaa_bb"},
{"aaaa/bb", "aaaa/bb"},
{"aaaa?*bb", "aaaa_bb"},
{"aa*aa?*bb", "aa_aa_bb"},
{"aa>aa<bb", "aa_aa_bb"},
{"path/to/file.txt", "path/to/file.txt"},
{" path/to/file.txt ", "path/to/file.txt"},
{"path<>to|file?.txt", "path_to_file_.txt"},
{strings.Repeat("a", maxPathLength+10), strings.Repeat("a", maxPathLength)},
{"path\\to/file.txt", "path/to/file.txt"},
{"con/nul", "con/nul"},
}
for i, tt := range tbl {
t.Run(strconv.Itoa(i), func(t *testing.T) {
assert.Equal(t, tt.out, SanitizePath(tt.inp))
})
}
}
func TestMoveFile(t *testing.T) {
t.Run("same device move", func(t *testing.T) {
// create temp source file
srcFile := filepath.Join(os.TempDir(), "move_test_src.txt")
err := os.WriteFile(srcFile, []byte("test content"), 0600)
require.NoError(t, err)
defer func() { _ = os.Remove(srcFile) }()
// create temp destination
dstFile := filepath.Join(os.TempDir(), "move_test_dst.txt")
defer func() { _ = os.Remove(dstFile) }()
// perform move
err = MoveFile(srcFile, dstFile)
require.NoError(t, err)
// verify source is gone and destination exists
_, err = os.Stat(srcFile)
assert.True(t, os.IsNotExist(err), "source file should not exist")
content, err := os.ReadFile(dstFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
})
t.Run("move into a missing directory", func(t *testing.T) {
// create source dir and file
srcDir := t.TempDir()
srcFile := filepath.Join(srcDir, "move_test_src2.txt")
err := os.WriteFile(srcFile, []byte("test content"), 0600)
require.NoError(t, err)
// create destination dir
dstDir := t.TempDir()
dstFile := filepath.Join(dstDir, "subdir", "move_test_dst.txt")
// perform move
err = MoveFile(srcFile, dstFile)
require.NoError(t, err)
// verify move succeeded
_, err = os.Stat(srcFile)
assert.True(t, os.IsNotExist(err), "source file should not exist")
content, err := os.ReadFile(dstFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
})
t.Run("copy fallback when rename fails", func(t *testing.T) {
srcFile := filepath.Join(t.TempDir(), "move_test_src3.txt")
require.NoError(t, os.WriteFile(srcFile, []byte("test content"), 0o600))
dstFile := filepath.Join(t.TempDir(), "subdir", "move_test_dst.txt")
// rename always fails, so the copy+delete path has to carry the move
renameAttempts := 0
err := moveFile(srcFile, dstFile, func(_, _ string) error {
renameAttempts++
return errors.New("forced rename failure")
})
require.NoError(t, err)
assert.Equal(t, 2, renameAttempts, "rename is retried once after the destination directory is created")
_, err = os.Stat(srcFile)
assert.True(t, os.IsNotExist(err), "source file should not exist")
content, err := os.ReadFile(dstFile) //nolint:gosec
require.NoError(t, err)
assert.Equal(t, "test content", string(content))
})
t.Run("errors", func(t *testing.T) {
tests := []struct {
name string
src string
dst string
wantErr string
}{
{
name: "source not found",
src: "notfound.txt",
dst: "dst.txt",
wantErr: "source file not found",
},
{
name: "empty source",
src: "",
dst: "dst.txt",
wantErr: "empty source path",
},
{
name: "empty destination",
src: "src.txt",
dst: "",
wantErr: "empty destination path",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := MoveFile(tt.src, tt.dst)
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
})
}
})
}
func TestTouchFile(t *testing.T) {
t.Run("create new", func(t *testing.T) {
tmpDir := t.TempDir()
newFile := filepath.Join(tmpDir, "new.txt")
// bound the modification time from below only, an upper bound would just measure the runner
before := time.Now().Add(-time.Second)
err := TouchFile(newFile)
require.NoError(t, err)
info, err := os.Stat(newFile)
require.NoError(t, err)
assert.Equal(t, int64(0), info.Size())
assert.True(t, info.ModTime().After(before), "modification time should be set on creation")
})
t.Run("update existing", func(t *testing.T) {
tmpDir := t.TempDir()
existingFile := filepath.Join(tmpDir, "existing.txt")
err := os.WriteFile(existingFile, []byte("test"), 0600)
require.NoError(t, err)
// backdate the file rather than sleeping, so the timestamp has to move regardless of
// how coarse the filesystem's timestamp resolution is
backdated := time.Now().Add(-time.Hour)
require.NoError(t, os.Chtimes(existingFile, backdated, backdated))
origInfo, err := os.Stat(existingFile)
require.NoError(t, err)
err = TouchFile(existingFile)
require.NoError(t, err)
// check content preserved and time updated
info, err := os.Stat(existingFile)
require.NoError(t, err)
assert.Equal(t, origInfo.Size(), info.Size())
assert.True(t, info.ModTime().After(origInfo.ModTime()))
})
t.Run("errors", func(t *testing.T) {
err := TouchFile("")
require.Error(t, err)
assert.Contains(t, err.Error(), "empty path")
err = TouchFile("/dev/null/invalid")
require.Error(t, err)
})
}
func TestChecksum(t *testing.T) {
// create a temporary test file
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "checksum_test.txt")
content := []byte("this is a test file for checksum calculation")
err := os.WriteFile(testFile, content, 0600)
require.NoError(t, err)
// expected checksums (re-calculated)
expectedMD5 := "656b12fec36f7df11771b03c53e177ba"
expectedSHA1 := "be4c9cf3936f6d20ee0f38637605a405ea831168"
expectedSHA224 := "098477fd72b5128aa051cbd0a09010d14b3dd18114d66b061f0ff382"
expectedSHA384 := "a4de83d650a8a4d07483ad61296685d9d261e6edb940a025b8b981f90c17bdca794d45f202b2b8c3de5cd9c9bcf5e1e0"
expectedSHA512 := "a182278014c2a2d6d00de8442ab0e358e689269965eea6dfb7761abe019d0c34d47c181e19f1021901a5c0cf65b82871a0fa36b8bb187f9f5bf97ed182798e9e"
expectedSHA512_224 := "aab1745f6f1464c67c4a46d29c3a79132afe6d104f96a1266a69a278"
expectedSHA512_256 := "b5bc9721b180d5c79264f5fbb61404b516b6bfcb486c95b65329a1fe71ff6728"
expectedSHA256 := "7644ba794d6c4df31bd440ea9f7ecbcb8f2f3846cc58fcbf55d13560e168c863"
t.Run("md5", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgMD5)
require.NoError(t, err)
assert.Equal(t, expectedMD5, checksum)
})
t.Run("sha1", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgSHA1)
require.NoError(t, err)
assert.Equal(t, expectedSHA1, checksum)
})
t.Run("sha256", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgSHA256)
require.NoError(t, err)
assert.Equal(t, expectedSHA256, checksum)
})
t.Run("sha224", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgSHA224)
require.NoError(t, err)
assert.Equal(t, expectedSHA224, checksum)
})
t.Run("sha384", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgSHA384)
require.NoError(t, err)
assert.Equal(t, expectedSHA384, checksum)
})
t.Run("sha512", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgSHA512)
require.NoError(t, err)
assert.Equal(t, expectedSHA512, checksum)
})
t.Run("sha512_224", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgSHA512_224)
require.NoError(t, err)
assert.Equal(t, expectedSHA512_224, checksum)
})
t.Run("sha512_256", func(t *testing.T) {
checksum, err := Checksum(testFile, enum.HashAlgSHA512_256)
require.NoError(t, err)
assert.Equal(t, expectedSHA512_256, checksum)
})
t.Run("parse from string", func(t *testing.T) {
// test parsing from string
alg, err := enum.ParseHashAlg("sha256")
require.NoError(t, err)
checksum, err := Checksum(testFile, alg)
require.NoError(t, err)
assert.Equal(t, expectedSHA256, checksum)
})
t.Run("errors", func(t *testing.T) {
_, err := Checksum("nonexistent.txt", enum.HashAlgMD5)
require.Error(t, err)
assert.Contains(t, err.Error(), "file not found")
// test invalid algorithm parsing
_, err = enum.ParseHashAlg("unsupported_algo")
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid hashAlg")
_, err = Checksum("", enum.HashAlgMD5)
require.Error(t, err)
assert.Contains(t, err.Error(), "empty path")
})
}