-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.go
More file actions
128 lines (111 loc) · 2.51 KB
/
client_test.go
File metadata and controls
128 lines (111 loc) · 2.51 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
package jdb
import (
"math/rand"
"strconv"
"sync"
_ "testing"
jsoniter "github.com/json-iterator/go"
"github.com/sirupsen/logrus"
)
type mockClient struct {
// Unique ID
uid int64
// Buffered channel of outbound messages.
send chan []byte
pending map[string]chan interface{}
pushes chan Push
responses chan Response
logger logrus.FieldLogger
options ClientOptions
mu sync.Mutex
}
func newMockClient(log logrus.FieldLogger) *mockClient {
return &mockClient{
uid: 0,
send: make(chan []byte),
pending: make(map[string]chan interface{}),
pushes: make(chan Push, 100),
responses: make(chan Response, 100),
logger: log,
options: ClientOptions{
Namespace: "@test/",
},
mu: sync.Mutex{},
}
}
func (m *mockClient) Run() {
for data := range m.send {
m.logger.WithField("data", string(data)).Info("received from server")
var response Response
jsoniter.ConfigFastest.Unmarshal(data, &response)
// Check message
if response.RequestID != "" {
m.mu.Lock()
// Get related channel
chn, ok := m.pending[response.RequestID]
if !ok {
// Send to generic responses I guess??
m.responses <- response
} else {
if response.Ok {
chn <- response
} else {
// Must be an error, re-parse correctly
var err Error
jsoniter.ConfigFastest.Unmarshal(data, &err)
chn <- err
}
delete(m.pending, response.RequestID)
}
m.mu.Unlock()
} else {
// Might be a push
switch response.CmdType {
case "push":
var push Push
jsoniter.ConfigFastest.Unmarshal(data, &push)
m.pushes <- push
}
}
}
}
func (c *mockClient) MakeRequest(cmd string, data map[string]interface{}) (rawMessage, <-chan interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
var requestID string
for {
// Generate Unique ID
requestID = strconv.FormatInt(rand.Int63(), 32)
// Only exit if ID is not already assigned
if _, ok := c.pending[requestID]; !ok {
break
}
}
chn := make(chan interface{}, 10)
c.pending[requestID] = chn
byt, _ := json.Marshal(Request{
CmdName: cmd,
Data: data,
RequestID: requestID,
})
return rawMessage{c, byt}, chn
}
func (c *mockClient) SetUID(uid int64) {
c.uid = uid
}
func (c *mockClient) UID() int64 {
return c.uid
}
func (c *mockClient) SendJSON(data interface{}) {
msg, _ := json.Marshal(data)
c.send <- msg
}
func (c *mockClient) SendMessage(data []byte) {
c.send <- data
}
func (c *mockClient) Options() ClientOptions {
return c.options
}
func (c *mockClient) Close() {
close(c.send)
}