github.com/atlassian/git-lob@v0.0.0-20150806085256-2386a5ed291a/testutils_test.go (about) 1 package main 2 3 import ( 4 "bufio" 5 cryptorand "crypto/rand" 6 "fmt" 7 "io" 8 "os" 9 "os/exec" 10 "path/filepath" 11 "runtime" 12 "strings" 13 14 . "github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/ginkgo" 15 "github.com/atlassian/git-lob/util" 16 ) 17 18 // Utility methods for testing only 19 // Sadly there's some duplication with the same file in the 'core' package; this is because you can't import shared packages when testing 20 // and still use _test.go to avoid polluting the non-testing namespace. Minimal duplication is a lesser evil than putting these utility functions 21 // in the non-test build 22 func CreateGitRepoForTest(path string) { 23 // in case not previously deleted cleanly 24 ForceRemoveAll(path) 25 cmd := exec.Command("git", "init", path) 26 err := cmd.Run() 27 if err != nil { 28 Fail("Unable to create git repo at " + path + ": " + err.Error()) 29 } 30 } 31 32 // Simplistic fire & forget running of git command - returns combined output 33 func RunGitCommandForTest(failureCheck bool, args ...string) string { 34 outp, err := exec.Command("git", args...).CombinedOutput() 35 if failureCheck && err != nil { 36 Fail(fmt.Sprintf("Error running git command 'git %v': %v", strings.Join(args, " "), err.Error())) 37 } 38 return string(outp) 39 40 } 41 42 // Create a file with random data of size sz 43 func CreateRandomFileForTest(sz int64, filename string) { 44 os.MkdirAll(filepath.Dir(filename), 0755) 45 f, err := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) 46 if err != nil { 47 Fail(fmt.Sprintf("Can't create test file %v: %v", filename, err)) 48 } 49 defer f.Close() 50 // random data 51 fileWriter := bufio.NewWriter(f) 52 _, err = io.CopyN(fileWriter, cryptorand.Reader, sz) 53 fileWriter.Flush() 54 if err != nil { 55 Fail(fmt.Sprintf("Can't write random data to test file %v: %v", filename, err)) 56 } 57 58 } 59 60 // Delete a directory & all contents, overriding read-only flags 61 // BE VERY CAREFUL WITH THIS 62 func ForceRemoveAll(path string) error { 63 // os.RemoveAll doesn't always work. Git marks some files within its structure as read-only 64 // and some OS's then don't delete these files & return an error (e.g. Windows) 65 err := os.RemoveAll(path) 66 if err != nil && runtime.GOOS == "windows" { 67 if path != "" && path != "\\" && util.DirExists(path) { 68 // 'del' isn't an executable, it's a builtin of cmd 69 cmd := exec.Command("cmd", "/C", "del", "/S", "/F", "/Q", path) 70 err = cmd.Run() 71 } 72 } 73 74 return err 75 }