forked from xelabs/go-mysqlstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmock.go
More file actions
399 lines (350 loc) · 9.97 KB
/
mock.go
File metadata and controls
399 lines (350 loc) · 9.97 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
* go-mysqlstack
* xelabs.org
*
* Copyright (c) XeLabs
* GPL License
*
*/
package driver
import (
"fmt"
"math/rand"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/xelabs/go-mysqlstack/sqldb"
"github.com/xelabs/go-mysqlstack/sqlparser/depends/sqltypes"
"github.com/xelabs/go-mysqlstack/xlog"
)
func randomPort(min int, max int) int {
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
d, delta := min, (max - min)
if delta > 0 {
d += rand.Intn(int(delta))
}
return d
}
type exprResult struct {
expr *regexp.Regexp
result *sqltypes.Result
err error
}
// CondType used for Condition type.
type CondType int
const (
// COND_NORMAL enum.
COND_NORMAL CondType = iota
// COND_DELAY enum.
COND_DELAY
// COND_ERROR enum.
COND_ERROR
// COND_PANIC enum.
COND_PANIC
// COND_STREAM enum.
COND_STREAM
)
// Cond presents a condition tuple.
type Cond struct {
// Cond type.
Type CondType
// Query string
Query string
// Query results
Result *sqltypes.Result
// Panic or Not
Panic bool
// Return Error if Error is not nil
Error error
// Delay(ms) for results return
Delay int
}
// CondList presents a list of Cond.
type CondList struct {
len int
idx int
conds []Cond
}
// SessionTuple presents a session tuple.
type SessionTuple struct {
session *Session
closed bool
killed chan bool
}
// TestHandler is the handler for testing.
type TestHandler struct {
log *xlog.Log
mu sync.RWMutex
conds map[string]*Cond
condList map[string]*CondList
ss map[uint32]*SessionTuple
// patterns is a list of regexp to results.
patterns []exprResult
patternErrors []exprResult
// How many times a query was called.
queryCalled map[string]int
}
// NewTestHandler creates new Handler.
func NewTestHandler(log *xlog.Log) *TestHandler {
return &TestHandler{
log: log,
ss: make(map[uint32]*SessionTuple),
conds: make(map[string]*Cond),
queryCalled: make(map[string]int),
condList: make(map[string]*CondList),
}
}
func (th *TestHandler) setCond(cond *Cond) {
th.mu.Lock()
defer th.mu.Unlock()
th.conds[strings.ToLower(cond.Query)] = cond
th.queryCalled[strings.ToLower(cond.Query)] = 0
}
// ResetAll resets all querys.
func (th *TestHandler) ResetAll() {
th.mu.Lock()
defer th.mu.Unlock()
for k := range th.conds {
delete(th.conds, k)
}
th.patterns = make([]exprResult, 0, 4)
th.patternErrors = make([]exprResult, 0, 4)
}
// ResetPatternErrors used to reset all the errors pattern.
func (th *TestHandler) ResetPatternErrors() {
th.patternErrors = make([]exprResult, 0, 4)
}
// ResetErrors used to reset all the errors.
func (th *TestHandler) ResetErrors() {
for k, v := range th.conds {
if v.Type == COND_ERROR {
delete(th.conds, k)
}
}
}
// SessionCheck implements the interface.
func (th *TestHandler) SessionCheck(s *Session) error {
//th.log.Debug("[%s].coming.db[%s].salt[%v].scramble[%v]", s.Addr(), s.Schema(), s.Salt(), s.Scramble())
return nil
}
// AuthCheck implements the interface.
func (th *TestHandler) AuthCheck(s *Session) error {
user := s.User()
if user != "mock" {
return sqldb.NewSQLError(sqldb.ER_ACCESS_DENIED_ERROR, "Access denied for user '%v'", user)
}
return nil
}
// NewSession implements the interface.
func (th *TestHandler) NewSession(s *Session) {
th.mu.Lock()
defer th.mu.Unlock()
st := &SessionTuple{
session: s,
killed: make(chan bool, 2),
}
th.ss[s.ID()] = st
}
// SessionClosed implements the interface.
func (th *TestHandler) SessionClosed(s *Session) {
th.mu.Lock()
defer th.mu.Unlock()
delete(th.ss, s.ID())
}
// ComInitDB implements the interface.
func (th *TestHandler) ComInitDB(s *Session, db string) error {
if strings.HasPrefix(db, "xx") {
return fmt.Errorf("mock.cominit.db.error: unkonw database[%s]", db)
}
return nil
}
// ComQuery implements the interface.
func (th *TestHandler) ComQuery(s *Session, query string, callback func(qr *sqltypes.Result) error) error {
log := th.log
query = strings.ToLower(query)
th.mu.Lock()
th.queryCalled[query]++
cond := th.conds[query]
sessTuple := th.ss[s.ID()]
th.mu.Unlock()
if cond != nil {
switch cond.Type {
case COND_DELAY:
log.Debug("test.handler.delay:%s,time:%dms", query, cond.Delay)
select {
case <-sessTuple.killed:
sessTuple.closed = true
return fmt.Errorf("mock.session[%v].query[%s].was.killed", s.ID(), query)
case <-time.After(time.Millisecond * time.Duration(cond.Delay)):
log.Debug("mock.handler.delay.done...")
}
callback(cond.Result)
return nil
case COND_ERROR:
return cond.Error
case COND_PANIC:
log.Panic("mock.handler.panic....")
case COND_NORMAL:
callback(cond.Result)
return nil
case COND_STREAM:
flds := cond.Result.Fields
// Send Fields for stream.
qr := &sqltypes.Result{Fields: flds, State: sqltypes.RStateFields}
if err := callback(qr); err != nil {
return fmt.Errorf("mock.handler.send.stream.error:%+v", err)
}
// Send Row by row for stream.
for _, row := range cond.Result.Rows {
qr := &sqltypes.Result{Fields: flds, State: sqltypes.RStateRows}
qr.Rows = append(qr.Rows, row)
if err := callback(qr); err != nil {
return fmt.Errorf("mock.handler.send.stream.error:%+v", err)
}
}
// Send EOF for stream.
qr = &sqltypes.Result{Fields: flds, State: sqltypes.RStateFinished}
if err := callback(qr); err != nil {
return fmt.Errorf("mock.handler.send.stream.error:%+v", err)
}
return nil
}
}
// kill filter.
if strings.HasPrefix(query, "kill") {
if id, err := strconv.ParseUint(strings.Split(query, " ")[1], 10, 32); err == nil {
th.mu.Lock()
if sessTuple, ok := th.ss[uint32(id)]; ok {
log.Debug("mock.session[%v].to.kill.the.session[%v]...", s.ID(), id)
if !sessTuple.closed {
sessTuple.killed <- true
}
delete(th.ss, uint32(id))
sessTuple.session.Close()
}
th.mu.Unlock()
}
callback(&sqltypes.Result{})
return nil
}
th.mu.Lock()
defer th.mu.Unlock()
// Check query patterns from AddQueryPattern().
for _, pat := range th.patternErrors {
if pat.expr.MatchString(query) {
return pat.err
}
}
for _, pat := range th.patterns {
if pat.expr.MatchString(query) {
callback(pat.result)
return nil
}
}
if v, ok := th.condList[query]; ok {
idx := 0
if v.idx >= v.len {
v.idx = 0
} else {
idx = v.idx
v.idx++
}
callback(v.conds[idx].Result)
return nil
}
return fmt.Errorf("mock.handler.query[%v].error[can.not.found.the.cond.please.set.first]", query)
}
// AddQuery used to add a query and its expected result.
func (th *TestHandler) AddQuery(query string, result *sqltypes.Result) {
th.setCond(&Cond{Type: COND_NORMAL, Query: query, Result: result})
}
// AddQuerys used to add new query rule.
func (th *TestHandler) AddQuerys(query string, results ...*sqltypes.Result) {
cl := &CondList{}
for _, r := range results {
cond := Cond{Type: COND_NORMAL, Query: query, Result: r}
cl.conds = append(cl.conds, cond)
cl.len++
}
th.condList[query] = cl
}
// AddQueryDelay used to add a query and returns the expected result after delay_ms.
func (th *TestHandler) AddQueryDelay(query string, result *sqltypes.Result, delayMs int) {
th.setCond(&Cond{Type: COND_DELAY, Query: query, Result: result, Delay: delayMs})
}
// AddQueryStream used to add a stream query.
func (th *TestHandler) AddQueryStream(query string, result *sqltypes.Result) {
th.setCond(&Cond{Type: COND_STREAM, Query: query, Result: result})
}
// AddQueryError used to add a query which will be rejected by a error.
func (th *TestHandler) AddQueryError(query string, err error) {
th.setCond(&Cond{Type: COND_ERROR, Query: query, Error: err})
}
// AddQueryPanic used to add query but underflying blackhearted.
func (th *TestHandler) AddQueryPanic(query string) {
th.setCond(&Cond{Type: COND_PANIC, Query: query})
}
// AddQueryPattern adds an expected result for a set of queries.
// These patterns are checked if no exact matches from AddQuery() are found.
// This function forces the addition of begin/end anchors (^$) and turns on
// case-insensitive matching mode.
// This code was derived from https://github.com/youtube/vitess.
func (th *TestHandler) AddQueryPattern(queryPattern string, expectedResult *sqltypes.Result) {
if len(expectedResult.Rows) > 0 && len(expectedResult.Fields) == 0 {
panic(fmt.Errorf("Please add Fields to this Result so it's valid: %v", queryPattern))
}
expr := regexp.MustCompile("(?is)^" + queryPattern + "$")
result := *expectedResult
th.mu.Lock()
defer th.mu.Unlock()
th.patterns = append(th.patterns, exprResult{expr, &result, nil})
}
// AddQueryErrorPattern used to add an query pattern with errors.
func (th *TestHandler) AddQueryErrorPattern(queryPattern string, err error) {
expr := regexp.MustCompile("(?is)^" + queryPattern + "$")
th.mu.Lock()
defer th.mu.Unlock()
th.patternErrors = append(th.patternErrors, exprResult{expr, nil, err})
}
// GetQueryCalledNum returns how many times db executes a certain query.
// This code was derived from https://github.com/youtube/vitess.
func (th *TestHandler) GetQueryCalledNum(query string) int {
th.mu.Lock()
defer th.mu.Unlock()
num, ok := th.queryCalled[strings.ToLower(query)]
if !ok {
return 0
}
return num
}
// MockMysqlServer creates a new mock mysql server.
func MockMysqlServer(log *xlog.Log, h Handler) (svr *Listener, err error) {
port := randomPort(10000, 20000)
return mockMysqlServer(log, port, h)
}
// MockMysqlServerWithPort creates a new mock mysql server with port.
func MockMysqlServerWithPort(log *xlog.Log, port int, h Handler) (svr *Listener, err error) {
return mockMysqlServer(log, port, h)
}
func mockMysqlServer(log *xlog.Log, port int, h Handler) (svr *Listener, err error) {
addr := fmt.Sprintf(":%d", port)
for i := 0; i < 5; i++ {
if svr, err = NewListener(log, addr, h); err != nil {
port = randomPort(5000, 20000)
addr = fmt.Sprintf("127.0.0.1:%d", port)
} else {
break
}
}
if err != nil {
return nil, err
}
go func() {
svr.Accept()
}()
time.Sleep(100 * time.Millisecond)
log.Debug("mock.server[%v].start...", addr)
return
}