github.com/defanghe/fabric@v2.1.1+incompatible/gossip/comm/metrics_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package comm
     8  
     9  import (
    10  	"sync/atomic"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/hyperledger/fabric/gossip/metrics"
    15  	"github.com/hyperledger/fabric/gossip/metrics/mocks"
    16  	"github.com/hyperledger/fabric/gossip/util"
    17  	"github.com/stretchr/testify/assert"
    18  )
    19  
    20  func newCommInstanceWithMetrics(t *testing.T, sec *naiveSecProvider, metrics *metrics.CommMetrics) (c Comm, port int) {
    21  	port, gRPCServer, certs, secureDialOpts, dialOpts := util.CreateGRPCLayer()
    22  	comm := newCommInstanceOnlyWithMetrics(t, metrics, sec, gRPCServer, certs, secureDialOpts, dialOpts...)
    23  	return comm, port
    24  }
    25  
    26  func TestMetrics(t *testing.T) {
    27  	t.Parallel()
    28  
    29  	testMetricProvider := mocks.TestUtilConstructMetricProvider()
    30  
    31  	var overflown uint32
    32  	testMetricProvider.FakeBufferOverflow.AddStub = func(delta float64) {
    33  		atomic.StoreUint32(&overflown, uint32(1))
    34  	}
    35  
    36  	fakeCommMetrics := metrics.NewGossipMetrics(testMetricProvider.FakeProvider).CommMetrics
    37  
    38  	comm1, _ := newCommInstanceWithMetrics(t, naiveSec, fakeCommMetrics)
    39  	comm2, port2 := newCommInstanceWithMetrics(t, naiveSec, fakeCommMetrics)
    40  	defer comm1.Stop()
    41  	defer comm2.Stop()
    42  
    43  	// Establish preliminary connection
    44  	fromComm1 := comm2.Accept(acceptAll)
    45  	comm1.Send(createGossipMsg(), remotePeer(port2))
    46  	<-fromComm1
    47  
    48  	// Drain messages slowly by comm2
    49  	drainMessages := func() {
    50  		for {
    51  			msg := <-fromComm1
    52  			time.Sleep(time.Millisecond)
    53  			if msg == nil {
    54  				return
    55  			}
    56  		}
    57  	}
    58  
    59  	go drainMessages()
    60  
    61  	// Send messages until the buffer overflow event emission is detected
    62  	for {
    63  		comm1.Send(createGossipMsg(), remotePeer(port2))
    64  		if atomic.LoadUint32(&overflown) == uint32(1) {
    65  			t.Log("Buffer overflow detected")
    66  			break
    67  		}
    68  	}
    69  
    70  	assert.EqualValues(t,
    71  		1,
    72  		testMetricProvider.FakeSentMessages.AddArgsForCall(0),
    73  	)
    74  
    75  	assert.EqualValues(t,
    76  		1,
    77  		testMetricProvider.FakeReceivedMessages.AddArgsForCall(0),
    78  	)
    79  
    80  	assert.EqualValues(t,
    81  		1,
    82  		testMetricProvider.FakeBufferOverflow.AddArgsForCall(0),
    83  	)
    84  
    85  	assert.Equal(t, uint32(1), atomic.LoadUint32(&overflown))
    86  
    87  }