github.com/bananabytelabs/wazero@v0.0.0-20240105073314-54b22a776da8/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  	"github.com/bananabytelabs/wazero"
    10  	"github.com/bananabytelabs/wazero/imports/wasi_snapshot_preview1"
    11  	"github.com/bananabytelabs/wazero/internal/fstest"
    12  	"github.com/bananabytelabs/wazero/internal/testing/require"
    13  )
    14  
    15  // pringArgsWasm was compiled from testdata/wasi_arg.wat
    16  //
    17  //go:embed testdata/print_args.wasm
    18  var pringArgsWasm []byte
    19  
    20  func TestInstantiateModule(t *testing.T) {
    21  	ctx := context.Background()
    22  
    23  	r := wazero.NewRuntime(ctx)
    24  	defer r.Close(ctx)
    25  
    26  	var stdout bytes.Buffer
    27  
    28  	// Configure WASI to write stdout to a buffer, so that we can verify it later.
    29  	sys := wazero.NewModuleConfig().WithStdout(&stdout)
    30  	wasi_snapshot_preview1.MustInstantiate(ctx, r)
    31  
    32  	compiled, err := r.CompileModule(ctx, pringArgsWasm)
    33  	require.NoError(t, err)
    34  
    35  	// Re-use the same module many times.
    36  	tests := []string{"a", "b", "c"}
    37  
    38  	for _, tt := range tests {
    39  		tc := tt
    40  		mod, err := r.InstantiateModule(ctx, compiled, sys.WithArgs(tc).WithName(tc))
    41  		require.NoError(t, err)
    42  
    43  		// Ensure the scoped configuration applied. As the args are null-terminated, we append zero (NUL).
    44  		require.Equal(t, append([]byte(tc), 0), stdout.Bytes())
    45  
    46  		stdout.Reset()
    47  		require.NoError(t, mod.Close(ctx))
    48  	}
    49  }
    50  
    51  // printPrestatDirname was compiled from testdata/print_prestat_dirname.wat
    52  //
    53  //go:embed testdata/print_prestat_dirname.wasm
    54  var printPrestatDirname []byte
    55  
    56  // TestInstantiateModule_Prestat
    57  func TestInstantiateModule_Prestat(t *testing.T) {
    58  	ctx := context.Background()
    59  
    60  	r := wazero.NewRuntime(ctx)
    61  	defer r.Close(ctx)
    62  
    63  	var stdout bytes.Buffer
    64  
    65  	wasi_snapshot_preview1.MustInstantiate(ctx, r)
    66  
    67  	_, err := r.InstantiateWithConfig(ctx, printPrestatDirname, wazero.NewModuleConfig().
    68  		WithStdout(&stdout).
    69  		WithFSConfig(wazero.NewFSConfig().WithFSMount(fstest.FS, "/wazero")))
    70  	require.NoError(t, err)
    71  
    72  	require.Equal(t, "/wazero", stdout.String())
    73  }