Esempio n. 1
0
func TestReadFromWithValidInput(t *testing.T) {
	t.Parallel()

	var pb prefixedio.Buffer // Reuse the same buffer between runs
	buf := &bytes.Buffer{}
	var maxLenBuf bytes.Buffer
	for i := 0; i < prefixedio.MaxLen; i++ {
		maxLenBuf.WriteString("Q")
	}
	ins := []string{
		"foo",              // 1 < length < 8
		"foobarba",         // length == 8
		"foobarbaz",        // length > 8
		maxLenBuf.String(), // length == maxLen
		"f",                // length == 1, test last to verify reusing buffer works when content shrinks
	}
	for _, in := range ins {
		binary.Write(buf, binary.BigEndian, uint64(len(in)))
		buf.WriteString(in)

		n, err := pb.ReadFrom(buf)
		if err != nil {
			t.Fatal("Error on read: ", err)
		}
		if n != int64(len(in)) {
			t.Fatalf("Number of read bytes doesn't match input. Expected: %v. Actual: %v\n", len(in), n)
		}
		if byteStr := string(pb.Bytes()); byteStr != in {
			t.Fatalf("Read bytes doesn't match input. Expected: %q. Actual: %q\n", in, byteStr)
		}
	}
}
Esempio n. 2
0
func TestReadFromWithInvalidInput(t *testing.T) {
	t.Parallel()

	length := prefixedio.MaxLen + 1
	buf := bytes.NewBuffer(make([]byte, 0, length+8))
	if err := binary.Write(buf, binary.BigEndian, uint64(length)); err != nil {
		t.Fatal("Error on write: ", err)
	}
	for i := 0; i < length; i++ {
		buf.WriteString("a")
	}
	var pb prefixedio.Buffer
	if _, err := pb.ReadFrom(buf); err == nil {
		t.Fatal("No error raised when message too long")
	}
}