From 57b41ad766b3c4505672c12f058f10c7a132dd5b Mon Sep 17 00:00:00 2001 From: Gabriel Arakaki Giovanini Date: Sat, 24 Jun 2023 00:34:57 +0200 Subject: feat: Remove unnecessary function --- pkg/coroutine/coroutine.go | 33 +++++++++++++++++++++ pkg/coroutine/coroutine_test.go | 63 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 pkg/coroutine/coroutine.go create mode 100644 pkg/coroutine/coroutine_test.go (limited to 'pkg/coroutine') diff --git a/pkg/coroutine/coroutine.go b/pkg/coroutine/coroutine.go new file mode 100644 index 0000000..96d149e --- /dev/null +++ b/pkg/coroutine/coroutine.go @@ -0,0 +1,33 @@ +package coroutine + +import ( + "context" +) + +// WrapProcess wraps process into a go routine and make it cancelable through context +func WrapProcess[V any](ctx context.Context, fun func() (V, error)) (V, error) { + c := make(chan V) + e := make(chan error) + go func() { + defer close(c) + defer close(e) + + v, err := fun() + if err != nil { + e <- err + } else { + c <- v + } + }() + + select { + case <-ctx.Done(): + var zero V + return zero, ctx.Err() + case m := <-c: + return m, nil + case err := <-e: + var zero V + return zero, err + } +} diff --git a/pkg/coroutine/coroutine_test.go b/pkg/coroutine/coroutine_test.go new file mode 100644 index 0000000..e876ec3 --- /dev/null +++ b/pkg/coroutine/coroutine_test.go @@ -0,0 +1,63 @@ +//go:build unit + +package coroutine + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "git.sr.ht/~gabrielgio/img/pkg/testkit" +) + +var rError = errors.New("This is a error") + +func imediatReturn() (string, error) { + return "A string", nil +} + +func imediatErrorReturn() (string, error) { + return "", rError +} + +func haltedReturn() (string, error) { + time.Sleep(time.Hour) + return "", nil +} + +func TestImediatReturn(t *testing.T) { + ctx := context.Background() + v, err := WrapProcess(ctx, imediatReturn) + testkit.TestError(t, "WrapProcess", nil, err) + testkit.TestValue(t, "WrapProcess", "A string", v) +} + +func TestImediatErrorReturn(t *testing.T) { + ctx := context.Background() + v, err := WrapProcess(ctx, imediatErrorReturn) + testkit.TestError(t, "WrapProcess", rError, err) + testkit.TestValue(t, "WrapProcess", "", v) +} + +func TestHaltedReturn(t *testing.T) { + ctx := context.Background() + ctx, cancel := context.WithCancel(ctx) + + var ( + err error + wg sync.WaitGroup + ) + + wg.Add(1) + go func(err *error) { + defer wg.Done() + _, *err = WrapProcess(ctx, haltedReturn) + }(&err) + + cancel() + wg.Wait() + + testkit.TestError(t, "WrapProcess", context.Canceled, err) +} -- cgit v1.2.3