get.porter.sh/porter@v1.3.0/pkg/test/helper.go (about) 1 package test 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strconv" 8 "strings" 9 "testing" 10 11 "get.porter.sh/porter/pkg" 12 "github.com/stretchr/testify/assert" 13 "github.com/stretchr/testify/require" 14 ) 15 16 const ( 17 MockedCommandEnv = "MOCK_COMMAND" 18 ExpectedCommandEnv = "EXPECTED_COMMAND" 19 ExpectedCommandExitCodeEnv = "EXPECTED_COMMAND_EXIT_CODE" 20 ExpectedCommandErrorEnv = "EXPECTED_COMMAND_STDERR" 21 ExpectedCommandOutputEnv = "EXPECTED_COMMAND_STDOUT" 22 ) 23 24 func TestMainWithMockedCommandHandlers(m *testing.M) { 25 26 // Fake out executing a command 27 // It's okay to use os.LookupEnv here because it's running in it's own process, and won't impact running tests in parallel. 28 if _, mockCommand := os.LookupEnv(MockedCommandEnv); mockCommand { 29 if expectedCmdEnv, doAssert := os.LookupEnv(ExpectedCommandEnv); doAssert { 30 gotCmd := strings.Join(os.Args[1:len(os.Args)], " ") 31 32 // There may be multiple expected commands, separated by a newline character 33 wantCmds := strings.Split(expectedCmdEnv, "\n") 34 35 commandNotFound := true 36 for _, wantCmd := range wantCmds { 37 if wantCmd == gotCmd { 38 commandNotFound = false 39 } 40 } 41 42 if commandNotFound { 43 fmt.Printf("WANT COMMANDS : %q\n", wantCmds) 44 fmt.Printf("GOT COMMAND : %q\n", gotCmd) 45 os.Exit(127) 46 } 47 } 48 49 if wantOutput, ok := os.LookupEnv(ExpectedCommandOutputEnv); ok { 50 fmt.Fprintln(os.Stdout, wantOutput) 51 } 52 53 if wantError, ok := os.LookupEnv(ExpectedCommandErrorEnv); ok { 54 fmt.Fprintln(os.Stderr, wantError) 55 } 56 57 exitCode := 0 58 if wantCode, ok := os.LookupEnv(ExpectedCommandExitCodeEnv); ok { 59 exitCode, _ = strconv.Atoi(wantCode) 60 } 61 os.Exit(exitCode) 62 } 63 64 // Otherwise, run the tests 65 os.Exit(m.Run()) 66 } 67 68 // CompareGoldenFile checks if the specified string matches the content of a golden test file. 69 // When they are different and PORTER_UPDATE_TEST_FILES is true, the file is updated to match 70 // the new test output. 71 func CompareGoldenFile(t *testing.T, goldenFile string, got string) { 72 if os.Getenv("PORTER_UPDATE_TEST_FILES") == "true" { 73 err := os.MkdirAll(filepath.Dir(goldenFile), pkg.FileModeDirectory) 74 require.NoError(t, err) 75 t.Logf("Updated test file %s to match latest test output", goldenFile) 76 require.NoError(t, os.WriteFile(goldenFile, []byte(got), pkg.FileModeWritable), "could not update golden file %s", goldenFile) 77 } else { 78 wantSchema, err := os.ReadFile(goldenFile) 79 require.NoError(t, err) 80 assert.Equal(t, string(wantSchema), got, "The test output doesn't match the expected output in %s. If this was intentional, run mage updateTestfiles to fix the tests.", goldenFile) 81 } 82 }