github.com/anjalikarhana/fabric@v2.1.1+incompatible/orderer/common/server/sched_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package server
     8  
     9  import (
    10  	"sync"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/onsi/gomega"
    15  	"github.com/stretchr/testify/assert"
    16  )
    17  
    18  func TestExponentialDuration(t *testing.T) {
    19  	t.Parallel()
    20  	exp := exponentialDurationSeries(time.Millisecond*100, time.Second)
    21  	prev := exp()
    22  	for i := 0; i < 3; i++ {
    23  		n := exp()
    24  		assert.Equal(t, prev*2, n)
    25  		prev = n
    26  		assert.True(t, n < time.Second)
    27  	}
    28  
    29  	for i := 0; i < 10; i++ {
    30  		assert.Equal(t, time.Second, exp())
    31  	}
    32  }
    33  
    34  func TestTicker(t *testing.T) {
    35  	t.Parallel()
    36  	everyMillis := func() time.Duration {
    37  		return time.Millisecond
    38  	}
    39  
    40  	t.Run("Stop ticker serially", func(t *testing.T) {
    41  		ticker := newTicker(everyMillis)
    42  		for i := 0; i < 10; i++ {
    43  			<-ticker.C
    44  		}
    45  
    46  		ticker.stop()
    47  		// Ensure the ticker channel is closed once stop() is called.
    48  		gt := gomega.NewGomegaWithT(t)
    49  		gt.Eventually(func() bool {
    50  			_, ok := <-ticker.C
    51  			return ok
    52  		}).Should(gomega.BeFalse())
    53  	})
    54  
    55  	t.Run("Stop ticker concurrently", func(t *testing.T) {
    56  		ticker := newTicker(func() time.Duration {
    57  			return time.Millisecond
    58  		})
    59  
    60  		var tickerStopped sync.WaitGroup
    61  		tickerStopped.Add(1)
    62  
    63  		go func() {
    64  			defer tickerStopped.Done()
    65  			time.Sleep(time.Millisecond * 50)
    66  			ticker.stop()
    67  			<-ticker.C
    68  		}()
    69  
    70  		tickerStopped.Wait()
    71  		_, ok := <-ticker.C
    72  		assert.False(t, ok)
    73  
    74  	})
    75  
    76  }