github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/pkg/testutil/testutil.go (about)

     1  // Copyright 2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package testutil
     6  
     7  import (
     8  	"io/ioutil"
     9  	"os"
    10  	"os/exec"
    11  	"path/filepath"
    12  	"strings"
    13  	"testing"
    14  )
    15  
    16  // CompileInTempDir creates a temp directory and compiles the main package of
    17  // the current directory. Remember to delete the directory after the test:
    18  //
    19  //     defer os.RemoveAll(tmpDir)
    20  //
    21  // The first argument of the environment variable EXECPATH overrides execPath.
    22  func CompileInTempDir(t testing.TB) (tmpDir string, execPath string) {
    23  	// Create temp directory
    24  	tmpDir, err := ioutil.TempDir("", "Test")
    25  	if err != nil {
    26  		t.Fatal("TempDir failed: ", err)
    27  	}
    28  
    29  	// Skip compilation if EXECPATH is set.
    30  	execPath = os.Getenv("EXECPATH")
    31  	if execPath != "" {
    32  		execPath = strings.SplitN(execPath, " ", 2)[0]
    33  		return
    34  	}
    35  
    36  	// Compile the program
    37  	execPath = filepath.Join(tmpDir, "exec")
    38  	out, err := exec.Command("go", "build", "-o", execPath).CombinedOutput()
    39  	if err != nil {
    40  		t.Fatalf("Failed to build: %v\n%s", err, string(out))
    41  	}
    42  	return
    43  }