-
Notifications
You must be signed in to change notification settings - Fork 0
/
purge_test.go
87 lines (78 loc) · 2.53 KB
/
purge_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
package main
import (
"testing"
"os"
"path/filepath"
"time"
"errors"
)
func TestPurgeOldFiles (t *testing.T) {
dir, err := os.MkdirTemp("", "")
if (err != nil) {
t.Fatalf("failed to create a temporary directory; %v", err)
}
path := filepath.Join(dir, "A")
err = os.WriteFile(path, []byte(""), 0644)
if err != nil {
t.Fatalf("failed to create a mock file; %v", err)
}
subdir := filepath.Join(dir, "sub")
err = os.Mkdir(subdir, 0755)
if err != nil {
t.Fatalf("failed to create a temporary subdirectory; %v", err)
}
subpath := filepath.Join(subdir, "B")
err = os.WriteFile(subpath, []byte(""), 0644)
if err != nil {
t.Fatalf("failed to create a mock file; %v", err)
}
// Also mocking up a symlink to ensure that this is handled sensibly.
var target string
{
handle, err := os.CreateTemp("", "")
if err != nil {
t.Fatalf("failed to create a temporary file; %v", err)
}
target = handle.Name()
handle.Close()
}
sympath := filepath.Join(dir, "C")
err = os.Symlink(target, sympath)
if err != nil {
t.Fatalf("failed to create a symlink; %v", err)
}
// Deleting with a 1-hour expiry.
err = purgeOldFiles(dir, 1 * time.Hour)
if (err != nil) {
t.Fatal(err)
}
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
t.Error("should not have deleted this file")
}
if _, err := os.Stat(subpath); errors.Is(err, os.ErrNotExist) {
t.Error("should not have deleted this file")
}
if _, err := os.Stat(sympath); errors.Is(err, os.ErrNotExist) {
t.Error("should not have deleted this file")
}
// Deleting with an immediate expiry.
err = purgeOldFiles(dir, 0 * time.Hour)
if (err != nil) {
t.Fatal(err)
}
if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
t.Error("should not have deleted the entire directory")
}
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
t.Error("should have deleted this file")
}
if _, err := os.Stat(subdir); !errors.Is(err, os.ErrNotExist) {
t.Error("should have deleted this directory")
}
if _, err := os.Stat(sympath); !errors.Is(err, os.ErrNotExist) { // Symlink can be deleted, but not its target.
t.Error("should have deleted the symlink")
}
if _, err := os.Stat(target); errors.Is(err, os.ErrNotExist) {
t.Error("should not have deleted the symlink target")
}
}