github.com/ezoic/ws@v1.0.4-0.20220713205711-5c1d69e074c5/wsutil/helper_test.go (about)

     1  package wsutil
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"testing"
     7  
     8  	"github.com/ezoic/ws"
     9  )
    10  
    11  func TestReadMessageEOF(t *testing.T) {
    12  	for _, test := range []struct {
    13  		source   func() io.Reader
    14  		messages []Message
    15  		err      error
    16  	}{
    17  		{
    18  			source: func() io.Reader { return eofReader },
    19  			err:    io.EOF,
    20  		},
    21  		{
    22  			source: func() io.Reader {
    23  				// This case tests that ReadMessage still fails after
    24  				// successfully reading header bytes frame via ws.ReadHeader()
    25  				// and non-successfully read of the body.
    26  				var buf bytes.Buffer
    27  				f := ws.NewTextFrame([]byte("this part will be lost"))
    28  				if err := ws.WriteHeader(&buf, f.Header); err != nil {
    29  					panic(err)
    30  				}
    31  				return &buf
    32  			},
    33  			err: io.ErrUnexpectedEOF,
    34  		},
    35  		{
    36  			source: func() io.Reader {
    37  				// This case tests that ReadMessage not fail when reading
    38  				// fragmented messages.
    39  				var buf bytes.Buffer
    40  				fs := []ws.Frame{
    41  					ws.NewFrame(ws.OpText, false, []byte("fragment1")),
    42  					ws.NewFrame(ws.OpContinuation, false, []byte(",")),
    43  					ws.NewFrame(ws.OpContinuation, true, []byte("fragment2")),
    44  				}
    45  				for _, f := range fs {
    46  					if err := ws.WriteFrame(&buf, f); err != nil {
    47  						panic(err)
    48  					}
    49  				}
    50  				return &buf
    51  			},
    52  			messages: []Message{
    53  				{ws.OpText, []byte("fragment1,fragment2")},
    54  			},
    55  		},
    56  	} {
    57  		t.Run("", func(t *testing.T) {
    58  			ms, err := ReadMessage(test.source(), 0, nil)
    59  			if err != test.err {
    60  				t.Errorf("unexpected error: %v; want %v", err, test.err)
    61  			}
    62  			if n := len(ms); n != len(test.messages) {
    63  				t.Fatalf("unexpected number of read messages: %d; want %d", n, 0)
    64  			}
    65  			for i, exp := range test.messages {
    66  				act := ms[i]
    67  				if act.OpCode != exp.OpCode {
    68  					t.Errorf(
    69  						"unexpected #%d message op code: %v; want %v",
    70  						i, act.OpCode, exp.OpCode,
    71  					)
    72  				}
    73  				if !bytes.Equal(act.Payload, exp.Payload) {
    74  					t.Errorf(
    75  						"unexpected #%d message payload: %q; want %q",
    76  						i, string(act.Payload), string(exp.Payload),
    77  					)
    78  				}
    79  			}
    80  		})
    81  	}
    82  }