github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/utils/shutdowner_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/mock"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  type appStub struct {
    15  	mock.Mock
    16  }
    17  
    18  func newAppStub(t *testing.T) *appStub {
    19  	s := new(appStub)
    20  
    21  	t.Cleanup(func() { s.AssertExpectations(t) })
    22  
    23  	return s
    24  }
    25  
    26  func (s *appStub) Shutdown(ctx context.Context) error {
    27  	return s.Called().Error(0)
    28  }
    29  
    30  func TestShutdowner_ok(t *testing.T) {
    31  	s1 := newAppStub(t)
    32  	s2 := newAppStub(t)
    33  	s3 := newAppStub(t)
    34  
    35  	s1.On("Shutdown").Return(nil).Once()
    36  	s2.On("Shutdown").Return(nil).Once()
    37  	s3.On("Shutdown").Return(nil).Once()
    38  
    39  	group := NewGroupShutdown(s1, s2, s3)
    40  
    41  	err := group.Shutdown(context.Background())
    42  	require.NoError(t, err)
    43  }
    44  
    45  func TestShutdowner_return_errors(t *testing.T) {
    46  	s1 := newAppStub(t)
    47  	s2 := newAppStub(t)
    48  	s3 := newAppStub(t)
    49  
    50  	s1.On("Shutdown").Return(nil).Once()
    51  	s2.On("Shutdown").Return(errors.New("some-error")).Once()
    52  	s3.On("Shutdown").Return(nil).Once()
    53  
    54  	group := NewGroupShutdown(s1, s2, s3)
    55  
    56  	err := group.Shutdown(context.Background())
    57  	require.EqualError(t, err, "1 error occurred:\n\t* some-error\n\n")
    58  }
    59  
    60  func TestShutdowner_are_run_in_parallel(t *testing.T) {
    61  	s1 := newAppStub(t)
    62  	s2 := newAppStub(t)
    63  	s3 := newAppStub(t)
    64  
    65  	s1.On("Shutdown").Return(nil).Once().WaitUntil(time.After(5 * time.Millisecond))
    66  	s2.On("Shutdown").Return(nil).Once().WaitUntil(time.After(5 * time.Millisecond))
    67  	s3.On("Shutdown").Return(nil).Once().WaitUntil(time.After(5 * time.Millisecond))
    68  
    69  	group := NewGroupShutdown(s1, s2, s3)
    70  
    71  	start := time.Now()
    72  	err := group.Shutdown(context.Background())
    73  	require.NoError(t, err)
    74  	assert.WithinDuration(t, time.Now(), start, 10*time.Millisecond)
    75  }