github.com/pvitto98/fabric@v2.1.1+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 TestSemaphoreAcquireBlocking(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 TestSemaphoreAcquireContextError(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 TestSemaphoreTryAcquireBufferFull(t *testing.T) {
    61  	gt := NewGomegaWithT(t)
    62  
    63  	sema := semaphore.New(5)
    64  	for i := 0; i < 5; i++ {
    65  		gt.Expect(t, true, sema.TryAcquire())
    66  	}
    67  
    68  	gt.Expect(t, false, sema.TryAcquire())
    69  }
    70  
    71  func TestSemaphoreReleaseTooMany(t *testing.T) {
    72  	sema := semaphore.New(1)
    73  	assert.PanicsWithValue(t, "semaphore buffer is empty", func() { sema.Release() })
    74  }