2020-06-29 19:21:03 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2022-06-18 07:11:37 +00:00
|
|
|
"fmt"
|
2020-06-29 19:21:03 +00:00
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestErrGroup(t *testing.T) {
|
2024-07-12 19:57:56 +00:00
|
|
|
f := func(errs []error, resultExpected string) {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
eg := &ErrGroup{}
|
|
|
|
for _, err := range errs {
|
2020-06-29 19:21:03 +00:00
|
|
|
eg.Add(err)
|
|
|
|
}
|
2024-07-12 19:57:56 +00:00
|
|
|
if len(errs) == 0 {
|
2020-06-29 19:21:03 +00:00
|
|
|
if eg.Err() != nil {
|
|
|
|
t.Fatalf("expected to get nil error")
|
|
|
|
}
|
2024-07-12 19:57:56 +00:00
|
|
|
return
|
2020-06-29 19:21:03 +00:00
|
|
|
}
|
|
|
|
if eg.Err() == nil {
|
|
|
|
t.Fatalf("expected to get non-nil error")
|
|
|
|
}
|
2024-07-12 19:57:56 +00:00
|
|
|
result := eg.Error()
|
|
|
|
if result != resultExpected {
|
|
|
|
t.Fatalf("unexpected result\ngot\n%v\nwant\n%v", result, resultExpected)
|
2020-06-29 19:21:03 +00:00
|
|
|
}
|
|
|
|
}
|
2024-07-12 19:57:56 +00:00
|
|
|
|
|
|
|
f(nil, "")
|
|
|
|
f([]error{errors.New("timeout")}, "errors(1): timeout")
|
|
|
|
f([]error{errors.New("timeout"), errors.New("deadline")}, "errors(2): timeout\ndeadline")
|
2020-06-29 19:21:03 +00:00
|
|
|
}
|
2022-06-18 07:11:37 +00:00
|
|
|
|
|
|
|
// TestErrGroupConcurrent supposed to test concurrent
|
|
|
|
// use of error group.
|
|
|
|
// Should be executed with -race flag
|
2023-09-01 07:34:16 +00:00
|
|
|
func TestErrGroupConcurrent(_ *testing.T) {
|
2022-06-18 07:11:37 +00:00
|
|
|
eg := new(ErrGroup)
|
|
|
|
|
|
|
|
const writersN = 4
|
|
|
|
payload := make(chan error, writersN)
|
|
|
|
for i := 0; i < writersN; i++ {
|
|
|
|
go func() {
|
|
|
|
for err := range payload {
|
|
|
|
eg.Add(err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
const iterations = 500
|
|
|
|
for i := 0; i < iterations; i++ {
|
|
|
|
payload <- fmt.Errorf("error %d", i)
|
|
|
|
if i%10 == 0 {
|
|
|
|
_ = eg.Err()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
close(payload)
|
|
|
|
}
|