| 1 |
package framing_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"io" |
| 6 |
"testing" |
| 7 |
|
| 8 |
. "github.com/mesos/mesos-go/api/v1/lib/encoding/framing" |
| 9 |
) |
| 10 |
|
| 11 |
func TestError(t *testing.T) { |
| 12 |
a := Error("a") |
| 13 |
if "a" != string(a) { |
| 14 |
t.Errorf("identity/sanity check failed") |
| 15 |
} |
| 16 |
if "a" != a.Error() { |
| 17 |
t.Errorf("expected 'a' instead of %q", a.Error()) |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
func TestReadAll(t *testing.T) { |
| 22 |
r := ReadAll(bytes.NewBufferString("")) |
| 23 |
buf, err := r.ReadFrame() |
| 24 |
if len(buf) != 0 { |
| 25 |
t.Errorf("expected zero length frame instead of %+v", buf) |
| 26 |
} |
| 27 |
if err != io.EOF { |
| 28 |
t.Errorf("expected EOF instead of %+v", err) |
| 29 |
} |
| 30 |
|
| 31 |
r = ReadAll(bytes.NewBufferString("foo")) |
| 32 |
buf, err = r.ReadFrame() |
| 33 |
if err != nil { |
| 34 |
t.Fatalf("unexpected error %+v", err) |
| 35 |
} |
| 36 |
if string(buf) != "foo" { |
| 37 |
t.Errorf("expected 'foo' instead of %q", string(buf)) |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
buf, err = r.ReadFrame() |
| 42 |
if len(buf) != 0 { |
| 43 |
t.Errorf("expected zero length frame instead of %+v", buf) |
| 44 |
} |
| 45 |
if err != io.EOF { |
| 46 |
t.Errorf("expected EOF instead of %+v", err) |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
func TestWriterFor(t *testing.T) { |
| 51 |
buf := new(bytes.Buffer) |
| 52 |
w := WriterFor(buf) |
| 53 |
err := w.WriteFrame(([]byte)("foo")) |
| 54 |
if err != nil { |
| 55 |
t.Fatalf("failed to write frame: +%v", err) |
| 56 |
} |
| 57 |
if buf.String() != "foo" { |
| 58 |
t.Fatalf("expected 'foo' instead of %q", buf.String()) |
| 59 |
} |
| 60 |
|
| 61 |
err = w.WriteFrame(([]byte)("")) |
| 62 |
if err != nil { |
| 63 |
t.Fatalf("failed to write empty frame: +%v", err) |
| 64 |
} |
| 65 |
if buf.String() != "foo" { |
| 66 |
t.Fatalf("expected 'foo' instead of %q", buf.String()) |
| 67 |
} |
| 68 |
|
| 69 |
w = WriterFor(&shortWriter{w: buf, n: 1}) |
| 70 |
err = w.WriteFrame(([]byte)("")) |
| 71 |
if err != nil { |
| 72 |
t.Fatalf("failed to write empty frame: +%v", err) |
| 73 |
} |
| 74 |
if buf.String() != "foo" { |
| 75 |
t.Fatalf("expected 'foo' instead of %q", buf.String()) |
| 76 |
} |
| 77 |
|
| 78 |
err = w.WriteFrame(([]byte)("bar")) |
| 79 |
if err != io.ErrShortWrite { |
| 80 |
t.Fatalf("failed to detect short write: +%v", err) |
| 81 |
} |
| 82 |
if buf.String() != "foob" { |
| 83 |
t.Fatalf("expected 'foob' instead of %q", buf.String()) |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
type shortWriter struct { |
| 88 |
w io.Writer |
| 89 |
n int |
| 90 |
} |
| 91 |
|
| 92 |
func (s *shortWriter) Write(b []byte) (n int, err error) { |
| 93 |
if s.n <= 0 { |
| 94 |
return 0, nil |
| 95 |
} |
| 96 |
n = len(b) |
| 97 |
if n > s.n { |
| 98 |
n = s.n |
| 99 |
} |
| 100 |
n, err = s.w.Write(b[0:n]) |
| 101 |
s.n -= n |
| 102 |
return |
| 103 |
} |