github.com/jvandenbroek/directory_stat_exporter@v0.2.0/dirstatFileAge_test.go (about) 1 package main 2 3 import ( 4 "io/ioutil" 5 "log" 6 "os" 7 "path" 8 "testing" 9 "time" 10 ) 11 12 func setupTestFileWithTimestamp(dir string, file string, ts time.Time) *os.File { 13 f, err := ioutil.TempFile(dir, file) 14 if err != nil { 15 log.Fatal("could not create temp file") 16 } 17 err = os.Chtimes(f.Name(), ts, ts) 18 if err != nil { 19 log.Fatal("could not change timestamp of file") 20 } 21 return f 22 } 23 24 func TestOldestFileInDir(t *testing.T) { 25 tmpDir := setupTmpDir() 26 defer func() { 27 err := os.RemoveAll(tmpDir) 28 if err != nil { 29 log.Printf("could not remove tmpDir") 30 } 31 }() 32 33 setupTestFileWithTimestamp(tmpDir, "test", time.Now().Add(time.Second*time.Duration(-20))) 34 35 t.Run("given a dir with one file with 20 seconds of age when analysed non recursively then return 20", func(t *testing.T) { 36 age := time.Now().Unix() - getOldestFileModTimestamp(tmpDir, false) 37 if age != 20 { 38 t.Fail() 39 t.Errorf("the file age is not 20, it's %v\n", age) 40 } 41 }) 42 43 t.Run("given a dir with one file with 20 seconds of age when analysed recursively then return 20", func(t *testing.T) { 44 age := time.Now().Unix() - getOldestFileModTimestamp(tmpDir, true) 45 if age != 20 { 46 t.Fail() 47 t.Errorf("the file age is not 20, it's %v\n", age) 48 } 49 }) 50 } 51 52 func TestModTimeIfFileDoesNotExist(t *testing.T) { 53 tmpDir := setupTmpDir() 54 defer func() { 55 err := os.RemoveAll(tmpDir) 56 if err != nil { 57 log.Printf("could not remove tmpDir") 58 } 59 }() 60 61 // 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 62 // todo: make better / more clear test for this. 63 t.Run("given a dir with no file in it when analysed non recursively then return current timestamp", func(t *testing.T) { 64 age := getModTime(path.Join(tmpDir, "a-file-that-does-not.exist")) 65 current := time.Now().Unix() 66 if age < (current-5) || age > (current+1) { 67 t.Fail() 68 t.Errorf("the result should be %v, it was %v\n", current, age) 69 } 70 }) 71 }