Skip to content

Commit

Permalink
add context helpers (#3)
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Goodman <[email protected]>
  • Loading branch information
wagoodman authored Sep 26, 2024
1 parent f275c2c commit 0345bfc
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
17 changes: 17 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package sync

import "context"

type executorKey struct{}

func ContextExecutor(ctx context.Context) Executor {
executor, ok := ctx.Value(executorKey{}).(Executor)
if !ok {
return sequentialExecutor{}
}
return executor
}

func SetContextExecutor(ctx context.Context, executor Executor) context.Context {
return context.WithValue(ctx, executorKey{}, executor)
}
29 changes: 29 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package sync

import (
"context"
"testing"

"github.com/stretchr/testify/require"
)

func TestContextExecutor(t *testing.T) {
t.Run("WithExecutorInContext", func(t *testing.T) {
executor := NewExecutor(1)
ctx := SetContextExecutor(context.Background(), executor)

result := ContextExecutor(ctx)

require.NotNil(t, result)
require.IsType(t, &boundedExecutor{}, result)
})

t.Run("WithoutExecutorInContext", func(t *testing.T) {
ctx := context.Background()

result := ContextExecutor(ctx)

require.NotNil(t, result)
require.IsType(t, sequentialExecutor{}, result)
})
}

0 comments on commit 0345bfc

Please sign in to comment.