github.com/jvandenbroek/directory_stat_exporter@v0.2.0/dirstatCounter_test.go (about) 1 package main 2 3 import ( 4 "io/ioutil" 5 "log" 6 "os" 7 "testing" 8 ) 9 10 func setupTmpDir() string { 11 tmpDir, err := ioutil.TempDir("", "dirstat_test_") 12 if err != nil { 13 log.Fatal("could not create temp dir", err) 14 } 15 return tmpDir 16 } 17 18 func TestGetFileCountZero(t *testing.T) { 19 tmpDir := setupTmpDir() 20 defer func() { 21 err := os.RemoveAll(tmpDir) 22 if err != nil { 23 log.Printf("could not remove tmpDir") 24 } 25 }() 26 27 t.Run("given a empty directory when counted not recursively then it should return 0", func(t *testing.T) { 28 count := getFileCount(tmpDir, false) 29 30 if count != 0 { 31 t.Fail() 32 t.Errorf("there are no documents in this folder. the count must be zero. it is %d!\n", count) 33 } 34 }) 35 36 t.Run("given an empty dir when counted recursively then it should return 0", func(t *testing.T) { 37 count := getFileCount(tmpDir, true) 38 if count != 0 { 39 t.Fail() 40 t.Error("the value shoud be 0 but was", count) 41 } 42 }) 43 } 44 45 func TestGetFileCountThree(t *testing.T) { 46 tmpDir := setupTmpDir() 47 defer func() { 48 err := os.RemoveAll(tmpDir) 49 if err != nil { 50 log.Printf("could not remove tmpDir") 51 } 52 }() 53 54 _, _ = ioutil.TempFile(tmpDir, "file1") 55 _, _ = ioutil.TempFile(tmpDir, "file2") 56 _, _ = ioutil.TempFile(tmpDir, "file3") 57 58 t.Run("given a directory with 3 files when counted not recursively then it should return 3", func(t *testing.T) { 59 count := getFileCount(tmpDir, false) 60 61 if count != 3 { 62 t.Fail() 63 t.Errorf("there are no documents in this folder. the count must be zero. it is %d!\n", count) 64 } 65 }) 66 67 t.Run("given a directory with 3 files when counted recursively then it should return 3", func(t *testing.T) { 68 count := getFileCount(tmpDir, true) 69 70 if count != 3 { 71 t.Fail() 72 t.Errorf("there are 3 files in the directory, it reported %d\n", count) 73 } 74 }) 75 } 76 77 func TestGetFileCountNotExisting(t *testing.T) { 78 tmpDir := setupTmpDir() 79 defer func() { 80 err := os.RemoveAll(tmpDir) 81 if err != nil { 82 log.Printf("could not remove tmpDir") 83 } 84 }() 85 86 t.Run("given the directory does not exist when counted non recursively then it should return -1 indicating an error", func(t *testing.T) { 87 count := getFileCount(tmpDir+"_this_dir_does_not_exist", false) 88 89 if count != -1 { 90 t.Fail() 91 t.Errorf("it should return -1, because the dir does not exist. it returned %d instead.\n", count) 92 } 93 }) 94 95 t.Run("given the directory does not exist when counted recursively then it should return -1 indicating an error", func(t *testing.T) { 96 count := getFileCount(tmpDir+"_this_dir_does_not_exist", true) 97 98 if count != -1 { 99 t.Fail() 100 t.Errorf("it should return -1, because the dir does not exist. it returned %d instead.\n", count) 101 } 102 }) 103 }