github.com/chenbh/concourse/v6@v6.4.2/atc/wrappa/pool_test.go (about)

     1  package wrappa_test
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/chenbh/concourse/v6/atc/wrappa"
     7  	. "github.com/onsi/ginkgo"
     8  	. "github.com/onsi/gomega"
     9  )
    10  
    11  var _ = Describe("Pool", func() {
    12  	It("can acquire a resource", func() {
    13  		pool := pool(1)
    14  
    15  		Expect(pool.TryAcquire()).To(BeTrue())
    16  	})
    17  
    18  	It("fails to acquire a resource when the limit is reached", func() {
    19  		pool := pool(1)
    20  
    21  		pool.TryAcquire()
    22  		Expect(pool.TryAcquire()).To(BeFalse())
    23  	})
    24  
    25  	It("can acquire a resource after releasing", func() {
    26  		pool := pool(1)
    27  
    28  		pool.TryAcquire()
    29  		pool.Release()
    30  		Expect(pool.TryAcquire()).To(BeTrue())
    31  	})
    32  
    33  	It("can acquire multiple resources", func() {
    34  		pool := pool(2)
    35  
    36  		pool.TryAcquire()
    37  		Expect(pool.TryAcquire()).To(BeTrue())
    38  	})
    39  
    40  	It("cannot release more resources than are held", func() {
    41  		pool := pool(1)
    42  
    43  		Expect(pool.Release).To(Panic())
    44  	})
    45  
    46  	It("cannot acquire multiple resources simultaneously", func() {
    47  		pool := pool(100)
    48  		failed := false
    49  
    50  		doInParallel(101, func() {
    51  			if !pool.TryAcquire() {
    52  				failed = true
    53  			}
    54  		})
    55  
    56  		Expect(failed).To(BeTrue())
    57  	})
    58  })
    59  
    60  func pool(size int) wrappa.Pool {
    61  	return wrappa.NewPool(size)
    62  }
    63  
    64  func doInParallel(numGoroutines int, thingToDo func()) {
    65  	var wg sync.WaitGroup
    66  	wg.Add(numGoroutines)
    67  	for i := 0; i < numGoroutines; i++ {
    68  		go func() {
    69  			thingToDo()
    70  			wg.Done()
    71  		}()
    72  	}
    73  	wg.Wait()
    74  }