github.com/xmidt-org/webpa-common@v1.11.9/server/signalWait_test.go (about)

     1  package server
     2  
     3  import (
     4  	"os"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/xmidt-org/webpa-common/logging"
    11  )
    12  
    13  func testSignalWaitBasic(t *testing.T) {
    14  	var (
    15  		assert  = assert.New(t)
    16  		logger  = logging.NewTestLogger(nil, t)
    17  		signals = make(chan os.Signal)
    18  
    19  		started  = new(sync.WaitGroup)
    20  		finished = make(chan os.Signal)
    21  	)
    22  
    23  	defer close(signals)
    24  	started.Add(1)
    25  	go func() {
    26  		started.Done()
    27  		finished <- SignalWait(logger, signals, os.Kill)
    28  	}()
    29  
    30  	started.Wait()
    31  
    32  	signals <- os.Interrupt
    33  	select {
    34  	case <-finished:
    35  		assert.Fail("os.Interrupt should not have ended SignalWait")
    36  	default:
    37  		// passing
    38  	}
    39  
    40  	signals <- os.Kill
    41  	select {
    42  	case actual := <-finished:
    43  		assert.Equal(os.Kill, actual)
    44  	case <-time.After(10 * time.Second):
    45  		assert.Fail("SignalWait did not complete within the timeout")
    46  	}
    47  }
    48  
    49  func testSignalWaitForever(t *testing.T) {
    50  	var (
    51  		assert  = assert.New(t)
    52  		logger  = logging.NewTestLogger(nil, t)
    53  		signals = make(chan os.Signal)
    54  
    55  		started  = new(sync.WaitGroup)
    56  		finished = make(chan os.Signal)
    57  	)
    58  
    59  	started.Add(1)
    60  	go func() {
    61  		started.Done()
    62  		finished <- SignalWait(logger, signals)
    63  	}()
    64  
    65  	started.Wait()
    66  	for _, s := range []os.Signal{os.Kill, os.Interrupt} {
    67  		signals <- s
    68  		select {
    69  		case <-finished:
    70  			assert.Fail("SignalWait should not have finished")
    71  		default:
    72  			// passing
    73  		}
    74  	}
    75  
    76  	close(signals)
    77  	select {
    78  	case actual := <-finished:
    79  		assert.Nil(actual)
    80  	case <-time.After(10 * time.Second):
    81  		assert.Fail("SignalWait did not complete within the timeout")
    82  	}
    83  }
    84  
    85  func TestSignalWait(t *testing.T) {
    86  	t.Run("Basic", testSignalWaitBasic)
    87  	t.Run("WaitForever", testSignalWaitForever)
    88  }