github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/testutils/os.go (about)

     1  package testutils
     2  
     3  import (
     4  	"os"
     5  	"strings"
     6  	"testing"
     7  )
     8  
     9  // NewTestCaseDir creates a new temporary directory for a test case.
    10  // Returns the directory path and a cleanup function.
    11  func NewTestCaseDir(t *testing.T) (string, func()) {
    12  	t.Helper()
    13  
    14  	// Replace any restricted character with safe ones (for nested tests)
    15  	pattern := strings.ReplaceAll(t.Name()+"_", "/", "_")
    16  	dir, err := os.MkdirTemp("", pattern)
    17  	if err != nil {
    18  		t.Fatalf("unable to generate temporary directory, %v", err)
    19  	}
    20  
    21  	return dir, func() { _ = os.RemoveAll(dir) }
    22  }
    23  
    24  // NewTestFile creates a new temporary file for a test case
    25  func NewTestFile(t *testing.T) (*os.File, func()) {
    26  	t.Helper()
    27  
    28  	// Replace any restricted character with safe ones (for nested tests)
    29  	pattern := strings.ReplaceAll(t.Name()+"-", "/", "_")
    30  	file, err := os.CreateTemp("", pattern)
    31  	if err != nil {
    32  		t.Fatalf(
    33  			"unable to create a temporary output file, %v",
    34  			err,
    35  		)
    36  	}
    37  
    38  	return file, func() { _ = os.RemoveAll(file.Name()) }
    39  }