1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20package thrift
21
22import (
23	"bytes"
24	"errors"
25	"io"
26	"reflect"
27	"testing"
28)
29
30func TestEnsureTransportsAreRich(t *testing.T) {
31	buf := bytes.NewBuffer(make([]byte, 0, 1024))
32
33	transports := []TTransportFactory{
34		NewTMemoryBufferTransportFactory(1024),
35		NewStreamTransportFactory(buf, buf, true),
36		NewTFramedTransportFactory(NewTMemoryBufferTransportFactory(1024)),
37		NewTHttpPostClientTransportFactory("http://127.0.0.1"),
38	}
39	for _, tf := range transports {
40		trans, err := tf.GetTransport(nil)
41		if err != nil {
42			t.Error(err)
43			continue
44		}
45		_, ok := trans.(TRichTransport)
46		if !ok {
47			t.Errorf("Transport %s does not implement TRichTransport interface", reflect.ValueOf(trans))
48		}
49	}
50}
51
52// TestReadByte tests whether readByte handles error cases correctly.
53func TestReadByte(t *testing.T) {
54	for i, test := range readByteTests {
55		v, err := readByte(test.r)
56		if v != test.v {
57			t.Fatalf("TestReadByte %d: value differs. Expected %d, got %d", i, test.v, test.r.v)
58		}
59		if err != test.err {
60			t.Fatalf("TestReadByte %d: error differs. Expected %s, got %s", i, test.err, test.r.err)
61		}
62	}
63}
64
65var errSomeError = errors.New("Some error")
66var readByteTests = []struct {
67	r   *mockReader
68	v   byte
69	err error
70}{
71	{&mockReader{0, 55, io.EOF}, 0, io.EOF},              // reader sends EOF w/o data
72	{&mockReader{0, 55, errSomeError}, 0, errSomeError},  // reader sends some other error
73	{&mockReader{1, 55, nil}, 55, nil},                   // reader sends data w/o error
74	{&mockReader{1, 55, io.EOF}, 55, nil},                // reader sends data with EOF
75	{&mockReader{1, 55, errSomeError}, 55, errSomeError}, // reader sends data withsome error
76}
77
78type mockReader struct {
79	n   int
80	v   byte
81	err error
82}
83
84func (r *mockReader) Read(p []byte) (n int, err error) {
85	if r.n > 0 {
86		p[0] = r.v
87	}
88	return r.n, r.err
89}
90