github.com/kaituanwang/hyperledger@v2.0.1+incompatible/core/scc/throttle_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package scc_test
     8  
     9  import (
    10  	"testing"
    11  
    12  	"github.com/hyperledger/fabric-chaincode-go/shim"
    13  	pb "github.com/hyperledger/fabric-protos-go/peer"
    14  	"github.com/hyperledger/fabric/core/scc"
    15  	"github.com/hyperledger/fabric/core/scc/mock"
    16  	. "github.com/onsi/gomega"
    17  )
    18  
    19  //go:generate counterfeiter -o mock/chaincode.go --fake-name Chaincode . chaincode
    20  //go:generate counterfeiter -o mock/selfdescribingsyscc.go --fake-name SelfDescribingSysCC . selfDescribingSysCC
    21  
    22  type chaincode interface{ shim.Chaincode }
    23  type selfDescribingSysCC interface{ scc.SelfDescribingSysCC } // prevent package cycle
    24  
    25  func TestThrottle(t *testing.T) {
    26  	gt := NewGomegaWithT(t)
    27  
    28  	runningCh := make(chan struct{}, 1)
    29  	doneCh := make(chan struct{})
    30  	chaincode := &mock.Chaincode{}
    31  	chaincode.InvokeStub = func(shim.ChaincodeStubInterface) pb.Response {
    32  		gt.Eventually(runningCh).Should(BeSent(struct{}{}))
    33  		<-doneCh
    34  		return pb.Response{}
    35  	}
    36  
    37  	sysCC := &mock.SelfDescribingSysCC{}
    38  	sysCC.ChaincodeReturns(chaincode)
    39  
    40  	// run invokes concurrently
    41  	throttled := scc.Throttle(5, sysCC).Chaincode()
    42  	for i := 0; i < 5; i++ {
    43  		go throttled.Invoke(nil)
    44  		gt.Eventually(runningCh).Should(Receive())
    45  	}
    46  	// invoke and ensure requet is delayed
    47  	go throttled.Invoke(nil)
    48  	gt.Consistently(runningCh).ShouldNot(Receive())
    49  
    50  	// release one of the pending invokes and see that
    51  	// the delayed request is started
    52  	gt.Eventually(doneCh).Should(BeSent(struct{}{}))
    53  	gt.Eventually(runningCh).Should(Receive())
    54  
    55  	// cleanup
    56  	close(doneCh)
    57  }
    58  
    59  func TestThrottledChaincode(t *testing.T) {
    60  	gt := NewGomegaWithT(t)
    61  
    62  	chaincode := &mock.Chaincode{}
    63  	chaincode.InitReturns(pb.Response{Message: "init-returns"})
    64  	chaincode.InvokeReturns(pb.Response{Message: "invoke-returns"})
    65  
    66  	sysCC := &mock.SelfDescribingSysCC{}
    67  	sysCC.ChaincodeReturns(chaincode)
    68  	throttled := scc.Throttle(5, sysCC).Chaincode()
    69  
    70  	initResp := throttled.Init(nil)
    71  	gt.Expect(initResp.Message).To(Equal("init-returns"))
    72  	invokeResp := throttled.Invoke(nil)
    73  	gt.Expect(invokeResp.Message).To(Equal("invoke-returns"))
    74  }