github.com/status-im/status-go@v1.1.0/services/wallet/async/async_test.go (about)

     1  package async
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestAtomicGroupTerminatesOnOneCommandFailed(t *testing.T) {
    13  	ctx := context.Background()
    14  	group := NewAtomicGroup(ctx)
    15  
    16  	err := errors.New("error")
    17  	group.Add(func(ctx context.Context) error {
    18  		return err // failure
    19  	})
    20  	group.Add(func(ctx context.Context) error {
    21  		<-ctx.Done()
    22  		return nil
    23  	})
    24  
    25  	group.Wait()
    26  	require.Equal(t, err, group.Error())
    27  }
    28  
    29  func TestAtomicGroupWaitsAllToFinish(t *testing.T) {
    30  	ctx := context.Background()
    31  	group := NewAtomicGroup(ctx)
    32  
    33  	finished := false
    34  	group.Add(func(ctx context.Context) error {
    35  		time.Sleep(1 * time.Millisecond)
    36  		return nil // success
    37  	})
    38  	group.Add(func(ctx context.Context) error {
    39  		for {
    40  			select {
    41  			case <-ctx.Done():
    42  				return nil
    43  			case <-time.After(3 * time.Millisecond):
    44  				finished = true
    45  				return nil
    46  			}
    47  		}
    48  	})
    49  
    50  	group.Wait()
    51  	require.True(t, finished)
    52  }