-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #23 from hurbcom/feature/add-thread-helper
add thread helper
- Loading branch information
Showing
3 changed files
with
88 additions
and
0 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} | ||
} |