github.com/tetratelabs/wazero@v1.7.3-0.20240513003603-48f702e154b5/examples/cli/cli_test.go (about)

     1  package cli
     2  
     3  import (
     4  	"bytes"
     5  	_ "embed"
     6  	"os"
     7  	"os/exec"
     8  	"path/filepath"
     9  	"runtime"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/tetratelabs/wazero/internal/testing/require"
    14  )
    15  
    16  //go:embed testdata/cli.wasm
    17  var cliWasm []byte
    18  
    19  func TestRun(t *testing.T) {
    20  	tests := []struct {
    21  		args   []string
    22  		stdOut string
    23  	}{
    24  		{
    25  			args:   []string{"3", "1"},
    26  			stdOut: "result: 4",
    27  		},
    28  		{
    29  			args:   []string{"-sub=true", "3", "1"},
    30  			stdOut: "result: 2",
    31  		},
    32  	}
    33  
    34  	wasmPath := filepath.Join(t.TempDir(), "cli.wasm")
    35  	require.NoError(t, os.WriteFile(wasmPath, cliWasm, 0o755))
    36  
    37  	// We can't invoke go run in our docker based cross-architecture tests. We do want to use
    38  	// otherwise so running unit tests normally does not require special build steps.
    39  	var cmdExe string
    40  	var cmdArgs []string
    41  	if cmdPath := os.Getenv("WAZEROCLI"); cmdPath != "" {
    42  		cmdExe = cmdPath
    43  	} else {
    44  		cmdExe = filepath.Join(runtime.GOROOT(), "bin", "go")
    45  		cmdArgs = []string{"run", "../../cmd/wazero"}
    46  	}
    47  	cmdArgs = append(cmdArgs, "run", wasmPath)
    48  
    49  	for _, tc := range tests {
    50  		tt := tc
    51  		t.Run(strings.Join(tt.args, " "), func(t *testing.T) {
    52  			stdOut := &bytes.Buffer{}
    53  			cmd := exec.Command(cmdExe, append(cmdArgs, tt.args...)...)
    54  			cmd.Stdout = stdOut
    55  			require.NoError(t, cmd.Run())
    56  			require.Equal(t, tt.stdOut, strings.TrimSpace(stdOut.String()))
    57  		})
    58  	}
    59  }