wa-lang.org/wazero@v1.0.2/imports/wasi_snapshot_preview1/usage_test.go (about)

     1  package wasi_snapshot_preview1_test
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	_ "embed"
     7  	"testing"
     8  
     9  	"wa-lang.org/wazero"
    10  	"wa-lang.org/wazero/imports/wasi_snapshot_preview1"
    11  	"wa-lang.org/wazero/internal/testing/require"
    12  )
    13  
    14  // wasiArg was compiled from testdata/wasi_arg.wat
    15  //
    16  //go:embed testdata/wasi_arg.wasm
    17  var wasiArg []byte
    18  
    19  func TestInstantiateModule(t *testing.T) {
    20  	ctx := context.Background()
    21  
    22  	r := wazero.NewRuntime(ctx)
    23  	defer r.Close(ctx)
    24  
    25  	var stdout bytes.Buffer
    26  
    27  	// Configure WASI to write stdout to a buffer, so that we can verify it later.
    28  	sys := wazero.NewModuleConfig().WithStdout(&stdout)
    29  	wasi_snapshot_preview1.MustInstantiate(ctx, r)
    30  
    31  	compiled, err := r.CompileModule(ctx, wasiArg)
    32  	require.NoError(t, err)
    33  
    34  	// Re-use the same module many times.
    35  	tests := []string{"a", "b", "c"}
    36  
    37  	for _, tt := range tests {
    38  		tc := tt
    39  		mod, err := r.InstantiateModule(ctx, compiled, sys.WithArgs(tc).WithName(tc))
    40  		require.NoError(t, err)
    41  
    42  		// Ensure the scoped configuration applied. As the args are null-terminated, we append zero (NUL).
    43  		require.Equal(t, append([]byte(tc), 0), stdout.Bytes())
    44  
    45  		stdout.Reset()
    46  		require.NoError(t, mod.Close(ctx))
    47  	}
    48  }