Skip to content

Commit

Permalink
Merge pull request #23 from hurbcom/feature/add-thread-helper
Browse files Browse the repository at this point in the history
add thread helper
  • Loading branch information
luis fernando fontoura spaniol authored Mar 3, 2021
2 parents ac9fb5a + 30ea67f commit 34ef32e
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions lib/thread.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package lib

import (
"context"

"golang.org/x/sync/errgroup"
)

// ErrorGroup resolves all go routines. It fails at first error encountered
// warning: Creating goroutines in the args will cause them to run in background
func ErrorGroup(ctx context.Context, args ...func() error) error {
g, _ := errgroup.WithContext(ctx)

for _, fn := range args {
g.Go(fn)
}

if err := g.Wait(); err != nil {
return err
}

return nil
}
56 changes: 56 additions & 0 deletions lib/thread_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package lib

import (
"context"
"errors"
"testing"
)

func TestErrorGroup(t *testing.T) {
type args struct {
ctx context.Context
args []func() error
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "Should run successfully when all go routines complete successfully",
args: args{
ctx: context.Background(),
args: []func() error{
func() error {
return nil
},
func() error {
return nil
},
},
},
},
{
name: "Should fail when first go routine fails",
args: args{
ctx: context.Background(),
args: []func() error{
func() error {
return errors.New("Oops, you received an error")
},
func() error {
return nil
},
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := ErrorGroup(tt.args.ctx, tt.args.args...); (err != nil) != tt.wantErr {
t.Errorf("ErrorGroup() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

0 comments on commit 34ef32e

Please sign in to comment.