github.com/yacovm/fabric@v2.0.0-alpha.0.20191128145320-c5d4087dc723+incompatible/common/semaphore/semaphore_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package semaphore_test
     8  
     9  import (
    10  	"context"
    11  	"testing"
    12  
    13  	"github.com/hyperledger/fabric/common/semaphore"
    14  	. "github.com/onsi/gomega"
    15  	"github.com/stretchr/testify/assert"
    16  )
    17  
    18  func TestNewSemaphorePanic(t *testing.T) {
    19  	assert.PanicsWithValue(t, "permits must be greater than 0", func() { semaphore.New(0) })
    20  }
    21  
    22  func TestSemaphoreBlocking(t *testing.T) {
    23  	gt := NewGomegaWithT(t)
    24  
    25  	sema := semaphore.New(5)
    26  	for i := 0; i < 5; i++ {
    27  		err := sema.Acquire(context.Background())
    28  		gt.Expect(err).NotTo(HaveOccurred())
    29  	}
    30  
    31  	done := make(chan struct{})
    32  	go func() {
    33  		err := sema.Acquire(context.Background())
    34  		gt.Expect(err).NotTo(HaveOccurred())
    35  
    36  		close(done)
    37  		sema.Release()
    38  	}()
    39  
    40  	gt.Consistently(done).ShouldNot(BeClosed())
    41  	sema.Release()
    42  	gt.Eventually(done).Should(BeClosed())
    43  }
    44  
    45  func TestSemaphoreContextError(t *testing.T) {
    46  	gt := NewGomegaWithT(t)
    47  
    48  	sema := semaphore.New(1)
    49  	err := sema.Acquire(context.Background())
    50  	gt.Expect(err).NotTo(HaveOccurred())
    51  
    52  	ctx, cancel := context.WithCancel(context.Background())
    53  	cancel()
    54  	errCh := make(chan error, 1)
    55  	go func() { errCh <- sema.Acquire(ctx) }()
    56  
    57  	gt.Eventually(errCh).Should(Receive(Equal(context.Canceled)))
    58  }
    59  
    60  func TestSemaphoreReleaseTooMany(t *testing.T) {
    61  	sema := semaphore.New(1)
    62  	assert.PanicsWithValue(t, "semaphore buffer is empty", func() { sema.Release() })
    63  }