github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/utils/async/errgroup_test.go (about)

     1  // Copyright 2020 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package async
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  	"testing"
    21  
    22  	"github.com/stretchr/testify/assert"
    23  	"golang.org/x/sync/errgroup"
    24  )
    25  
    26  func TestGoWithCancel(t *testing.T) {
    27  	t.Run("NilError", func(t *testing.T) {
    28  		eg, ctx := errgroup.WithContext(context.Background())
    29  		_ = GoWithCancel(ctx, eg, func(ctx context.Context) error {
    30  			return nil
    31  		})
    32  		assert.NoError(t, eg.Wait())
    33  	})
    34  	t.Run("NonNilError", func(t *testing.T) {
    35  		eg, ctx := errgroup.WithContext(context.Background())
    36  		_ = GoWithCancel(ctx, eg, func(ctx context.Context) error {
    37  			return errors.New("there was an error")
    38  		})
    39  		assert.Error(t, eg.Wait())
    40  	})
    41  	t.Run("CancelNoError", func(t *testing.T) {
    42  		eg, ctx := errgroup.WithContext(context.Background())
    43  		cancel := GoWithCancel(ctx, eg, func(ctx context.Context) error {
    44  			<-ctx.Done()
    45  			return ctx.Err()
    46  		})
    47  		cancel()
    48  		assert.NoError(t, eg.Wait())
    49  	})
    50  	t.Run("CancelParentError", func(t *testing.T) {
    51  		parent, cancel := context.WithCancel(context.Background())
    52  		eg, ctx := errgroup.WithContext(parent)
    53  		_ = GoWithCancel(ctx, eg, func(ctx context.Context) error {
    54  			<-ctx.Done()
    55  			return ctx.Err()
    56  		})
    57  		cancel()
    58  		assert.Error(t, eg.Wait())
    59  	})
    60  }