-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathclient_server_test.go
115 lines (93 loc) · 2.13 KB
/
client_server_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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package goridge
import (
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"net"
"net/rpc"
"strings"
"testing"
)
// testService sample
type testService struct{}
// Payload sample
type Payload struct {
Name string `json:"name"`
Value int `json:"value"`
Keys map[string]string `json:"keys,omitempty"`
}
// Echo returns incoming message
func (s *testService) Echo(msg string, r *string) error {
*r = msg
return nil
}
// Echo returns error
func (s *testService) EchoR(msg string, r *string) error {
return errors.New("echoR error")
}
// Process performs payload conversion
func (s *testService) Process(msg Payload, r *Payload) error {
r.Name = strings.ToUpper(msg.Name)
r.Value = -msg.Value
if len(msg.Keys) != 0 {
r.Keys = make(map[string]string)
for n, v := range msg.Keys {
r.Keys[v] = n
}
}
return nil
}
// EchoBinary work over binary data
func (s *testService) EchoBinary(msg []byte, out *[]byte) error {
*out = append(*out, msg...)
return nil
}
func TestClientServer(t *testing.T) {
var ln net.Listener
var err error
ln, err = net.Listen("tcp", ":8079")
if err != nil {
panic(err)
}
err = rpc.RegisterName("test", new(testService))
if err != nil {
panic(err)
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
continue
}
rpc.ServeCodec(NewCodec(conn))
}
}()
conn, err := net.Dial("tcp", ":8079")
if err != nil {
panic(err)
}
client := rpc.NewClientWithCodec(NewClientCodec(conn))
defer func() {
err := client.Close()
if err != nil {
panic(err)
}
}()
var (
rs = ""
rp = Payload{}
rb = make([]byte, 0)
)
assert.NoError(t, client.Call("test.Process", Payload{
Name: "name",
Value: 1000,
Keys: map[string]string{"key": "value"},
}, &rp))
assert.Equal(t, "NAME", rp.Name)
assert.Equal(t, -1000, rp.Value)
assert.Equal(t, "key", rp.Keys["value"])
assert.NoError(t, client.Call("test.Echo", "hello", &rs))
assert.Equal(t, "hello", rs)
assert.NoError(t, client.Call("test.EchoBinary", []byte("hello world"), &rb))
assert.Equal(t, []byte("hello world"), rb)
assert.Error(t, client.Call("test.EchoR", "hi", &rs))
}