github.com/cilium/cilium@v1.16.2/pkg/revert/revert_test.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package revert
     5  
     6  import (
     7  	"errors"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestRevertStack(t *testing.T) {
    14  	expectedContent := []string{"lmao", "ayy", "bar", "foo"}
    15  	content := make([]string, 0, 4)
    16  	rStack := RevertStack{}
    17  
    18  	rStack.Push(func() error {
    19  		content = append(content, "foo")
    20  		return nil
    21  	})
    22  	rStack.Push(func() error {
    23  		content = append(content, "bar")
    24  		return nil
    25  	})
    26  	rStack.Push(func() error {
    27  		content = append(content, "ayy")
    28  		return nil
    29  	})
    30  	rStack.Push(func() error {
    31  		content = append(content, "lmao")
    32  		return nil
    33  	})
    34  
    35  	err := rStack.Revert()
    36  	require.NoError(t, err)
    37  
    38  	require.Equal(t, expectedContent, content)
    39  }
    40  
    41  func TestRevertStackError(t *testing.T) {
    42  	var firstFuncCalled, secondFuncCalled, thirdFuncCalled bool
    43  	rStack := RevertStack{}
    44  
    45  	rStack.Push(func() error {
    46  		firstFuncCalled = true
    47  		return nil
    48  	})
    49  	rStack.Push(func() error {
    50  		secondFuncCalled = true
    51  		return errors.New("2nd function failed")
    52  	})
    53  	rStack.Push(func() error {
    54  		thirdFuncCalled = true
    55  		return nil
    56  	})
    57  
    58  	err := rStack.Revert()
    59  	require.Error(t, err)
    60  	require.Contains(t, err.Error(), "failed to execute revert function; skipping 1 revert functions: 2nd function failed")
    61  
    62  	require.Equal(t, firstFuncCalled, false)
    63  	require.Equal(t, secondFuncCalled, true)
    64  	require.Equal(t, thirdFuncCalled, true)
    65  }