wa-lang.org/wazero@v1.0.2/imports/wasi_snapshot_preview1/example/cat_test.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "fmt" 6 "io/fs" 7 "os" 8 "os/exec" 9 "path/filepath" 10 "runtime" 11 "testing" 12 13 "wa-lang.org/wazero/internal/testing/maintester" 14 "wa-lang.org/wazero/internal/testing/require" 15 ) 16 17 // Test_main ensures the following will work: 18 // 19 // go run cat.go /test.txt 20 func Test_main(t *testing.T) { 21 for _, toolchain := range []string{"cargo-wasi", "tinygo", "zig", "zig-cc"} { 22 toolchain := toolchain 23 t.Run(toolchain, func(t *testing.T) { 24 t.Setenv("TOOLCHAIN", toolchain) 25 stdout, stderr := maintester.TestMain(t, main, "cat", "/test.txt") 26 require.Equal(t, "", stderr) 27 require.Equal(t, "greet filesystem\n", stdout) 28 }) 29 } 30 } 31 32 // Test_cli ensures the following will work: 33 // 34 // go run github.com/tetratelabs/wazero/cmd/wazero run -mount=testdata:/ cat.wasm /test.txt 35 func Test_cli(t *testing.T) { 36 tests := []struct { 37 toolchain string 38 wasm []byte 39 }{ 40 { 41 toolchain: "cargo-wasi", 42 wasm: catWasmCargoWasi, 43 }, 44 { 45 toolchain: "tinygo", 46 wasm: catWasmTinyGo, 47 }, 48 { 49 toolchain: "zig", 50 wasm: catWasmZig, 51 }, 52 { 53 toolchain: "zig-cc", 54 wasm: catWasmZigCc, 55 }, 56 } 57 58 for _, tc := range tests { 59 tt := tc 60 t.Run(tt.toolchain, func(t *testing.T) { 61 for _, testPath := range []string{"/test.txt", "/testcases/test.txt"} { 62 t.Run(testPath, func(t *testing.T) { 63 // Write out embedded files instead of accessing directly for docker cross-architecture tests. 64 wasmPath := filepath.Join(t.TempDir(), "cat.wasm") 65 require.NoError(t, os.WriteFile(wasmPath, tt.wasm, 0o755)) 66 67 testTxt, err := fs.ReadFile(catFS, "testdata/test.txt") 68 require.NoError(t, err) 69 testTxtPath := filepath.Join(t.TempDir(), "test.txt") 70 require.NoError(t, os.WriteFile(testTxtPath, testTxt, 0o755)) 71 72 // We can't invoke go run in our docker based cross-architecture tests. We do want to use 73 // otherwise so running unit tests normally does not require special build steps. 74 var cmdExe string 75 var cmdArgs []string 76 if cmdPath := os.Getenv("WAZEROCLI"); cmdPath != "" { 77 cmdExe = cmdPath 78 } else { 79 cmdExe = filepath.Join(runtime.GOROOT(), "bin", "go") 80 cmdArgs = []string{"run", "../../../cmd/wazero"} 81 } 82 83 cmdArgs = append(cmdArgs, "run", 84 fmt.Sprintf("-mount=%s:/", filepath.Dir(testTxtPath)), 85 fmt.Sprintf("-mount=%s:/testcases", filepath.Dir(testTxtPath)), 86 wasmPath, testPath) 87 88 stdOut := &bytes.Buffer{} 89 stdErr := &bytes.Buffer{} 90 cmd := exec.Command(cmdExe, cmdArgs...) 91 cmd.Stdout = stdOut 92 cmd.Stderr = stdErr 93 require.NoError(t, cmd.Run(), stdErr.String()) 94 require.Equal(t, "greet filesystem\n", stdOut.String()) 95 }) 96 } 97 }) 98 } 99 }