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