github.com/n3integration/conseil@v0.1.1/testing.go (about) 1 package conseil 2 3 import ( 4 "os" 5 "path/filepath" 6 "regexp" 7 "testing" 8 ) 9 10 // StageTestDir sets up a testing directory structure for our tests 11 func StageTestDir(t *testing.T) (string, func()) { 12 cwd, err := os.Getwd() 13 if err != nil { 14 t.Fatalf("err: %s", err) 15 } 16 wd := filepath.Join(cwd, "__staging") 17 if err := os.MkdirAll(wd, 0755); err != nil { 18 t.Fatalf("err: %s", err) 19 } 20 return wd, func() { 21 CleanDir(t, wd) 22 } 23 } 24 25 // CleanDir recursively removes all generated content in dir 26 func CleanDir(t *testing.T, dir string) { 27 d, err := os.Open(dir) 28 if err != nil { 29 t.Fatalf("err: %s", err) 30 } 31 defer d.Close() 32 names, err := d.Readdirnames(-1) 33 if err != nil { 34 t.Fatalf("err: %s", err) 35 } 36 for _, name := range names { 37 err = os.RemoveAll(filepath.Join(dir, name)) 38 if err != nil { 39 t.Fatalf("err: %s", err) 40 } 41 } 42 } 43 44 // FileExists asserts that path exists 45 func FileExists(path string) bool { 46 if _, err := os.Stat(path); os.IsNotExist(err) { 47 return false 48 } 49 return true 50 } 51 52 // FileCount gets a count of files matching pattern 53 func FileCount(base string, pattern string) int { 54 count := 0 55 re := regexp.MustCompile(pattern) 56 filepath.Walk(base, func(path string, info os.FileInfo, err error) error { 57 if re.MatchString(path) { 58 count++ 59 } 60 return err 61 }) 62 return count 63 }