Skip to content

Instantly share code, notes, and snippets.

@willis7
Last active May 2, 2016 11:22
Show Gist options
  • Save willis7/9b781d64cfe65158e70fd5495f4b9aca to your computer and use it in GitHub Desktop.
Save willis7/9b781d64cfe65158e70fd5495f4b9aca to your computer and use it in GitHub Desktop.
Test Helpers for Go
// testTempFile
// create a temp file using only a single line
// cleanly manages err handling
func testTempFile(t *testing.T) string {
tf, err := ioutil.TempFile("", "test")
if err != nil {
t.Fatalf("err: %s", err)
}
tf.Close()
return tf.Name()
}
// testChdir
// use defer to return to a previous state.
// this example shows changing a directory and changing it back later.
func testChdir(t *testing.T, dir string) func() {
old, err := os.Getwd()
if err != nil {
t.Fatalf("err: %s", err)
}
if err := os.Chdir(dir); err != nil {
t.Fatalf("err: %s", err)
}
return func() { os.Chdir(old) }
}
func TestThing(t *testing.T) {
defer testChdir(t, "/other")()
// ... test something
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment