github.com/iotexproject/iotex-core@v1.14.1-rc1/pkg/lifecycle/lifecycle_test.go (about)

     1  // Copyright (c) 2019 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package lifecycle
     7  
     8  import (
     9  	"context"
    10  	"testing"
    11  
    12  	"github.com/golang/mock/gomock"
    13  	"github.com/pkg/errors"
    14  	"github.com/stretchr/testify/assert"
    15  
    16  	"github.com/iotexproject/iotex-core/test/mock/mock_lifecycle"
    17  )
    18  
    19  func TestLifecycle(t *testing.T) {
    20  	mctrl := gomock.NewController(t)
    21  	defer mctrl.Finish()
    22  
    23  	ctx := context.Background()
    24  	m := mock_lifecycle.NewMockStartStopper(mctrl)
    25  	m.EXPECT().Start(gomock.Any()).Return(nil).Times(1)
    26  	m.EXPECT().Stop(gomock.Any()).Return(nil).Times(1)
    27  
    28  	var lc Lifecycle
    29  	lc.Add(m)
    30  	assert.Nil(t, lc.OnStart(ctx))
    31  	assert.Nil(t, lc.OnStop(ctx))
    32  }
    33  
    34  func TestLifecycleWithError(t *testing.T) {
    35  	mctrl := gomock.NewController(t)
    36  	defer mctrl.Finish()
    37  
    38  	ctx := context.Background()
    39  	m1 := mock_lifecycle.NewMockStartStopper(mctrl)
    40  	m1.EXPECT().Start(gomock.Any()).Return(nil).Times(1)
    41  	m1.EXPECT().Stop(gomock.Any()).Return(nil).Times(1)
    42  
    43  	err := errors.New("error")
    44  	m2 := mock_lifecycle.NewMockStartStopper(mctrl)
    45  	m2.EXPECT().Start(gomock.Any()).Return(nil).Times(1)
    46  	m2.EXPECT().Stop(gomock.Any()).Return(err).Times(1)
    47  
    48  	var lc Lifecycle
    49  	lc.AddModels(m1, m2)
    50  	assert.Nil(t, lc.OnStart(ctx))
    51  	assert.EqualError(t, lc.OnStop(ctx), err.Error())
    52  }