1package testutil
2
3import (
4	"fmt"
5	"io/ioutil"
6	"os"
7	"strings"
8	"testing"
9)
10
11// tmpdir is the base directory for all temporary directories
12// and files created with TempDir and TempFile. This could be
13// achieved by setting a system environment variable but then
14// the test execution would depend on whether or not the
15// environment variable is set.
16//
17// On macOS the temp base directory is quite long and that
18// triggers a problem with some tests that bind to UNIX sockets
19// where the filename seems to be too long. Using a shorter name
20// fixes this and makes the paths more readable.
21//
22// It also provides a single base directory for cleanup.
23var tmpdir = "/tmp/consul-test"
24
25func init() {
26	if err := os.MkdirAll(tmpdir, 0755); err != nil {
27		fmt.Printf("Cannot create %s. Reverting to /tmp\n", tmpdir)
28		tmpdir = "/tmp"
29	}
30}
31
32var noCleanup = strings.ToLower(os.Getenv("TEST_NOCLEANUP")) == "true"
33
34// TempDir creates a temporary directory within tmpdir with the name 'testname-name'.
35// If the directory cannot be created t.Fatal is called.
36// The directory will be removed when the test ends. Set TEST_NOCLEANUP env var
37// to prevent the directory from being removed.
38func TempDir(t testing.TB, name string) string {
39	if t == nil {
40		panic("argument t must be non-nil")
41	}
42	name = t.Name() + "-" + name
43	name = strings.Replace(name, "/", "_", -1)
44	d, err := ioutil.TempDir(tmpdir, name)
45	if err != nil {
46		t.Fatalf("err: %s", err)
47	}
48	t.Cleanup(func() {
49		if noCleanup {
50			t.Logf("skipping cleanup because TEST_NOCLEANUP was enabled")
51			return
52		}
53		os.RemoveAll(d)
54	})
55	return d
56}
57
58// TempFile creates a temporary file within tmpdir with the name 'testname-name'.
59// If the file cannot be created t.Fatal is called. If a temporary directory
60// has been created before consider storing the file inside this directory to
61// avoid double cleanup.
62// The file will be removed when the test ends.  Set TEST_NOCLEANUP env var
63// to prevent the file from being removed.
64func TempFile(t testing.TB, name string) *os.File {
65	if t == nil {
66		panic("argument t must be non-nil")
67	}
68	name = t.Name() + "-" + name
69	name = strings.Replace(name, "/", "_", -1)
70	f, err := ioutil.TempFile(tmpdir, name)
71	if err != nil {
72		t.Fatalf("err: %s", err)
73	}
74	t.Cleanup(func() {
75		if noCleanup {
76			t.Logf("skipping cleanup because TEST_NOCLEANUP was enabled")
77			return
78		}
79		os.Remove(f.Name())
80	})
81	return f
82}
83