github.com/msales/pkg/v3@v3.24.0/grpcx/server_test.go (about)

     1  package grpcx_test
     2  
     3  import (
     4  	"errors"
     5  	"net"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/msales/pkg/v3/grpcx"
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/mock"
    12  	"google.golang.org/grpc"
    13  )
    14  
    15  func TestNewServer(t *testing.T) {
    16  	srv := grpcx.NewServer(new(mockListener), &grpc.Server{})
    17  
    18  	assert.IsType(t, (*grpcx.Server)(nil), srv)
    19  }
    20  
    21  func TestServer_Serve(t *testing.T) {
    22  	lisErr := errors.New("test: listener error")
    23  
    24  	lis := new(mockListener)
    25  	lis.On("Accept").Return(new(mockConn), lisErr)
    26  	lis.On("Close").Return(nil)
    27  
    28  	srv := grpcx.NewServer(lis, grpc.NewServer())
    29  
    30  	err := srv.Serve()
    31  
    32  	assert.Equal(t, lisErr, err)
    33  	lis.AssertExpectations(t)
    34  }
    35  
    36  func TestServer_Close(t *testing.T) {
    37  	// Cannot properly unit-test it because the server cannot be mocked.
    38  }
    39  
    40  type mockListener struct {
    41  	mock.Mock
    42  }
    43  
    44  func (l *mockListener) Accept() (net.Conn, error) {
    45  	args := l.Called()
    46  
    47  	return args.Get(0).(net.Conn), args.Error(1)
    48  }
    49  
    50  func (l *mockListener) Close() error {
    51  	return l.Called().Error(0)
    52  }
    53  
    54  func (l *mockListener) Addr() net.Addr {
    55  	return l.Called().Get(0).(net.Addr)
    56  }
    57  
    58  type mockConn struct{}
    59  
    60  func (mockConn) Read(b []byte) (n int, err error) {
    61  	return 0, nil
    62  }
    63  
    64  func (mockConn) Write(b []byte) (n int, err error) {
    65  	return 0, nil
    66  }
    67  
    68  func (mockConn) Close() error {
    69  	return nil
    70  }
    71  
    72  func (mockConn) LocalAddr() net.Addr {
    73  	return nil
    74  }
    75  
    76  func (mockConn) RemoteAddr() net.Addr {
    77  	return nil
    78  }
    79  
    80  func (mockConn) SetDeadline(t time.Time) error {
    81  	return nil
    82  }
    83  
    84  func (mockConn) SetReadDeadline(t time.Time) error {
    85  	return nil
    86  }
    87  
    88  func (mockConn) SetWriteDeadline(t time.Time) error {
    89  	return nil
    90  }