github.com/contiv/libOpenflow@v0.0.0-20210609050114-d967b14cc688/stream_test.go (about)

     1  package libOpenflow
     2  
     3  import (
     4  	"io"
     5  	"net"
     6  	"runtime"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/contiv/libOpenflow/common"
    11  	"github.com/contiv/libOpenflow/openflow13"
    12  	"github.com/contiv/libOpenflow/util"
    13  	"github.com/sirupsen/logrus"
    14  )
    15  
    16  var helloMessage *common.Hello
    17  var binaryMessage []byte
    18  
    19  type fakeConn struct {
    20  	count int
    21  	max   int
    22  }
    23  
    24  func (f *fakeConn) Close() error {
    25  	return nil
    26  }
    27  
    28  func (f *fakeConn) Read(b []byte) (int, error) {
    29  	if f.count == f.max {
    30  		return 0, io.EOF
    31  	}
    32  	f.count++
    33  	copy(b, binaryMessage)
    34  	return len(binaryMessage), nil
    35  }
    36  
    37  func (f *fakeConn) Write(b []byte) (int, error) {
    38  	b, _ = helloMessage.MarshalBinary()
    39  	return len(b), nil
    40  }
    41  
    42  func (f *fakeConn) LocalAddr() net.Addr {
    43  	return nil
    44  }
    45  
    46  func (f *fakeConn) RemoteAddr() net.Addr {
    47  	return nil
    48  }
    49  
    50  func (f *fakeConn) SetDeadline(t time.Time) error {
    51  	return nil
    52  }
    53  
    54  func (f *fakeConn) SetReadDeadline(t time.Time) error {
    55  	return nil
    56  }
    57  
    58  func (f *fakeConn) SetWriteDeadline(t time.Time) error {
    59  	return nil
    60  }
    61  
    62  type parserIntf struct {
    63  }
    64  
    65  func (p parserIntf) Parse(b []byte) (message util.Message, err error) {
    66  	switch b[0] {
    67  	case openflow13.VERSION:
    68  		message, err = openflow13.Parse(b)
    69  	default:
    70  
    71  	}
    72  	return
    73  }
    74  
    75  func init() {
    76  	helloMessage, _ = common.NewHello(4)
    77  	binaryMessage, _ = helloMessage.MarshalBinary()
    78  
    79  }
    80  
    81  func TestMessageStream(t *testing.T) {
    82  	var (
    83  		c = &fakeConn{
    84  			max: 5000000,
    85  		}
    86  		p                   = parserIntf{}
    87  		goroutineCountStart = runtime.NumGoroutine()
    88  		goroutineCountEnd   int
    89  	)
    90  	logrus.SetLevel(logrus.PanicLevel)
    91  	stream := util.NewMessageStream(c, p)
    92  	go func() {
    93  		_ = <-stream.Error
    94  	}()
    95  	for i := 0; i < 5000000; i++ {
    96  		<-stream.Inbound
    97  	}
    98  	time.Sleep(2 * time.Second)
    99  	goroutineCountEnd = runtime.NumGoroutine()
   100  	if goroutineCountEnd > goroutineCountStart {
   101  		t.Fatalf("found more goroutines: %v before, %v after", goroutineCountStart, goroutineCountEnd)
   102  	}
   103  }