wa-lang.org/wazero@v1.0.2/internal/testing/maintester/maintester.go (about)

     1  package maintester
     2  
     3  import (
     4  	"os"
     5  	"path"
     6  	"strings"
     7  	"testing"
     8  
     9  	"wa-lang.org/wazero/internal/testing/require"
    10  )
    11  
    12  func TestMain(t *testing.T, main func(), args ...string) (stdout, stderr string) {
    13  	// Setup files to capture stdout and stderr
    14  	tmp := t.TempDir()
    15  
    16  	stdoutPath := path.Join(tmp, "stdout.txt")
    17  	stdoutF, err := os.Create(stdoutPath)
    18  	require.NoError(t, err)
    19  
    20  	stderrPath := path.Join(tmp, "stderr.txt")
    21  	stderrF, err := os.Create(stderrPath)
    22  	require.NoError(t, err)
    23  
    24  	// Save the old os.XXX and revert regardless of the outcome.
    25  	oldArgs := os.Args
    26  	os.Args = args
    27  	oldStdout := os.Stdout
    28  	os.Stdout = stdoutF
    29  	oldStderr := os.Stderr
    30  	os.Stderr = stderrF
    31  	revertOS := func() {
    32  		os.Args = oldArgs
    33  		_ = stdoutF.Close()
    34  		os.Stdout = oldStdout
    35  		_ = stderrF.Close()
    36  		os.Stderr = oldStderr
    37  	}
    38  	defer revertOS()
    39  
    40  	// Run the main command.
    41  	main()
    42  
    43  	// Revert os.XXX so that test output is visible on failure.
    44  	revertOS()
    45  
    46  	// Capture any output and return it in a portable way (ex without windows newlines)
    47  	stdoutB, err := os.ReadFile(stdoutPath)
    48  	require.NoError(t, err)
    49  	stdout = strings.ReplaceAll(string(stdoutB), "\r\n", "\n")
    50  
    51  	stderrB, err := os.ReadFile(stderrPath)
    52  	require.NoError(t, err)
    53  	stderr = strings.ReplaceAll(string(stderrB), "\r\n", "\n")
    54  
    55  	return
    56  }