From e3af1b0ec63d3b319597ff3bc902c7373655f344 Mon Sep 17 00:00:00 2001 From: "M. J. Fromberger" Date: Mon, 26 Aug 2024 10:54:56 -0700 Subject: [PATCH] atomicfile: clean up example output before exit Wire up a TestMain that creates the temp directory and cleans it up before exiting from the test binary. This avoids littering the user's temp directory with example outputs. --- example_test.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/example_test.go b/example_test.go index 7f52b2a..fc2c9c1 100644 --- a/example_test.go +++ b/example_test.go @@ -7,20 +7,13 @@ import ( "os" "path/filepath" "strings" + "testing" "github.com/creachadair/atomicfile" ) var tempDir string -func init() { - dir, err := os.MkdirTemp("", "example") - if err != nil { - panic(err) - } - tempDir = dir -} - func cat(path string) { f, err := os.Open(path) if err != nil { @@ -96,3 +89,16 @@ func ExampleFile_Cancel() { // left right // left right } + +func TestMain(m *testing.M) { + // Set up a temporary directory for the examples that will get cleaned up + // before the tests exit. + var err error + tempDir, err = os.MkdirTemp("", "atomicfile-example") + if err != nil { + log.Fatalf("Create example output directory: %v", err) + } + code := m.Run() + os.RemoveAll(tempDir) + os.Exit(code) +}