github.com/moby/docker@v26.1.3+incompatible/internal/cleanups/composite_test.go (about)

     1  package cleanups
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"testing"
     8  
     9  	"gotest.tools/v3/assert"
    10  	is "gotest.tools/v3/assert/cmp"
    11  )
    12  
    13  func TestCall(t *testing.T) {
    14  	c := Composite{}
    15  	var err1 = errors.New("error1")
    16  	var err2 = errors.New("error2")
    17  	var errX = errors.New("errorX")
    18  	var errY = errors.New("errorY")
    19  	var errZ = errors.New("errorZ")
    20  	var errYZ = errors.Join(errY, errZ)
    21  
    22  	c.Add(func(ctx context.Context) error {
    23  		return err1
    24  	})
    25  	c.Add(func(ctx context.Context) error {
    26  		return nil
    27  	})
    28  	c.Add(func(ctx context.Context) error {
    29  		return fmt.Errorf("something happened: %w", err2)
    30  	})
    31  	c.Add(func(ctx context.Context) error {
    32  		return errors.Join(errX, fmt.Errorf("joined: %w", errYZ))
    33  	})
    34  
    35  	err := c.Call(context.Background())
    36  
    37  	errs := err.(interface{ Unwrap() []error }).Unwrap()
    38  
    39  	assert.Check(t, is.ErrorContains(err, err1.Error()))
    40  	assert.Check(t, is.ErrorContains(err, err2.Error()))
    41  	assert.Check(t, is.ErrorContains(err, errX.Error()))
    42  	assert.Check(t, is.ErrorContains(err, errY.Error()))
    43  	assert.Check(t, is.ErrorContains(err, errZ.Error()))
    44  	assert.Check(t, is.ErrorContains(err, "something happened: "+err2.Error()))
    45  
    46  	t.Logf(err.Error())
    47  	assert.Assert(t, is.Len(errs, 3))
    48  
    49  	// Cleanups executed in reverse order.
    50  	assert.Check(t, is.ErrorIs(errs[2], err1))
    51  	assert.Check(t, is.ErrorIs(errs[1], err2))
    52  	assert.Check(t, is.ErrorIs(errs[0], errX))
    53  	assert.Check(t, is.ErrorIs(errs[0], errYZ))
    54  }