diff --git a/test/io/io.go b/test/io/io.go new file mode 100644 index 0000000000..593acdfb84 --- /dev/null +++ b/test/io/io.go @@ -0,0 +1,31 @@ +package io + +import ( + "fmt" + "io/ioutil" + "os" + "regexp" + "testing" +) + +var invalidPathCharRegex = regexp.MustCompile("([^a-zA-Z0-9])") + +// TestDirectory returns a temporary directory for this test only. Calling TestDirectory multiple times for the same +// instance of t returns a new directory every time. +func TestDirectory(t *testing.T) string { + if dir, err := ioutil.TempDir("", normalizeTestName(t)); err != nil { + t.Fatal(err) + return "" + } else { + t.Cleanup(func() { + if err := os.RemoveAll(dir); err != nil { + _, _ = os.Stderr.WriteString(fmt.Sprintf("Unable to remove temporary directory for test (%s): %v\n", dir, err)) + } + }) + return dir + } +} + +func normalizeTestName(t *testing.T) string { + return invalidPathCharRegex.ReplaceAllString(t.Name(), "_") +} diff --git a/test/io/io_test.go b/test/io/io_test.go new file mode 100644 index 0000000000..6dca9e99bd --- /dev/null +++ b/test/io/io_test.go @@ -0,0 +1,14 @@ +package io + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func Test_normalizeTestName(t *testing.T) { + t.Run("level 1!@#!@3", func(t *testing.T) { + t.Run("level 2!!", func(t *testing.T) { + assert.Equal(t, "Test_normalizeTestName_level_1_____3_level_2__", normalizeTestName(t)) + }) + }) +} \ No newline at end of file