github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+incompatible/builder/dockerfile/utils_test.go (about)

     1  package dockerfile // import "github.com/docker/docker/builder/dockerfile"
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"testing"
     7  )
     8  
     9  // createTestTempDir creates a temporary directory for testing.
    10  // It returns the created path and a cleanup function which is meant to be used as deferred call.
    11  // When an error occurs, it terminates the test.
    12  func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {
    13  	path, err := os.MkdirTemp(dir, prefix)
    14  
    15  	if err != nil {
    16  		t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
    17  	}
    18  
    19  	return path, func() {
    20  		err = os.RemoveAll(path)
    21  
    22  		if err != nil {
    23  			t.Fatalf("Error when removing directory %s: %s", path, err)
    24  		}
    25  	}
    26  }
    27  
    28  // createTestTempFile creates a temporary file within dir with specific contents and permissions.
    29  // When an error occurs, it terminates the test
    30  func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {
    31  	filePath := filepath.Join(dir, filename)
    32  	err := os.WriteFile(filePath, []byte(contents), perm)
    33  
    34  	if err != nil {
    35  		t.Fatalf("Error when creating %s file: %s", filename, err)
    36  	}
    37  
    38  	return filePath
    39  }
    40  
    41  // createTestSymlink creates a symlink file within dir which points to oldname
    42  func createTestSymlink(t *testing.T, dir, filename, oldname string) string {
    43  	filePath := filepath.Join(dir, filename)
    44  	if err := os.Symlink(oldname, filePath); err != nil {
    45  		t.Fatalf("Error when creating %s symlink to %s: %s", filename, oldname, err)
    46  	}
    47  
    48  	return filePath
    49  }