| 68 | } |
| 69 | |
| 70 | func TestWSReader(t *testing.T) { |
| 71 | mr := &fakeReader{ch: make(chan []byte, 1)} |
| 72 | defer mr.close() |
| 73 | r := wsNewReader(mr) |
| 74 | |
| 75 | p := make([]byte, 100) |
| 76 | checkRead := func(limit int, expected []byte, lenPending int) { |
| 77 | t.Helper() |
| 78 | n, err := r.Read(p[:limit]) |
| 79 | if err != nil { |
| 80 | t.Fatalf("Error reading: %v", err) |
| 81 | } |
| 82 | if !bytes.Equal(p[:n], expected) { |
| 83 | t.Fatalf("Expected %q, got %q", expected, p[:n]) |
| 84 | } |
| 85 | if len(r.pending) != lenPending { |
| 86 | t.Fatalf("Expected len(r.pending) to be %v, got %v", lenPending, len(r.pending)) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | // Test with a buffer that contains a single pending with all data that |
| 91 | // fits in the read buffer. |
| 92 | mr.buf.Write([]byte{130, 10}) |
| 93 | mr.buf.WriteString("ABCDEFGHIJ") |
| 94 | checkRead(100, []byte("ABCDEFGHIJ"), 0) |
| 95 | |
| 96 | // Write 2 frames in the buffer. Since we will call with a read buffer |
| 97 | // that can fit both, we will create 2 pending and consume them at once. |
| 98 | mr.buf.Write([]byte{130, 5}) |
| 99 | mr.buf.WriteString("ABCDE") |
| 100 | mr.buf.Write([]byte{130, 5}) |
| 101 | mr.buf.WriteString("FGHIJ") |
| 102 | checkRead(100, []byte("ABCDEFGHIJ"), 0) |
| 103 | |
| 104 | // We also write 2 frames, but this time we will call the first read |
| 105 | // with a read buffer that can accommodate only the first frame. |
| 106 | // So internally only a single frame is going to be read in pending. |
| 107 | mr.buf.Write([]byte{130, 5}) |
| 108 | mr.buf.WriteString("ABCDE") |
| 109 | mr.buf.Write([]byte{130, 5}) |
| 110 | mr.buf.WriteString("FGHIJ") |
| 111 | checkRead(6, []byte("ABCDE"), 0) |
| 112 | checkRead(100, []byte("FGHIJ"), 0) |
| 113 | |
| 114 | // To test partials, we need to directly set the pending buffers. |
| 115 | r.pending = append(r.pending, []byte("ABCDE")) |
| 116 | r.pending = append(r.pending, []byte("FGHIJ")) |
| 117 | // Now check that the first read cannot get the full first pending |
| 118 | // buffer and gets only a partial. |
| 119 | checkRead(3, []byte("ABC"), 2) |
| 120 | // Since the read buffer is big enough to get everything else, after |
| 121 | // this call we should have no pending. |
| 122 | checkRead(7, []byte("DEFGHIJ"), 0) |
| 123 | |
| 124 | // Similar to above but with both partials. |
| 125 | r.pending = append(r.pending, []byte("ABCDE")) |
| 126 | r.pending = append(r.pending, []byte("FGHIJ")) |
| 127 | checkRead(3, []byte("ABC"), 2) |