Debian Codegraph @

api/v1/lib/encoding/framing/decoder_test.go

raw symbols SCIP
1 package framing_test
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "reflect"
8 "testing"
9
10 . "github.com/mesos/mesos-go/api/v1/lib/encoding/framing"
11 )
12
13 func TestNewDecoder(t *testing.T) {
14 var (
15 byteCopy = UnmarshalFunc(func(b []byte, m interface{}) error {
16 if m == nil {
17 return errors.New("unmarshal target may not be nil")
18 }
19 v, ok := m.(*[]byte)
20 if !ok {
21 return fmt.Errorf("expected *[]byte instead of %T", m)
22 }
23 if v == nil {
24 return errors.New("target *[]byte may not be nil")
25 }
26 *v = append((*v)[:0], b...)
27 return nil
28 })
29 fakeError = errors.New("fake unmarshal error")
30 errorUnmarshaler = UnmarshalFunc(func(_ []byte, _ interface{}) error {
31 return fakeError
32 })
33 )
34 for ti, tc := range []struct {
35 r Reader
36 uf UnmarshalFunc
37 wants [][]byte
38 wantsErr error
39 }{
40 {errorReader(ErrorBadSize), byteCopy, nil, ErrorBadSize},
41 {tokenReader("james"), byteCopy, frames("james"), nil},
42 {tokenReader("james", "foo"), byteCopy, frames("james", "foo"), nil},
43 {tokenReader("", "foo"), byteCopy, frames("", "foo"), nil},
44 {tokenReader("foo", ""), byteCopy, frames("foo", ""), nil},
45 {tokenReader(""), byteCopy, frames(""), nil},
46 {tokenReader(), byteCopy, frames(), io.EOF},
47 {tokenReader("james"), errorUnmarshaler, nil, fakeError},
48 } {
49 t.Run(fmt.Sprintf("test case %d", ti), func(t *testing.T) {
50 if (tc.wants == nil) != (tc.wantsErr != nil) {
51 t.Fatalf("invalid test case: cannot expect both data and an error")
52 }
53 var (
54 f [][]byte
55 d = NewDecoder(tc.r, tc.uf)
56 err error
57 )
58 for err == nil {
59 var buf []byte
60 err = d.Decode(&buf)
61 if err == io.EOF {
62 break
63 }
64 if err == nil {
65 f = append(f, buf)
66 }
67 if err != tc.wantsErr {
68 t.Errorf("expected error %q instead of %q", tc.wantsErr, err)
69 }
70 }
71 if !reflect.DeepEqual(f, tc.wants) {
72 t.Errorf("expected %#v instead of %#v", tc.wants, f)
73 }
74 })
75 }
76 }
77
78 func tokenReader(s ...string) ReaderFunc {
79 if len(s) == 0 {
80 return EOFReaderFunc
81 }
82 ch := make(chan []byte, len(s))
83 for i := range s {
84 ch <- ([]byte)(s[i])
85 }
86 return func() ([]byte, error) {
87 select {
88 case b := <-ch:
89 return b, nil
90 default:
91 return nil, io.EOF
92 }
93 }
94 }
95
96 func errorReader(err error) ReaderFunc {
97 return func() ([]byte, error) { return nil, err }
98 }
99
100 func frames(s ...string) (f [][]byte) {
101 if len(s) == 0 {
102 return nil
103 }
104 f = make([][]byte, 0, len(s))
105 for i := range s {
106 // converting to/from []byte and string for empty string isn't a perfectly symmetrical
107 // operation. fix it up here with a quick length check.
108 if len(s[i]) == 0 {
109 f = append(f, nil)
110 continue
111 }
112 f = append(f, ([]byte)(s[i]))
113 }
114 return
115 }