wa-lang.org/wazero@v1.0.2/namespace_test.go (about)

     1  package wazero
     2  
     3  import (
     4  	_ "embed"
     5  	"testing"
     6  
     7  	"wa-lang.org/wazero/internal/testing/require"
     8  )
     9  
    10  // TestRuntime_Namespace ensures namespaces are independent.
    11  func TestRuntime_Namespace(t *testing.T) {
    12  	r := NewRuntime(testCtx)
    13  	defer r.Close(testCtx)
    14  
    15  	// Compile a module to add to the runtime
    16  	compiled, err := r.NewHostModuleBuilder("env").Compile(testCtx)
    17  	require.NoError(t, err)
    18  
    19  	// Instantiate "env" into the runtime default namespace (base case)
    20  	require.Nil(t, r.Module("env"))
    21  	m1, err := r.InstantiateModule(testCtx, compiled, NewModuleConfig())
    22  	require.NoError(t, err)
    23  	require.Equal(t, m1, r.Module("env"))
    24  
    25  	// NewNamespace does not inherit modules in the default namespace
    26  	ns1 := r.NewNamespace(testCtx)
    27  	require.Nil(t, ns1.Module("env"))
    28  
    29  	// Ensure this namespace has a new instance of "env"
    30  	m2, err := ns1.InstantiateModule(testCtx, compiled, NewModuleConfig())
    31  	require.NoError(t, err)
    32  	require.NotSame(t, m1, m2)
    33  
    34  	// Ensure the next namespace is similarly independent.
    35  	ns2 := r.NewNamespace(testCtx)
    36  	m3, err := ns2.InstantiateModule(testCtx, compiled, NewModuleConfig())
    37  	require.NoError(t, err)
    38  	require.NotSame(t, m1, m3)
    39  	require.NotSame(t, m2, m3)
    40  
    41  	// Ensure we can't re-instantiate the same module multiple times.
    42  	_, err = ns2.InstantiateModule(testCtx, compiled, NewModuleConfig())
    43  	require.EqualError(t, err, "module[env] has already been instantiated")
    44  
    45  	// Ensure we can instantiate the same module multiple times.
    46  	m4, err := ns2.InstantiateModule(testCtx, compiled, NewModuleConfig().WithName("env2"))
    47  	require.NoError(t, err)
    48  	require.NotSame(t, m3, m4)
    49  
    50  	// Ensure closing one namespace doesn't affect another
    51  	require.NoError(t, ns2.Close(testCtx))
    52  	require.Nil(t, ns2.Module("env"))
    53  	require.Nil(t, ns2.Module("env2"))
    54  	require.Equal(t, m1, r.Module("env"))
    55  	require.Equal(t, m2, ns1.Module("env"))
    56  
    57  	// Ensure closing the Runtime closes all namespaces
    58  	require.NoError(t, r.Close(testCtx))
    59  	require.Nil(t, r.Module("env"))
    60  	require.Nil(t, ns1.Module("env"))
    61  }