github.com/anycable/anycable-go@v1.5.1/sse/connection_test.go (about) 1 package sse 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "testing" 7 "time" 8 9 "github.com/anycable/anycable-go/ws" 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func (c *Connection) testResponse() string { 14 c.mu.Lock() 15 defer c.mu.Unlock() 16 17 return c.writer.(*httptest.ResponseRecorder).Body.String() 18 } 19 20 func (c *Connection) testStatus() int { 21 c.mu.Lock() 22 defer c.mu.Unlock() 23 24 return c.writer.(*httptest.ResponseRecorder).Code 25 } 26 27 func TestConnection_Write(t *testing.T) { 28 w := httptest.NewRecorder() 29 c := NewConnection(w) 30 31 msg := []byte("hello, world!") 32 err := c.Write(msg, time.Now().Add(1*time.Second)) 33 34 assert.NoError(t, err) 35 36 assert.Empty(t, c.testResponse()) 37 38 c.Established() 39 40 assert.Equal(t, http.StatusOK, c.testStatus()) 41 assert.Equal(t, "hello, world!\n\n", c.testResponse()) 42 } 43 44 func TestConnection_Close(t *testing.T) { 45 t.Run("Close cancels the context", func(t *testing.T) { 46 // Create a new connection 47 w := httptest.NewRecorder() 48 c := NewConnection(w) 49 50 ctx := c.Context() 51 52 c.Close(ws.CloseNormalClosure, "bye") 53 54 <-ctx.Done() 55 assert.True(t, c.done) 56 57 c.Close(ws.CloseNormalClosure, "bye") 58 }) 59 } 60 61 func TestConnection_WriteBinary(t *testing.T) { 62 w := httptest.NewRecorder() 63 c := NewConnection(w) 64 65 msg := []byte{0x01, 0x02, 0x03} 66 err := c.WriteBinary(msg, time.Now().Add(1*time.Second)) 67 68 assert.Error(t, err) 69 assert.Equal(t, []byte(nil), w.Body.Bytes()) 70 } 71 72 func TestConnection_Read(t *testing.T) { 73 w := httptest.NewRecorder() 74 c := NewConnection(w) 75 76 msg, err := c.Read() 77 78 assert.Error(t, err) 79 assert.Equal(t, []byte(nil), msg) 80 } 81 82 func TestConnection_Descriptor(t *testing.T) { 83 w := httptest.NewRecorder() 84 c := NewConnection(w) 85 86 assert.Nil(t, c.Descriptor()) 87 }