github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/utils/stopper_test.go (about)

     1  /*
     2   * Copyright (C) 2017 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package utils
    19  
    20  import (
    21  	"errors"
    22  	"testing"
    23  
    24  	"github.com/stretchr/testify/assert"
    25  )
    26  
    27  func newFakeKiller(killReturnsError bool) *fakeKiller {
    28  	return &fakeKiller{
    29  		Killed:           false,
    30  		killReturnsError: killReturnsError,
    31  	}
    32  }
    33  
    34  type fakeKiller struct {
    35  	Killed           bool
    36  	killReturnsError bool
    37  }
    38  
    39  func (fk *fakeKiller) Kill() error {
    40  	fk.Killed = true
    41  	if fk.killReturnsError {
    42  		return errors.New("fake error")
    43  	}
    44  	return nil
    45  }
    46  
    47  func newFakeExiter() fakeExiter {
    48  	return fakeExiter{-1}
    49  }
    50  
    51  type fakeExiter struct {
    52  	LastCode int
    53  }
    54  
    55  func (fe *fakeExiter) Exit(code int) {
    56  	fe.LastCode = code
    57  }
    58  
    59  func TestNewStopper(t *testing.T) {
    60  	killer := newFakeKiller(false)
    61  	exiter := newFakeExiter()
    62  	stopper := newStopper(killer.Kill, exiter.Exit)
    63  	assert.NotNil(t, stopper)
    64  }
    65  
    66  func TestStopperExitsWithSuccessWhenKillerSucceeds(t *testing.T) {
    67  	exiter := newFakeExiter()
    68  	fakeKiller := newFakeKiller(false)
    69  
    70  	stopper := newStopper(fakeKiller.Kill, exiter.Exit)
    71  	stopper()
    72  
    73  	assert.Equal(t, 0, exiter.LastCode)
    74  	assert.True(t, fakeKiller.Killed)
    75  }
    76  
    77  func TestStopperExitsWithErrorWhenKillerFails(t *testing.T) {
    78  	exiter := newFakeExiter()
    79  	fakeKiller := newFakeKiller(true)
    80  
    81  	stopper := newStopper(fakeKiller.Kill, exiter.Exit)
    82  	stopper()
    83  
    84  	assert.Equal(t, 1, exiter.LastCode)
    85  	assert.True(t, fakeKiller.Killed)
    86  }