Files
wazero/internal/testing/maintester/maintester.go
Crypt Keeper c4caa1ea9b Changes how examples are tested, and fixes ExitError bug (#468)
Before, we tested the examples/ directory using "ExampleXX", but this is
not ideal because it literally embeds the call to `main` into example
godoc output. This stops doing that for a different infrastructure.

This also makes sure there's a godoc example for both the main package
and wasi, so that people looking at https://pkg.go.dev see something and
also a link to our real examples directory.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-15 15:51:27 +08:00

57 lines
1.3 KiB
Go

package maintester
import (
"os"
"path"
"strings"
"testing"
"github.com/tetratelabs/wazero/internal/testing/require"
)
func TestMain(t *testing.T, main func(), args ...string) (stdout, stderr string) {
// Setup files to capture stdout and stderr
tmp := t.TempDir()
stdoutPath := path.Join(tmp, "stdout.txt")
stdoutF, err := os.Create(stdoutPath)
require.NoError(t, err)
stderrPath := path.Join(tmp, "stderr.txt")
stderrF, err := os.Create(stderrPath)
require.NoError(t, err)
// Save the old os.XXX and revert regardless of the outcome.
oldArgs := os.Args
os.Args = args
oldStdout := os.Stdout
os.Stdout = stdoutF
oldStderr := os.Stderr
os.Stderr = stderrF
revertOS := func() {
os.Args = oldArgs
_ = stdoutF.Close()
os.Stdout = oldStdout
_ = stderrF.Close()
os.Stderr = oldStderr
}
defer revertOS()
// Run the main command.
main()
// Revert os.XXX so that test output is visible on failure.
revertOS()
// Capture any output and return it in a portable way (ex without windows newlines)
stdoutB, err := os.ReadFile(stdoutPath)
require.NoError(t, err)
stdout = strings.ReplaceAll(string(stdoutB), "\r\n", "\n")
stderrB, err := os.ReadFile(stderrPath)
require.NoError(t, err)
stderr = strings.ReplaceAll(string(stderrB), "\r\n", "\n")
return
}