diff --git a/runtime.go b/runtime.go index 80232a94..c8548711 100644 --- a/runtime.go +++ b/runtime.go @@ -127,6 +127,9 @@ func NewRuntime(ctx context.Context) Runtime { // NewRuntimeWithConfig returns a runtime with the given configuration. func NewRuntimeWithConfig(ctx context.Context, rConfig RuntimeConfig) Runtime { + if ctx == nil { + ctx = context.Background() + } if v := ctx.Value(version.WazeroVersionKey{}); v == nil { ctx = context.WithValue(ctx, version.WazeroVersionKey{}, wazeroVersion) } diff --git a/runtime_test.go b/runtime_test.go index 22b41424..1d9b0ea9 100644 --- a/runtime_test.go +++ b/runtime_test.go @@ -22,16 +22,35 @@ var ( ) func TestNewRuntimeWithConfig_version(t *testing.T) { - cfg := NewRuntimeConfig().(*runtimeConfig) - oldNewEngine := cfg.newEngine - cfg.newEngine = func(ctx context.Context, features wasm.Features) wasm.Engine { - // Ensures that wazeroVersion is propagated to the engine. - v := ctx.Value(version.WazeroVersionKey{}) - require.NotNil(t, v) - require.Equal(t, wazeroVersion, v.(string)) - return oldNewEngine(ctx, features) + // Make sure nil ctx doesn't panic + tests := []struct { + name string + ctx context.Context + }{ + { + name: "not nil", + ctx: testCtx, + }, + { + name: "nil", + ctx: nil, + }, + } + for _, tc := range tests { + tt := tc + t.Run(tt.name, func(t *testing.T) { + cfg := NewRuntimeConfig().(*runtimeConfig) + oldNewEngine := cfg.newEngine + cfg.newEngine = func(ctx context.Context, features wasm.Features) wasm.Engine { + // Ensures that wazeroVersion is propagated to the engine. + v := ctx.Value(version.WazeroVersionKey{}) + require.NotNil(t, v) + require.Equal(t, wazeroVersion, v.(string)) + return oldNewEngine(ctx, features) + } + _ = NewRuntimeWithConfig(tt.ctx, cfg) + }) } - _ = NewRuntimeWithConfig(testCtx, cfg) } func TestRuntime_CompileModule(t *testing.T) {