summaryrefslogtreecommitdiff
path: root/src/pkg/crypto/tls/record_read_test.go
blob: f897599ad098f5b87e4785be999b3346d1fb7da6 (plain)
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
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tls

import (
	"bytes"
	"testing"
	"testing/iotest"
)

func matchRecord(r1, r2 *record) bool {
	if (r1 == nil) != (r2 == nil) {
		return false
	}
	if r1 == nil {
		return true
	}
	return r1.contentType == r2.contentType &&
		r1.major == r2.major &&
		r1.minor == r2.minor &&
		bytes.Compare(r1.payload, r2.payload) == 0
}

type recordReaderTest struct {
	in  []byte
	out []*record
}

var recordReaderTests = []recordReaderTest{
	recordReaderTest{nil, nil},
	recordReaderTest{fromHex("01"), nil},
	recordReaderTest{fromHex("0102"), nil},
	recordReaderTest{fromHex("010203"), nil},
	recordReaderTest{fromHex("01020300"), nil},
	recordReaderTest{fromHex("0102030000"), []*record{&record{1, 2, 3, nil}}},
	recordReaderTest{fromHex("01020300000102030000"), []*record{&record{1, 2, 3, nil}, &record{1, 2, 3, nil}}},
	recordReaderTest{fromHex("0102030001fe0102030002feff"), []*record{&record{1, 2, 3, []byte{0xfe}}, &record{1, 2, 3, []byte{0xfe, 0xff}}}},
	recordReaderTest{fromHex("010203000001020300"), []*record{&record{1, 2, 3, nil}}},
}

func TestRecordReader(t *testing.T) {
	for i, test := range recordReaderTests {
		buf := bytes.NewBuffer(test.in)
		c := make(chan *record)
		go recordReader(c, buf)
		matchRecordReaderOutput(t, i, test, c)

		buf = bytes.NewBuffer(test.in)
		buf2 := iotest.OneByteReader(buf)
		c = make(chan *record)
		go recordReader(c, buf2)
		matchRecordReaderOutput(t, i*2, test, c)
	}
}

func matchRecordReaderOutput(t *testing.T, i int, test recordReaderTest, c <-chan *record) {
	for j, r1 := range test.out {
		r2 := <-c
		if r2 == nil {
			t.Errorf("#%d truncated after %d values", i, j)
			break
		}
		if !matchRecord(r1, r2) {
			t.Errorf("#%d (%d) got:%#v want:%#v", i, j, r2, r1)
		}
	}
	<-c
	if !closed(c) {
		t.Errorf("#%d: channel didn't close", i)
	}
}