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) +}