-
Notifications
You must be signed in to change notification settings - Fork 11
/
proxy_test.go
80 lines (65 loc) · 1.63 KB
/
proxy_test.go
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
package main
import (
"bytes"
"encoding/binary"
"errors"
"io"
"sync"
"testing"
)
func send(t *testing.T, sizeBuf, expectedBytes []byte, expectedErr error) {
t.Helper()
var err error
var wg sync.WaitGroup
wg.Add(1)
errCh := make(chan error)
go func() {
err = <-errCh
wg.Done()
}()
out := &bytes.Buffer{}
in := bytes.NewBuffer(append(sizeBuf, expectedBytes...))
tx(in, out, errCh)
wg.Wait()
if !errors.Is(err, expectedErr) {
t.Fatalf("Expected error %v but got %v.", expectedErr, err)
}
actualBytes := out.Bytes()
if !bytes.Equal(actualBytes, expectedBytes) {
t.Fatalf("Expected to read bytes\n%v\nbut got\n%v", expectedBytes, actualBytes)
}
}
func receive(t *testing.T, b []byte, expectedErr error) {
t.Helper()
var err error
var wg sync.WaitGroup
wg.Add(1)
errCh := make(chan error)
go func() {
err = <-errCh
wg.Done()
}()
expectedBytes := make([]byte, len(b)+frameSizeLen)
binary.LittleEndian.PutUint16(expectedBytes[:frameSizeLen], uint16(len(b)))
copy(expectedBytes[frameSizeLen:], b)
out := &bytes.Buffer{}
rx(out, bytes.NewBuffer(b), errCh)
wg.Wait()
if !errors.Is(err, expectedErr) {
t.Fatalf("Expected error %v but got %v.", expectedErr, err)
}
actualBytes := out.Bytes()
if !bytes.Equal(actualBytes, expectedBytes) {
t.Fatalf("Expected to read bytes\n%v\nbut got\n%v", expectedBytes, actualBytes)
}
}
func TestTx(t *testing.T) {
expected := "foobar"
frameSize := make([]byte, frameSizeLen)
binary.LittleEndian.PutUint16(frameSize, uint16(len(expected)))
send(t, frameSize, []byte(expected), io.EOF)
}
func TestRx(t *testing.T) {
expected := "foobar"
receive(t, []byte(expected), io.EOF)
}