2023-03-28 22:48:58 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2017-05-12 13:41:13 +00:00
|
|
|
package testutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2017-05-19 08:48:28 +00:00
|
|
|
"strings"
|
2017-05-12 13:41:13 +00:00
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
2020-08-14 17:19:06 +00:00
|
|
|
var noCleanup = strings.ToLower(os.Getenv("TEST_NOCLEANUP")) == "true"
|
2023-10-03 15:06:50 +00:00
|
|
|
var saveSnapshot = strings.ToLower(os.Getenv("TEST_SAVE_SNAPSHOT")) == "true"
|
2020-08-14 17:19:06 +00:00
|
|
|
|
2020-08-15 00:06:01 +00:00
|
|
|
// TempDir creates a temporary directory within tmpdir with the name 'testname-name'.
|
|
|
|
// If the directory cannot be created t.Fatal is called.
|
|
|
|
// The directory will be removed when the test ends. Set TEST_NOCLEANUP env var
|
|
|
|
// to prevent the directory from being removed.
|
2021-03-16 22:05:39 +00:00
|
|
|
func TempDir(t testing.TB, name string) string {
|
2020-08-14 17:19:06 +00:00
|
|
|
if t == nil {
|
|
|
|
panic("argument t must be non-nil")
|
2017-05-12 13:41:13 +00:00
|
|
|
}
|
2020-08-14 17:19:06 +00:00
|
|
|
name = t.Name() + "-" + name
|
2017-05-19 08:48:28 +00:00
|
|
|
name = strings.Replace(name, "/", "_", -1)
|
2022-11-10 16:26:01 +00:00
|
|
|
d, err := os.MkdirTemp("", name)
|
2017-05-12 13:41:13 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
2020-08-14 17:19:06 +00:00
|
|
|
t.Cleanup(func() {
|
|
|
|
if noCleanup {
|
|
|
|
t.Logf("skipping cleanup because TEST_NOCLEANUP was enabled")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
os.RemoveAll(d)
|
|
|
|
})
|
2017-05-12 13:41:13 +00:00
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
2020-08-15 00:06:01 +00:00
|
|
|
// TempFile creates a temporary file within tmpdir with the name 'testname-name'.
|
|
|
|
// If the file cannot be created t.Fatal is called. If a temporary directory
|
|
|
|
// has been created before consider storing the file inside this directory to
|
|
|
|
// avoid double cleanup.
|
|
|
|
// The file will be removed when the test ends. Set TEST_NOCLEANUP env var
|
|
|
|
// to prevent the file from being removed.
|
2021-03-16 22:05:39 +00:00
|
|
|
func TempFile(t testing.TB, name string) *os.File {
|
2020-08-15 00:06:01 +00:00
|
|
|
if t == nil {
|
|
|
|
panic("argument t must be non-nil")
|
2017-05-12 13:41:13 +00:00
|
|
|
}
|
2020-08-15 00:06:01 +00:00
|
|
|
name = t.Name() + "-" + name
|
2019-04-30 23:27:16 +00:00
|
|
|
name = strings.Replace(name, "/", "_", -1)
|
2022-11-10 16:26:01 +00:00
|
|
|
f, err := os.CreateTemp("", name)
|
2017-05-12 13:41:13 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
2020-08-15 00:06:01 +00:00
|
|
|
t.Cleanup(func() {
|
|
|
|
if noCleanup {
|
|
|
|
t.Logf("skipping cleanup because TEST_NOCLEANUP was enabled")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
os.Remove(f.Name())
|
|
|
|
})
|
2017-05-12 13:41:13 +00:00
|
|
|
return f
|
|
|
|
}
|