File: framing_test.go

package info (click to toggle)
golang-github-mesos-mesos-go 0.0.6%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 11,724 kB
  • sloc: makefile: 163
file content (103 lines) | stat: -rw-r--r-- 2,172 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package framing_test

import (
	"bytes"
	"io"
	"testing"

	. "github.com/mesos/mesos-go/api/v1/lib/encoding/framing"
)

func TestError(t *testing.T) {
	a := Error("a")
	if "a" != string(a) {
		t.Errorf("identity/sanity check failed")
	}
	if "a" != a.Error() {
		t.Errorf("expected 'a' instead of %q", a.Error())
	}
}

func TestReadAll(t *testing.T) {
	r := ReadAll(bytes.NewBufferString(""))
	buf, err := r.ReadFrame()
	if len(buf) != 0 {
		t.Errorf("expected zero length frame instead of %+v", buf)
	}
	if err != io.EOF {
		t.Errorf("expected EOF instead of %+v", err)
	}

	r = ReadAll(bytes.NewBufferString("foo"))
	buf, err = r.ReadFrame()
	if err != nil {
		t.Fatalf("unexpected error %+v", err)
	}
	if string(buf) != "foo" {
		t.Errorf("expected 'foo' instead of %q", string(buf))
	}

	// read again, now that there's no more data
	buf, err = r.ReadFrame()
	if len(buf) != 0 {
		t.Errorf("expected zero length frame instead of %+v", buf)
	}
	if err != io.EOF {
		t.Errorf("expected EOF instead of %+v", err)
	}
}

func TestWriterFor(t *testing.T) {
	buf := new(bytes.Buffer)
	w := WriterFor(buf)
	err := w.WriteFrame(([]byte)("foo"))
	if err != nil {
		t.Fatalf("failed to write frame: +%v", err)
	}
	if buf.String() != "foo" {
		t.Fatalf("expected 'foo' instead of %q", buf.String())
	}

	err = w.WriteFrame(([]byte)(""))
	if err != nil {
		t.Fatalf("failed to write empty frame: +%v", err)
	}
	if buf.String() != "foo" {
		t.Fatalf("expected 'foo' instead of %q", buf.String())
	}

	w = WriterFor(&shortWriter{w: buf, n: 1})
	err = w.WriteFrame(([]byte)(""))
	if err != nil {
		t.Fatalf("failed to write empty frame: +%v", err)
	}
	if buf.String() != "foo" {
		t.Fatalf("expected 'foo' instead of %q", buf.String())
	}

	err = w.WriteFrame(([]byte)("bar"))
	if err != io.ErrShortWrite {
		t.Fatalf("failed to detect short write: +%v", err)
	}
	if buf.String() != "foob" {
		t.Fatalf("expected 'foob' instead of %q", buf.String())
	}
}

type shortWriter struct {
	w io.Writer
	n int
}

func (s *shortWriter) Write(b []byte) (n int, err error) {
	if s.n <= 0 {
		return 0, nil
	}
	n = len(b)
	if n > s.n {
		n = s.n
	}
	n, err = s.w.Write(b[0:n])
	s.n -= n
	return
}