mirror of
https://github.com/VictoriaMetrics/VictoriaMetrics.git
synced 2024-12-30 07:40:06 +01:00
43fc1183b9
This makes test code more clear and reduces the number of code lines by 500.
This also simplifies debugging tests. See https://itnext.io/f-tests-as-a-replacement-for-table-driven-tests-in-go-8814a8b19e9e
While at it, consistently use t.Fatal* instead of t.Error* across tests, since t.Error*
requires more boilerplate code, which can result in additional bugs inside tests.
While t.Error* allows writing logging errors for the same, this doesn't simplify fixing
broken tests most of the time.
This is a follow-up for a9525da8a4
62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"testing"
|
|
)
|
|
|
|
func TestErrGroup(t *testing.T) {
|
|
f := func(errs []error, resultExpected string) {
|
|
t.Helper()
|
|
|
|
eg := &ErrGroup{}
|
|
for _, err := range errs {
|
|
eg.Add(err)
|
|
}
|
|
if len(errs) == 0 {
|
|
if eg.Err() != nil {
|
|
t.Fatalf("expected to get nil error")
|
|
}
|
|
return
|
|
}
|
|
if eg.Err() == nil {
|
|
t.Fatalf("expected to get non-nil error")
|
|
}
|
|
result := eg.Error()
|
|
if result != resultExpected {
|
|
t.Fatalf("unexpected result\ngot\n%v\nwant\n%v", result, resultExpected)
|
|
}
|
|
}
|
|
|
|
f(nil, "")
|
|
f([]error{errors.New("timeout")}, "errors(1): timeout")
|
|
f([]error{errors.New("timeout"), errors.New("deadline")}, "errors(2): timeout\ndeadline")
|
|
}
|
|
|
|
// TestErrGroupConcurrent supposed to test concurrent
|
|
// use of error group.
|
|
// Should be executed with -race flag
|
|
func TestErrGroupConcurrent(_ *testing.T) {
|
|
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)
|
|
}
|