github.com/boxboat/in-toto-golang@v0.0.3-0.20210303203820-2fa16ecbe6f6/in_toto/in_toto_test.go (about)

     1  package in_toto
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  	"testing"
     9  )
    10  
    11  const testData = "../test/data"
    12  
    13  // TestMain calls all Test*'s of this package (in_toto) explicitly with m.Run
    14  // This can be used for test setup and teardown, e.g. copy test data to a tmp
    15  // test dir, change to that dir and remove the and contents in the end
    16  func TestMain(m *testing.M) {
    17  	testDir, err := ioutil.TempDir("", "in_toto_test_dir")
    18  	if err != nil {
    19  		panic("Cannot create temp test dir")
    20  	}
    21  
    22  	// Copy test files to temp test directory
    23  	// NOTE: Only works for a flat directory of files
    24  	testFiles, _ := filepath.Glob(filepath.Join(testData, "*"))
    25  	for _, inputPath := range testFiles {
    26  		input, err := ioutil.ReadFile(inputPath)
    27  		if err != nil {
    28  			panic(fmt.Sprintf("Cannot copy test files (read error: %s)", err))
    29  		}
    30  		outputPath := filepath.Join(testDir, filepath.Base(inputPath))
    31  		err = ioutil.WriteFile(outputPath, input, 0644)
    32  		if err != nil {
    33  			panic(fmt.Sprintf("Cannot copy test files (write error: %s)", err))
    34  		}
    35  	}
    36  
    37  	cwd, _ := os.Getwd()
    38  	err = os.Chdir(testDir)
    39  	if err != nil {
    40  		fmt.Printf("Unable to change dir to %s: %s", testDir, err)
    41  	}
    42  	// Always change back to where we were and remove the temp directory
    43  	defer func(cwd string) {
    44  		if err := os.Chdir(cwd); err != nil {
    45  			fmt.Printf("Unable to change to directory %s: %s", cwd, err)
    46  		}
    47  	}(cwd)
    48  	defer func(testDir string) {
    49  		if err := os.RemoveAll(testDir); err != nil {
    50  			fmt.Printf("Unable to remove directory %s: %s", testDir, err)
    51  		}
    52  	}(testDir)
    53  
    54  	// Run tests
    55  	m.Run()
    56  }