From 2725513eeae347cc111e5acbd31b06dd2f16eb27 Mon Sep 17 00:00:00 2001 From: Daniel Nephin Date: Fri, 14 Aug 2020 13:19:06 -0400 Subject: [PATCH] testutil: Add t.Cleanup to TempDir TempDir registers a Cleanup so that the directory is always removed. To disable to cleanup, set the TEST_NOCLEANUP env var. --- agent/testagent.go | 4 ---- sdk/testutil/io.go | 17 ++++++++++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/agent/testagent.go b/agent/testagent.go index 426de1a91..a946b32c4 100644 --- a/agent/testagent.go +++ b/agent/testagent.go @@ -10,7 +10,6 @@ import ( "io" "math/rand" "net/http/httptest" - "os" "path/filepath" "strconv" "testing" @@ -38,9 +37,6 @@ func init() { rand.Seed(time.Now().UnixNano()) // seed random number generator } -// TempDir defines the base dir for temporary directories. -var TempDir = os.TempDir() - // TestAgent encapsulates an Agent with a default configuration and // startup procedure suitable for testing. It panics if there are errors // during creation or startup instead of returning errors. It manages a diff --git a/sdk/testutil/io.go b/sdk/testutil/io.go index a137fc6a3..28f215b67 100644 --- a/sdk/testutil/io.go +++ b/sdk/testutil/io.go @@ -29,21 +29,28 @@ func init() { } } +var noCleanup = strings.ToLower(os.Getenv("TEST_NOCLEANUP")) == "true" + // TempDir creates a temporary directory within tmpdir // with the name 'testname-name'. If the directory cannot // be created t.Fatal is called. func TempDir(t *testing.T, name string) string { - if t != nil && t.Name() != "" { - name = t.Name() + "-" + name + if t == nil { + panic("argument t must be non-nil") } + name = t.Name() + "-" + name name = strings.Replace(name, "/", "_", -1) d, err := ioutil.TempDir(tmpdir, name) if err != nil { - if t == nil { - panic(err) - } t.Fatalf("err: %s", err) } + t.Cleanup(func() { + if noCleanup { + t.Logf("skipping cleanup because TEST_NOCLEANUP was enabled") + return + } + os.RemoveAll(d) + }) return d }