github.com/outbrain/consul@v1.4.5/testutil/io.go (about)

     1  package testutil
     2  
     3  import (
     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.
    23  var tmpdir = "/tmp/consul-test"
    24  
    25  func 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  
    32  // TempDir creates a temporary directory within tmpdir
    33  // with the name 'testname-name'. If the directory cannot
    34  // be created t.Fatal is called.
    35  func TempDir(t *testing.T, name string) string {
    36  	if t != nil && t.Name() != "" {
    37  		name = t.Name() + "-" + name
    38  	}
    39  	name = strings.Replace(name, "/", "_", -1)
    40  	d, err := ioutil.TempDir(tmpdir, name)
    41  	if err != nil {
    42  		if t == nil {
    43  			panic(err)
    44  		}
    45  		t.Fatalf("err: %s", err)
    46  	}
    47  	return d
    48  }
    49  
    50  // TempFile creates a temporary file within tmpdir
    51  // with the name 'testname-name'. If the file cannot
    52  // be created t.Fatal is called. If a temporary directory
    53  // has been created before consider storing the file
    54  // inside this directory to avoid double cleanup.
    55  func TempFile(t *testing.T, name string) *os.File {
    56  	if t != nil && t.Name() != "" {
    57  		name = t.Name() + "-" + name
    58  	}
    59  	f, err := ioutil.TempFile(tmpdir, name)
    60  	if err != nil {
    61  		if t == nil {
    62  			panic(err)
    63  		}
    64  		t.Fatalf("err: %s", err)
    65  	}
    66  	return f
    67  }