|
| 1 | +// Copyright 2023 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +//go:build go1.20 |
| 6 | +// +build go1.20 |
| 7 | + |
| 8 | +package errgroup_test |
| 9 | + |
| 10 | +import ( |
| 11 | + "context" |
| 12 | + "errors" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "golang.org/x/sync/errgroup" |
| 16 | +) |
| 17 | + |
| 18 | +func TestCancelCause(t *testing.T) { |
| 19 | + errDoom := errors.New("group_test: doomed") |
| 20 | + |
| 21 | + cases := []struct { |
| 22 | + errs []error |
| 23 | + want error |
| 24 | + }{ |
| 25 | + {want: nil}, |
| 26 | + {errs: []error{nil}, want: nil}, |
| 27 | + {errs: []error{errDoom}, want: errDoom}, |
| 28 | + {errs: []error{errDoom, nil}, want: errDoom}, |
| 29 | + } |
| 30 | + |
| 31 | + for _, tc := range cases { |
| 32 | + g, ctx := errgroup.WithContext(context.Background()) |
| 33 | + |
| 34 | + for _, err := range tc.errs { |
| 35 | + err := err |
| 36 | + g.TryGo(func() error { return err }) |
| 37 | + } |
| 38 | + |
| 39 | + if err := g.Wait(); err != tc.want { |
| 40 | + t.Errorf("after %T.TryGo(func() error { return err }) for err in %v\n"+ |
| 41 | + "g.Wait() = %v; want %v", |
| 42 | + g, tc.errs, err, tc.want) |
| 43 | + } |
| 44 | + |
| 45 | + if tc.want == nil { |
| 46 | + tc.want = context.Canceled |
| 47 | + } |
| 48 | + |
| 49 | + if err := context.Cause(ctx); err != tc.want { |
| 50 | + t.Errorf("after %T.TryGo(func() error { return err }) for err in %v\n"+ |
| 51 | + "context.Cause(ctx) = %v; tc.want %v", |
| 52 | + g, tc.errs, err, tc.want) |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments