Last active
May 2, 2016 11:22
-
-
Save willis7/9b781d64cfe65158e70fd5495f4b9aca to your computer and use it in GitHub Desktop.
Test Helpers for Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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