testutil: new TempFile function, simplify WriteToNewTempFile (#8123)

Files returned by WriteToNewTempFile are cleaned up
automatically at the end of a test case execution.
WriteToNewTempFile now relies on the TB.TempDir()
function provided by the testing std package.

TempFile returns a temporary file that can be used
within a test case and is automatically removed
at the end of the test execution.
This commit is contained in:
Alessio Treglia
2020-12-09 18:27:20 +00:00
committed by GitHub
parent af401359eb
commit f51f5e6784
9 changed files with 49 additions and 84 deletions
+13 -6
View File
@@ -52,15 +52,22 @@ func ApplyMockIODiscardOutErr(c *cobra.Command) BufferReader {
}
// Write the given string to a new temporary file.
// Returns an open file and a clean up function that
// the caller must call to remove the file when it is
// no longer needed.
func WriteToNewTempFile(t testing.TB, s string) (*os.File, func()) {
fp, err := ioutil.TempFile("", strings.ReplaceAll(t.Name(), "/", "_")+"_")
// Returns an open file for the test to use.
func WriteToNewTempFile(t testing.TB, s string) *os.File {
t.Helper()
fp, err := TempFile(t)
require.Nil(t, err)
_, err = fp.WriteString(s)
require.Nil(t, err)
return fp, func() { os.Remove(fp.Name()) }
return fp
}
// TempFile returns a writable temporary file for the test to use.
func TempFile(t testing.TB) (*os.File, error) {
t.Helper()
return ioutil.TempFile(t.TempDir(), "")
}
+1 -5
View File
@@ -25,16 +25,12 @@ func TestApplyMockIO(t *testing.T) {
}
func TestWriteToNewTempFile(t *testing.T) {
tempfile, cleanup := testutil.WriteToNewTempFile(t, "test string")
tempfile := testutil.WriteToNewTempFile(t, "test string")
tempfile.Close()
bs, err := ioutil.ReadFile(tempfile.Name())
require.NoError(t, err)
require.Equal(t, "test string", string(bs))
cleanup()
require.NoFileExists(t, tempfile.Name())
}
func TestApplyMockIODiscardOutErr(t *testing.T) {