github.com/anycable/anycable-go@v1.5.1/encoders/encoding_cache_test.go (about)

     1  package encoders
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/anycable/anycable-go/ws"
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  type MockMessage struct {
    11  	Encoded int
    12  	Value   string
    13  }
    14  
    15  func (m *MockMessage) GetType() string {
    16  	return "mock"
    17  }
    18  
    19  func TestEncodingCache(t *testing.T) {
    20  	msg := &MockMessage{Value: "mock"}
    21  
    22  	c := NewEncodingCache()
    23  
    24  	callback := func(msg EncodedMessage) (*ws.SentFrame, error) {
    25  		if m, ok := msg.(*MockMessage); ok {
    26  			m.Encoded++
    27  			return &ws.SentFrame{FrameType: ws.TextFrame, Payload: []byte(m.Value)}, nil
    28  		}
    29  		return nil, nil
    30  	}
    31  
    32  	v, _ := c.Fetch(msg, "mock", callback)
    33  	assert.Equal(t, []byte("mock"), v.Payload)
    34  
    35  	v, _ = c.Fetch(msg, "mock", callback)
    36  	assert.Equal(t, []byte("mock"), v.Payload)
    37  	assert.Equal(t, 1, msg.Encoded)
    38  }