-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrmstale_test.go
More file actions
781 lines (694 loc) · 21.4 KB
/
rmstale_test.go
File metadata and controls
781 lines (694 loc) · 21.4 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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"testing"
"time"
"github.com/google/logger"
"github.com/stretchr/testify/suite"
)
func init() {
initLogger()
}
// RMStaleSuite defines the testing suite with the following files:
//
// rootDir/
// oldEmptySubdir/
// oldSubdir1/
// oldFile2
// oldSubdir2/
// oldFile3.yes
// oldFile3.no
// oldSubdir3/
// recentFile3
// recentSubdir1/
// oldFile1
// oldFile4.no
// oldFile4.yes
// recentFile1
// recentFile2.no
// recentFile2.yes
type RMStateSuite struct {
suite.Suite
age int
rootDir string
oldEmptySubdir string
oldSubdir1 string
oldFile2 *os.File
oldSubdir2 string
oldFile3yes *os.File
oldFile3no *os.File
oldSubdir3 string
recentFile3 *os.File
recentSubdir1 string
oldFile1 *os.File
oldFile4no *os.File
oldFile4yes *os.File
recentFile1 *os.File
recentFile2no *os.File
recentFile2yes *os.File
}
// The SetupTest method will be run before every test in the suite.
func (suite *RMStateSuite) SetupTest() {
// Create folder structure
suite.rootDir = tempDirectory(suite.T(), "rootDir", os.TempDir())
suite.oldSubdir1 = tempDirectory(suite.T(), "oldSubdir1", suite.rootDir)
suite.oldSubdir2 = tempDirectory(suite.T(), "oldSubdir2", suite.rootDir)
suite.oldSubdir3 = tempDirectory(suite.T(), "oldSubdir3", suite.rootDir)
suite.oldEmptySubdir = tempDirectory(suite.T(), "oldEmptySubdir", suite.rootDir)
suite.recentSubdir1 = tempDirectory(suite.T(), "recentSubdir1", suite.rootDir)
// Create file structure
suite.oldFile2 = tempFile(suite.T(), "oldFile2", suite.oldSubdir1)
suite.oldFile3no = tempFile(suite.T(), "oldFile3.*.no", suite.oldSubdir2)
suite.oldFile3yes = tempFile(suite.T(), "oldFile3.*.yes", suite.oldSubdir2)
suite.oldFile1 = tempFile(suite.T(), "oldFile1", suite.rootDir)
suite.oldFile4no = tempFile(suite.T(), "oldFile4.*.no", suite.rootDir)
suite.oldFile4yes = tempFile(suite.T(), "oldFile4.*.yes", suite.rootDir)
suite.recentFile1 = tempFile(suite.T(), "recentFile1", suite.rootDir)
suite.recentFile2no = tempFile(suite.T(), "recentFile2.*.no", suite.rootDir)
suite.recentFile2yes = tempFile(suite.T(), "recentFile2.*.yes", suite.rootDir)
suite.recentFile3 = tempFile(suite.T(), "recentFile3", suite.oldSubdir3)
// Set the ages of the files and folders
suite.age = 14
setAge(suite.oldSubdir1, suite.age+4)
setAge(suite.oldSubdir2, suite.age+4)
setAge(suite.oldSubdir3, suite.age+4)
setAge(suite.oldEmptySubdir, suite.age+4)
setAge(suite.recentSubdir1, suite.age-4)
setAge(suite.oldFile1.Name(), suite.age+4)
setAge(suite.oldFile2.Name(), suite.age+4)
setAge(suite.oldFile3no.Name(), suite.age+4)
setAge(suite.oldFile3yes.Name(), suite.age+4)
setAge(suite.oldFile4no.Name(), suite.age+4)
setAge(suite.oldFile4yes.Name(), suite.age+4)
setAge(suite.recentFile1.Name(), suite.age-4)
setAge(suite.recentFile2no.Name(), suite.age-4)
setAge(suite.recentFile2yes.Name(), suite.age-4)
setAge(suite.recentFile3.Name(), suite.age-4)
}
// The TearDownTest method will be run after every test in the suite.
func (suite *RMStateSuite) TearDownTest() {
if err := os.RemoveAll(suite.rootDir); err != nil {
suite.T().Fatal(err)
}
}
// TestAgeDetection tests the detection of stale files
func (suite *RMStateSuite) TestAgeDetection() {
for _, t := range []struct {
name string
filename string
want bool
}{
{
name: "Test with an old file",
filename: suite.oldFile1.Name(),
want: true,
},
{
name: "Test with an old folder",
filename: suite.oldSubdir1,
want: true,
},
{
name: "Test with a new file",
filename: suite.recentFile1.Name(),
want: false,
},
{
name: "Test with a new folder",
filename: suite.recentSubdir1,
want: false,
},
} {
suite.Run(t.name, func() {
got := isStale(fileInfo(suite.T(), t.filename), suite.age)
suite.Equal(t.want, got)
})
}
}
// TestAgeDetection tests the removal of old files
func (suite *RMStateSuite) TestFileRemoval() {
for _, t := range []struct {
name string
filename string
directory string
dryRun bool
want bool
}{
{
name: "Test with a file",
filename: suite.oldFile1.Name(),
directory: suite.rootDir,
dryRun: false,
want: false,
},
{
name: "Test with an empty folder",
filename: suite.oldEmptySubdir,
directory: suite.rootDir,
dryRun: false,
want: false,
},
{
name: "Test with a non-empty folder",
filename: suite.oldSubdir1,
directory: suite.rootDir,
dryRun: false,
want: true,
},
{
name: "Test when given the root folder",
filename: suite.rootDir,
directory: suite.rootDir,
dryRun: false,
want: true,
},
} {
suite.Run(t.name, func() {
removeItem(t.filename, t.directory, t.dryRun)
got := exists(t.filename)
suite.Equal(t.want, got)
})
}
}
// TestEmptyDirectoryDetection tests the empty folder detection
func (suite *RMStateSuite) TestEmptyDirectoryDetection() {
for _, t := range []struct {
name string
filename string
directory string
want bool
wantErr bool
}{
{
name: "Test with the root folder",
directory: suite.rootDir,
want: false,
wantErr: false,
},
{
name: "Test with an old empty folder",
directory: suite.oldEmptySubdir,
want: true,
wantErr: false,
},
{
name: "Test with an new empty folder",
directory: suite.recentSubdir1,
want: true,
wantErr: false,
},
{
name: "Test with a non-existing folder",
directory: "fakefile",
want: false,
wantErr: true,
},
} {
suite.Run(t.name, func() {
got, err := isEmpty(t.directory)
suite.Equal(t.wantErr, (err != nil))
suite.Equal(t.want, got)
})
}
}
// TestProcDirErrors tests the edge cases for the procDir function
func (suite *RMStateSuite) TestProcDirErrors() {
for _, t := range []struct {
name string
path string
directory string
ext string
dryRun bool
wantErr bool
}{
{
name: "Test with a missing file",
path: "badFile",
directory: suite.rootDir,
ext: "",
dryRun: false,
wantErr: true,
},
{
name: "Test with a file",
path: suite.oldFile1.Name(),
directory: suite.oldFile1.Name(),
ext: "",
dryRun: false,
wantErr: true,
},
} {
suite.Run(t.name, func() {
err := procDir(t.path, t.directory, suite.age, t.ext, t.dryRun, false)
suite.Equal(t.wantErr, (err != nil))
})
}
}
// TestDirectoryProcessing tests the running the entire process over a directory
func (suite *RMStateSuite) TestDirectoryProcessing() {
err := procDir(suite.rootDir, suite.rootDir, suite.age, "", false, false)
// Ensure that err == nil
suite.Nil(err)
// Check that all of the old files are removed
suite.False(exists(suite.oldFile1.Name()))
suite.False(exists(suite.oldFile2.Name()))
suite.False(exists(suite.oldFile3no.Name()))
suite.False(exists(suite.oldFile3yes.Name()))
suite.False(exists(suite.oldFile4no.Name()))
suite.False(exists(suite.oldFile4yes.Name()))
// Check that the new files are retained
suite.True(exists(suite.recentFile1.Name()))
suite.True(exists(suite.recentFile2no.Name()))
suite.True(exists(suite.recentFile2yes.Name()))
// Check old empty directories are removed
suite.False(exists(suite.oldSubdir1))
suite.False(exists(suite.oldEmptySubdir))
// Check that the old directories that still have files are retained
suite.True(exists(suite.oldSubdir3))
// Check that new directories that contain no files are retained
suite.True(exists(suite.recentSubdir1))
}
// TestFilteredDirectoryProcessing tests the running the entire process over a directory
func (suite *RMStateSuite) TestFilteredDirectoryProcessing() {
err := procDir(suite.rootDir, suite.rootDir, suite.age, "yes", false, false)
// Ensure that err == nil
suite.Nil(err)
// Check that all of the old files matching the extension are removed
suite.False(exists(suite.oldFile3yes.Name()))
suite.False(exists(suite.oldFile4yes.Name()))
// Check that all of the old files not matching the extension are retained
suite.True(exists(suite.oldFile3no.Name()))
suite.True(exists(suite.oldFile4no.Name()))
// Check that the new files are retained
suite.True(exists(suite.recentFile1.Name()))
suite.True(exists(suite.recentFile2no.Name()))
suite.True(exists(suite.recentFile2yes.Name()))
suite.True(exists(suite.recentFile3.Name()))
// Check all directories are retained
suite.True(exists(suite.recentSubdir1))
suite.True(exists(suite.oldSubdir1))
suite.True(exists(suite.oldSubdir2))
suite.True(exists(suite.oldSubdir3))
suite.True(exists(suite.oldEmptySubdir))
}
// TestDryRunOption tests the dry run option
func (suite *RMStateSuite) TestDryRunOption() {
err := procDir(suite.rootDir, suite.rootDir, suite.age, "yes", true, false)
// Ensure that err == nil
suite.Nil(err)
// Check that all of the old files are retained
suite.True(exists(suite.oldFile3yes.Name()))
suite.True(exists(suite.oldFile4yes.Name()))
// Check that all of the old files not matching the extension are retained
suite.True(exists(suite.oldFile3no.Name()))
suite.True(exists(suite.oldFile4no.Name()))
// Check that the new files are retained
suite.True(exists(suite.recentFile1.Name()))
suite.True(exists(suite.recentFile2no.Name()))
suite.True(exists(suite.recentFile2yes.Name()))
suite.True(exists(suite.recentFile3.Name()))
// Check all directories are retained
suite.True(exists(suite.recentSubdir1))
suite.True(exists(suite.oldSubdir1))
suite.True(exists(suite.oldSubdir2))
suite.True(exists(suite.oldSubdir3))
suite.True(exists(suite.oldEmptySubdir))
}
// TestPruneEmptyDirsOption tests the prune-empty-dirs option
func (suite *RMStateSuite) TestPruneEmptyDirsOption() {
// Create a new empty subdirectory that is recent (should normally be kept)
recentEmptySubdir := tempDirectory(suite.T(), "recentEmptySubdir", suite.rootDir)
setAge(recentEmptySubdir, suite.age-4)
// Run procDir with pruneEmptyDirs = true
err := procDir(suite.rootDir, suite.rootDir, suite.age, "", false, true)
// Ensure that err == nil
suite.Nil(err)
// Check that the recent empty subdirectory is removed
suite.False(exists(recentEmptySubdir))
// Check that other empty directories (even recent ones) are also removed
suite.False(exists(suite.recentSubdir1))
// Check that non-empty directories are still retained
suite.True(exists(suite.oldSubdir3))
}
// TestVersionInfo tests the version information output
func (suite *RMStateSuite) TestVersionInfo() {
expected := "rmstale v0.0.0"
actual := versionInfo()
suite.Equal(expected, actual)
}
// TestPrompt tests the prompt function
func (suite *RMStateSuite) TestPrompt() {
for _, t := range []struct {
name string
format string
a []interface{}
response string
want bool
}{
{
name: "Test with 'y' response",
format: "Test prompt (%s).",
a: []interface{}{"y"},
response: "y\n",
want: true,
},
{
name: "Test with 'y' response and nil args",
format: "Test prompt (%s).",
a: nil,
response: "y\n",
want: true,
},
{
name: "Test with 'y' response and multiple args",
format: "Test prompt (%s).",
a: []interface{}{"y", "z"},
response: "y\n",
want: true,
},
{
name: "Test with 'n' response",
format: "Test prompt (%s).",
a: []interface{}{"n"},
response: "n\n",
want: false,
},
{
name: "Test with invalid response",
format: "Test prompt (%s).",
a: []interface{}{"invalid"},
response: "invalid\n",
want: false,
},
{
name: "Test with error response",
format: "Test prompt (%s).",
a: []interface{}{"error"},
response: "",
want: false,
},
} {
suite.Run(t.name, func() {
// Redirect standard input for testing
oldStdin := os.Stdin
defer func() { os.Stdin = oldStdin }()
r, w, _ := os.Pipe()
os.Stdin = r
if _, err := fmt.Fprint(w, t.response); err != nil {
suite.T().Fatal(err)
}
if err := w.Close(); err != nil {
suite.T().Fatal(err)
}
got := prompt(t.format, t.a...)
suite.Equal(t.want, got)
})
}
}
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestRunSuite(t *testing.T) {
suite.Run(t, new(RMStateSuite))
}
func initLogger() {
defer logger.Init("rmstale_test", true, false, io.Discard).Close()
logger.SetFlags(log.Ltime | log.Lshortfile)
}
func fileInfo(t *testing.T, fn string) os.FileInfo {
fi, err := os.Stat(fn)
if err != nil {
t.Fatal(err)
}
return fi
}
func tempFile(t *testing.T, prefix, dir string) *os.File {
content := []byte("Test file contents")
tmpFile, err := os.CreateTemp(dir, prefix)
if err != nil {
t.Fatal(err)
}
if _, err := tmpFile.Write(content); err != nil {
t.Fatal(err)
}
if err := tmpFile.Close(); err != nil {
t.Fatal(err)
}
return tmpFile
}
func tempDirectory(t *testing.T, prefix, dir string) string {
tmpDir, err := os.MkdirTemp(dir, prefix)
if err != nil {
t.Fatal(err)
}
return tmpDir
}
func setAge(f string, age int) {
ts := time.Now().AddDate(0, 0, (age * -1))
_ = os.Chtimes(f, ts, ts)
}
func exists(fn string) bool {
if _, err := os.Stat(fn); err == nil {
return true
}
return false
}
// captureOutput captures stdout during function f execution
func captureOutput(f func()) string {
old := os.Stdout
r, w, err := os.Pipe()
if err != nil {
panic(err)
}
os.Stdout = w
f()
if err := w.Close(); err != nil {
panic(err)
}
os.Stdout = old
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
panic(err)
}
return buf.String()
}
func TestMainVersionFlag(t *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
os.Args = []string{"rmstale", "-v"}
output := captureOutput(func() { main() })
if !strings.Contains(output, "rmstale v") {
t.Fatalf("expected version info, got %q", output)
}
}
func TestMainNoFlagsShowsUsage(t *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
os.Args = []string{"rmstale"}
output := captureOutput(func() { main() })
if !strings.Contains(output, "Usage of rmstale") {
t.Fatalf("expected usage output, got %q", output)
}
}
func TestMainHelpShowsDefaults(t *testing.T) {
output := usage()
if !strings.Contains(output, os.TempDir()) {
t.Fatalf("expected default path in usage output, got %q", output)
}
if !strings.Contains(output, "(REQUIRED)") || !strings.Contains(output, "(default false)") {
t.Fatalf("expected default values in usage output, got %q", output)
}
if !strings.Contains(output, "--prune-empty-dirs") {
t.Fatal("expected --prune-empty-dirs in usage output")
}
}
func TestGetExt(t *testing.T) {
for _, tt := range []struct{ path, want string }{
{"file.txt", "txt"},
{"dir/file.tar.gz", "gz"},
{"dir/file", ""},
{"dir.name/file", ""},
} {
if got := getExt(tt.path); got != tt.want {
t.Errorf("getExt(%q) = %q, want %q", tt.path, got, tt.want)
}
}
}
func TestMatchExt(t *testing.T) {
for _, tt := range []struct {
name string
ext string
want bool
}{
{"empty ext always matches", "", true},
{"match", "txt", true},
{"no match", "gz", false},
} {
file := "test.txt"
if tt.name == "no match" {
file = "test.doc"
}
if got := matchExt(file, tt.ext); got != tt.want {
t.Errorf("%s: matchExt(%q,%q) = %v, want %v", tt.name, file, tt.ext, got, tt.want)
}
}
}
func TestGetDirectoryContents(t *testing.T) {
dir := os.TempDir()
tmp, err := os.CreateTemp(dir, "file")
if err != nil {
t.Fatal(err)
}
if err := tmp.Close(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := os.Remove(tmp.Name()); err != nil {
t.Fatal(err)
}
})
infos, err := getDirectoryContents(dir)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(infos) == 0 {
t.Fatalf("expected some entries, got 0")
}
_, err = getDirectoryContents("non-existent")
if err == nil {
t.Fatalf("expected error for bad directory")
}
}
// TestMainWithExtensionMessage tests main function with extension message
func TestMainWithExtensionMessage(t *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
// Create a temporary directory for testing
tmpDir := tempDirectory(t, "test", os.TempDir())
defer os.RemoveAll(tmpDir)
// Create files with different extensions
txtFile := tempFile(t, "test.txt", tmpDir)
docFile := tempFile(t, "test.doc", tmpDir)
setAge(txtFile.Name(), 35) // Make them old
setAge(docFile.Name(), 35)
os.Args = []string{"rmstale", "-a", "30", "-e", "txt", "-y", "-d", "-p", tmpDir}
// Run main and verify extension filtering works
main()
// Both files should still exist since we're in dry-run mode
// But the extension logic should have been exercised
if !exists(txtFile.Name()) || !exists(docFile.Name()) {
t.Fatal("files should still exist in dry-run mode")
}
}
// TestMainWithProcDirError tests main function when procDir returns an error
func TestMainWithProcDirError(_ *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
os.Args = []string{"rmstale", "-a", "30", "-p", "/nonexistent/path", "-y"}
// Just verify main doesn't panic when given invalid path
// The error handling is internal and logged, not returned
main()
// Test passes if no panic occurs - the error is handled internally
}
// TestIsEmptyWithFile tests isEmpty function with a file instead of directory
func TestIsEmptyWithFile(t *testing.T) {
tmpFile := tempFile(t, "test", os.TempDir())
defer os.Remove(tmpFile.Name())
_, err := isEmpty(tmpFile.Name())
if err == nil {
t.Fatal("expected error when calling isEmpty on a file")
}
}
// TestGetDirectoryContentsError tests error handling in getDirectoryContents
func TestGetDirectoryContentsError(t *testing.T) {
_, err := getDirectoryContents("/nonexistent/directory/path")
if err == nil {
t.Fatal("expected error when getting contents of non-existent directory")
}
}
// TestHandleEmptyDirectoryWithExtensionFilter tests handleEmptyDirectory with extension filter
func TestHandleEmptyDirectoryWithExtensionFilter(t *testing.T) {
tmpDir := tempDirectory(t, "test", os.TempDir())
defer os.RemoveAll(tmpDir)
// Make directory old
setAge(tmpDir, 30)
// Test with extension filter - should not remove directory even if empty and old
err := handleEmptyDirectory(tmpDir, fileInfo(t, tmpDir), 20, "txt", tmpDir, false, false)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Directory should still exist because extension filter is set
if !exists(tmpDir) {
t.Fatal("directory should not have been removed with extension filter")
}
}
// TestHandleEmptyDirectoryWithPruneAndExtensionFilter tests handleEmptyDirectory with both prune and extension filter
func TestHandleEmptyDirectoryWithPruneAndExtensionFilter(t *testing.T) {
tmpDir := tempDirectory(t, "test", os.TempDir())
defer os.RemoveAll(tmpDir)
subDir := tempDirectory(t, "subdir", tmpDir)
// Make directory old
setAge(subDir, 30)
// Test with extension filter AND pruneEmptyDirs - should remove directory
err := handleEmptyDirectory(subDir, fileInfo(t, subDir), 20, "txt", tmpDir, false, true)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Directory should be removed because pruneEmptyDirs is true, even though extension filter is set
if exists(subDir) {
t.Fatal("directory should have been removed with pruneEmptyDirs even with extension filter")
}
}
// TestProcDirWithFileAsPath tests procDir when given a file path instead of directory
func TestProcDirWithFileAsPath(t *testing.T) {
tmpFile := tempFile(t, "test", os.TempDir())
defer os.Remove(tmpFile.Name())
err := procDir(tmpFile.Name(), tmpFile.Name(), 30, "", false, false)
if err == nil {
t.Fatal("expected error when processing a file path as directory")
}
}
// TestMainWithConfirmationDenied tests main function when user denies confirmation
func TestMainWithConfirmationDenied(t *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
// Create a temporary directory for testing
tmpDir := tempDirectory(t, "test", os.TempDir())
defer os.RemoveAll(tmpDir)
// Create an old file that would be removed if confirmation was accepted
oldFile := tempFile(t, "oldfile", tmpDir)
setAge(oldFile.Name(), 35) // Make it older than 30 days
os.Args = []string{"rmstale", "-a", "30", "-p", tmpDir}
// Redirect stdin to simulate user input "n"
oldStdin := os.Stdin
defer func() { os.Stdin = oldStdin }()
r, w, _ := os.Pipe()
os.Stdin = r
go func() {
defer w.Close()
w.WriteString("n\n")
}()
output := captureOutput(func() { main() })
// Should contain confirmation prompt and file should still exist since user denied
if !strings.Contains(output, "Continue") && !strings.Contains(output, "proceed") {
t.Fatalf("expected confirmation prompt in output, got %q", output)
}
// File should still exist since user denied confirmation
if !exists(oldFile.Name()) {
t.Fatal("file should still exist after denying confirmation")
}
}
// TestIsEmptyWithDeferError tests the defer error handling in isEmpty
func TestIsEmptyWithDeferError(t *testing.T) {
// This is difficult to test directly, but we can test the normal case
// The defer error handling is covered when the file is properly closed
tmpDir := tempDirectory(t, "test", os.TempDir())
defer os.RemoveAll(tmpDir)
empty, err := isEmpty(tmpDir)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !empty {
t.Fatal("expected empty directory to be reported as empty")
}
}