Debian Codegraph @

imports/wasi_snapshot_preview1/wasi_snapshot_preview1_test.go

raw symbols SCIP
1 package wasi_snapshot_preview1_test
2
3 import (
4 "context"
5 "fmt"
6 "os"
7 "os/exec"
8 "path"
9 "testing"
10 "time"
11
12 "github.com/tetratelabs/wazero"
13 )
14
15 func TestMain(m *testing.M) {
16 var err error
17 if wasmGo, err = compileWasip1Wasm(); err != nil {
18 println("go: skipping due compilation error:", err)
19 }
20 os.Exit(m.Run())
21 }
22
23 // runtimeCfg is a shared runtime configuration for tests within this package to reduce the compilation time of the binary.
24 var runtimeCfg = wazero.NewRuntimeConfig().WithCompilationCache(wazero.NewCompilationCache())
25
26 // compileWasip1Wasm allows us to generate a binary with runtime.GOOS=wasip1
27 // and runtime.GOARCH=wasm. This intentionally does so on-demand, because the
28 // wasm is too big to check in.
29 func compileWasip1Wasm() ([]byte, error) {
30 // Prepare the working directory.
31 workdir, err := os.MkdirTemp("", "wasi")
32 if err != nil {
33 return nil, err
34 }
35 defer os.RemoveAll(workdir)
36
37 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
38 defer cancel()
39
40 binPath := path.Join(workdir, "wasi.wasm")
41 cmd := exec.CommandContext(ctx, "go", "build", "-o", binPath, ".") //nolint:gosec
42 cmd.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm")
43 cmd.Dir = "testdata/go"
44 out, err := cmd.CombinedOutput()
45 if err != nil {
46 return nil, fmt.Errorf("couldn't compile %s: %w", string(out), err)
47 }
48
49 bin, err := os.ReadFile(binPath) //nolint:gosec
50 if err != nil {
51 return nil, err
52 }
53
54 // Proactively compile the binary to reduce the test time.
55 r := wazero.NewRuntimeWithConfig(context.Background(), runtimeCfg)
56 defer r.Close(context.Background())
57 _, err = r.CompileModule(context.Background(), bin)
58 return bin, err
59 }