forked from oliwur/directory_stat_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dirstatFileAge_test.go
71 lines (63 loc) · 1.91 KB
/
dirstatFileAge_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
package main
import (
"io/ioutil"
"log"
"os"
"path"
"testing"
"time"
)
func setupTestFileWithTimestamp(dir string, file string, ts time.Time) *os.File {
f, err := ioutil.TempFile(dir, file)
if err != nil {
log.Fatal("could not create temp file")
}
err = os.Chtimes(f.Name(), ts, ts)
if err != nil {
log.Fatal("could not change timestamp of file")
}
return f
}
func TestOldestFileInDir(t *testing.T) {
tmpDir := setupTmpDir()
defer func() {
err := os.RemoveAll(tmpDir)
if err != nil {
log.Printf("could not remove tmpDir")
}
}()
setupTestFileWithTimestamp(tmpDir, "test", time.Now().Add(time.Second*time.Duration(-20)))
t.Run("given a dir with one file with 20 seconds of age when analysed non recursively then return 20", func(t *testing.T) {
age := time.Now().Unix() - getOldestFileModTimestamp(tmpDir, false)
if age != 20 {
t.Fail()
t.Errorf("the file age is not 20, it's %v\n", age)
}
})
t.Run("given a dir with one file with 20 seconds of age when analysed recursively then return 20", func(t *testing.T) {
age := time.Now().Unix() - getOldestFileModTimestamp(tmpDir, true)
if age != 20 {
t.Fail()
t.Errorf("the file age is not 20, it's %v\n", age)
}
})
}
func TestModTimeIfFileDoesNotExist(t *testing.T) {
tmpDir := setupTmpDir()
defer func() {
err := os.RemoveAll(tmpDir)
if err != nil {
log.Printf("could not remove tmpDir")
}
}()
// short explain why: it it would return -1, then -1 will always be the oldest file in a dir. it should not change the oldest file
// todo: make better / more clear test for this.
t.Run("given a dir with no file in it when analysed non recursively then return current timestamp", func(t *testing.T) {
age := getModTime(path.Join(tmpDir, "a-file-that-does-not.exist"))
current := time.Now().Unix()
if age < (current-5) || age > (current+1) {
t.Fail()
t.Errorf("the result should be %v, it was %v\n", current, age)
}
})
}