github.com/osdi23p228/fabric@v0.0.0-20221218062954-77808885f5db/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/osdi23p228/fabric/gossip/metrics"
    15  	"github.com/osdi23p228/fabric/gossip/metrics/mocks"
    16  	"github.com/osdi23p228/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  	testMetricProvider := mocks.TestUtilConstructMetricProvider()
    28  
    29  	var overflown uint32
    30  	testMetricProvider.FakeBufferOverflow.AddStub = func(delta float64) {
    31  		atomic.StoreUint32(&overflown, uint32(1))
    32  	}
    33  
    34  	fakeCommMetrics := metrics.NewGossipMetrics(testMetricProvider.FakeProvider).CommMetrics
    35  
    36  	comm1, _ := newCommInstanceWithMetrics(t, naiveSec, fakeCommMetrics)
    37  	comm2, port2 := newCommInstanceWithMetrics(t, naiveSec, fakeCommMetrics)
    38  	defer comm1.Stop()
    39  	defer comm2.Stop()
    40  
    41  	// Establish preliminary connection
    42  	fromComm1 := comm2.Accept(acceptAll)
    43  	comm1.Send(createGossipMsg(), remotePeer(port2))
    44  	<-fromComm1
    45  
    46  	// Drain messages slowly by comm2
    47  	drainMessages := func() {
    48  		for {
    49  			msg := <-fromComm1
    50  			time.Sleep(time.Millisecond)
    51  			if msg == nil {
    52  				return
    53  			}
    54  		}
    55  	}
    56  
    57  	go drainMessages()
    58  
    59  	// Send messages until the buffer overflow event emission is detected
    60  	for {
    61  		comm1.Send(createGossipMsg(), remotePeer(port2))
    62  		if atomic.LoadUint32(&overflown) == uint32(1) {
    63  			t.Log("Buffer overflow detected")
    64  			break
    65  		}
    66  	}
    67  
    68  	assert.EqualValues(t,
    69  		1,
    70  		testMetricProvider.FakeSentMessages.AddArgsForCall(0),
    71  	)
    72  
    73  	assert.EqualValues(t,
    74  		1,
    75  		testMetricProvider.FakeReceivedMessages.AddArgsForCall(0),
    76  	)
    77  
    78  	assert.EqualValues(t,
    79  		1,
    80  		testMetricProvider.FakeBufferOverflow.AddArgsForCall(0),
    81  	)
    82  
    83  	assert.Equal(t, uint32(1), atomic.LoadUint32(&overflown))
    84  }