-
Notifications
You must be signed in to change notification settings - Fork 17
/
kamevapi_test.go
634 lines (586 loc) · 16.1 KB
/
kamevapi_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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
/*
Released under MIT License <http://www.opensource.org/licenses/mit-license.php
Copyright (C) ITsysCOM GmbH. All Rights Reserved.
Provides Kamailio evapi socket communication.
*/
package kamevapi
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"reflect"
"regexp"
"strings"
"sync"
"testing"
"time"
)
var authRequest = `188:{"event":"CGR_AUTH_REQUEST",
"tr_index":"35215",
"tr_label":"852281699",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_setuptime":"1420142013"},`
var callStart = `264:{"event":"CGR_CALL_START",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"h_entry":"2395",
"h_id":"2711",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016"},`
var callEnd = `248:{"event":"CGR_CALL_END",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016",
"cgr_duration":"6"},`
func TestDispatchEvent(t *testing.T) {
r, w, err := os.Pipe()
if err != nil {
t.Error("Error creating pipe!")
}
kea = &KamEvapi{}
kea.rcvBuffer = bufio.NewReader(r)
var events []string
kea.eventHandlers = map[*regexp.Regexp][]func([]byte, int){
regexp.MustCompile(".*"): {func(ev []byte, ignr int) { events = append(events, string(ev)) }},
}
go kea.readEvents(make(chan struct{}), make(chan error))
w.WriteString(authRequest)
w.WriteString(callStart)
w.WriteString(callEnd)
time.Sleep(50 * time.Millisecond)
expectEvents := []string{
`{"event":"CGR_AUTH_REQUEST",
"tr_index":"35215",
"tr_label":"852281699",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_setuptime":"1420142013"}`, `{"event":"CGR_CALL_START",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"h_entry":"2395",
"h_id":"2711",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016"}`, `{"event":"CGR_CALL_END",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016",
"cgr_duration":"6"}`,
}
expectEvents2 := []string{
`{"event":"CGR_CALL_END",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016",
"cgr_duration":"6"}`,
`{"event":"CGR_AUTH_REQUEST",
"tr_index":"35215",
"tr_label":"852281699",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_setuptime":"1420142013"}`, `{"event":"CGR_CALL_START",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"h_entry":"2395",
"h_id":"2711",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016"}`,
}
expectEvents3 := []string{
`{"event":"CGR_CALL_END",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016",
"cgr_duration":"6"}`, `{"event":"CGR_CALL_START",
"callid":"fcab096696848e58191ed79fdd732751@0:0:0:0:0:0:0:0",
"from_tag":"4c759c18",
"h_entry":"2395",
"h_id":"2711",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_answertime":"1420142016"}`,
`{"event":"CGR_AUTH_REQUEST",
"tr_index":"35215",
"tr_label":"852281699",
"cgr_reqtype":"postpaid",
"cgr_account":"1001",
"cgr_destination":"1002",
"cgr_setuptime":"1420142013"}`,
}
if !reflect.DeepEqual(expectEvents, events) &&
!reflect.DeepEqual(expectEvents2, events) &&
!reflect.DeepEqual(expectEvents3, events) {
t.Errorf("Received events: %+v", events)
}
}
func TestKamevapiFib(t *testing.T) {
fib := fibDuration(time.Second, 0)
f := fib()
expected := 1 * time.Second
if expected != f {
t.Errorf("Exptected %v but received %v", expected, f)
}
f = fib()
expected = 1 * time.Second
if expected != f {
t.Errorf("Exptected %v but received %v", expected, f)
}
f = fib()
expected = 2 * time.Second
if expected != f {
t.Errorf("Exptected %v but received %v", expected, f)
}
f = fib()
expected = 3 * time.Second
if expected != f {
t.Errorf("Exptected %v but received %v", expected, f)
}
f = fib()
expected = 5 * time.Second
if expected != f {
t.Errorf("Exptected %v but received %v", expected, f)
}
}
func TestNewKamEvapiError(t *testing.T) {
var err error
errExpect := "KamEvapi dial tcp 127.0.0.1:9435: connect: connection refused"
if kea, err = NewKamEvapi("127.0.0.1:9435", 0, 3, 0, fibDuration, nil, nil); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestReadevents(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:9435")
if err != nil {
t.Fatal(err)
}
go l.Accept()
defer l.Close()
if err != nil {
t.Fatal("Cannot connect to syslog:", err)
}
if kea, err = NewKamEvapi("127.0.0.1:9435", 0, 3, 0, fibDuration, nil, new(nopLogger)); err != nil {
t.Fatal("Could not create KamEvapi, error: ", err)
}
exitChan := make(chan struct{}, 1)
errorChan := make(chan error, 1)
errorChan <- err
close(exitChan)
kea.readEvents(exitChan, errorChan)
}
func makeNewKea() *KamEvapi {
l, err := net.Listen("tcp", "127.0.0.1:9435")
if err != nil {
fmt.Println(err)
}
go l.Accept()
defer l.Close()
if err != nil {
fmt.Println("Cannot connect to syslog:", err)
}
if kea, err = NewKamEvapi("127.0.0.1:9435", 0, 3, 0, fibDuration, nil, new(nopLogger)); err != nil {
fmt.Println(err)
}
return kea
}
func TestConnectError(t *testing.T) {
kea := makeNewKea()
mckChan := make(chan struct{})
kea.stopReadEvents = mckChan
kea.Connect()
}
func TestSend(t *testing.T) {
kea := makeNewKea()
if err := kea.Send("test"); err != nil {
t.Error(err)
}
}
func TestRemoteAddr(t *testing.T) {
kea := makeNewKea()
if err := kea.RemoteAddr(); err == nil {
t.Error("Address shouldn't be nil")
}
}
type mockConn struct{}
func (mockConn) Close() error { return errors.New("error") }
func (mockConn) Read(b []byte) (n int, err error) { return 0, nil }
func (mockConn) Write(b []byte) (n int, err error) { return 0, nil }
func (mockConn) LocalAddr() net.Addr { return &net.IPAddr{} }
func (mockConn) RemoteAddr() net.Addr { return &net.IPAddr{} }
func (mockConn) SetDeadline(t time.Time) error { return nil }
func (mockConn) SetReadDeadline(t time.Time) error { return nil }
func (mockConn) SetWriteDeadline(t time.Time) error { return nil }
type testLogger struct {
*log.Logger
}
func (l *testLogger) Alert(msg string) error {
l.Println(msg)
return nil
}
func (l *testLogger) Close() error {
return nil
}
func (l *testLogger) Crit(msg string) error {
l.Println(msg)
return nil
}
func (l *testLogger) Debug(msg string) error {
l.Println(msg)
return nil
}
func (l *testLogger) Emerg(msg string) error {
l.Println(msg)
return nil
}
func (l *testLogger) Err(msg string) error {
l.Println(msg)
return nil
}
func (l *testLogger) Notice(msg string) error {
l.Println(msg)
return nil
}
func (l *testLogger) Warning(msg string) error {
l.Println(msg)
return nil
}
func (l *testLogger) Info(msg string) error {
l.Println(msg)
return nil
}
func TestReadEventsErrDisconnect(t *testing.T) {
mckConn := new(mockConn)
kea := &KamEvapi{
errReadEvents: make(chan error, 1),
connMutex: &sync.RWMutex{},
conn: mckConn,
logger: nopLogger{},
}
kea.errReadEvents <- io.EOF
errExpect := "error"
var capturedLogBuffer bytes.Buffer
originalLogger := kea.logger
kea.logger = &testLogger{log.New(&capturedLogBuffer, "", 0)}
bufExpect := "Disconnecting from"
if err := kea.ReadEvents(); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but received %v", errExpect, err)
} else if rcv := capturedLogBuffer.String(); !strings.Contains(rcv, bufExpect) {
t.Errorf("Expected %s but received %s", bufExpect, rcv)
}
kea.logger = originalLogger
}
func TestReadEventsErrNotConnected(t *testing.T) {
c1, _ := net.Pipe()
kea := &KamEvapi{
errReadEvents: make(chan error, 1),
connMutex: &sync.RWMutex{},
conn: c1,
logger: nopLogger{},
delayFunc: fibDuration,
}
kea.errReadEvents <- io.EOF
errExpect := "Not connected to Kamailio"
if err := kea.ReadEvents(); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but recevied %v", errExpect, err)
}
}
func TestReadEventsErrNotEOF(t *testing.T) {
c1, _ := net.Pipe()
kea := &KamEvapi{
errReadEvents: make(chan error, 1),
connMutex: &sync.RWMutex{},
conn: c1,
logger: nopLogger{},
}
kea.errReadEvents <- errors.New("not EOF!")
errExpect := "not EOF!"
if err := kea.ReadEvents(); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but recevied %v", errExpect, err)
}
}
func TestSendAsNetstring(t *testing.T) {
w, r := net.Pipe() //w -> server & r -> client
kea := &KamEvapi{
conn: w,
connMutex: new(sync.RWMutex),
}
ch := make(chan string)
go func() {
b := make([]byte, 512)
n, err := r.Read(b)
if err != nil {
t.Error(err)
ch <- ""
return
}
ch <- string(b[:n])
}()
if err := kea.sendAsNetstring("string!"); err != nil {
t.Fatal(err)
}
rcv := <-ch
rcvExpect := "7:string!,"
if rcv != rcvExpect {
t.Errorf("Expected %s but received %s", rcvExpect, rcv)
}
}
func TestReadNetstring(t *testing.T) {
kea := &KamEvapi{
rcvBuffer: bufio.NewReader(bytes.NewBufferString("7:string!,")),
}
rcv, err := kea.readNetstring()
if err != nil {
t.Error(err)
}
rcvExpect := []byte("string!")
if !reflect.DeepEqual(rcv, rcvExpect) {
t.Errorf("Expected %s but received %s", rcvExpect, rcv)
}
}
func TestReadNetstringError1(t *testing.T) {
kea := &KamEvapi{
rcvBuffer: bufio.NewReader(bytes.NewBufferString("3:string")),
}
errExpect := "Crosschecking netstring failed, no comma in the end but: i"
if _, err := kea.readNetstring(); err == nil || errExpect != err.Error() {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestReadNetstringError2(t *testing.T) {
kea := &KamEvapi{
rcvBuffer: bufio.NewReader(bytes.NewBufferString(":string")),
}
errExpect := `strconv.Atoi: parsing "": invalid syntax`
if _, err := kea.readNetstring(); err == nil || errExpect != err.Error() {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestReadNetstringError3(t *testing.T) {
kea := &KamEvapi{
rcvBuffer: bufio.NewReader(bytes.NewBufferString("7:string,")), //It is not valid because it is not "7:string!,"
}
errExpect := io.EOF
if _, err := kea.readNetstring(); err == nil || errExpect != err {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestReadNetstringError4(t *testing.T) {
kea := &KamEvapi{
rcvBuffer: bufio.NewReader(bytes.NewBufferString("10:string,")), //It is not valid because it is not "7:string!,"
}
errExpect := io.EOF
if _, err := kea.readNetstring(); err == nil || errExpect != err {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestRemoteAddrErr(t *testing.T) {
kea := &KamEvapi{
conn: nil,
connMutex: &sync.RWMutex{},
}
if err := kea.RemoteAddr(); err != nil {
t.Error(err)
}
}
func TestSendErr(t *testing.T) {
kea := &KamEvapi{
conn: nil,
connMutex: &sync.RWMutex{},
delayFunc: fibDuration,
}
errExpect := "Not connected to Kamailio"
if err := kea.Send("idk"); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestReconnectIfNeeded(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:9435")
if err != nil {
fmt.Println(err)
}
go l.Accept()
defer l.Close()
kea := &KamEvapi{
kamaddr: "127.0.0.1:9435",
connMutex: &sync.RWMutex{},
conn: nil,
reconnects: 4,
delayFunc: fibDuration,
}
if err := kea.ReconnectIfNeeded(); err != nil {
t.Error(err)
}
}
func TestReconnectIfNeeded2(t *testing.T) {
kea := &KamEvapi{
kamaddr: "127.0.0.1:9435",
connMutex: &sync.RWMutex{},
conn: nil,
reconnects: 4,
delayFunc: fibDuration,
}
errExpect := "KamEvapi dial tcp 127.0.0.1:9435: connect: connection refused"
if err := kea.ReconnectIfNeeded(); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestDispatchEventErr(t *testing.T) {
kea := &KamEvapi{
connIdx: 2,
eventHandlers: map[*regexp.Regexp][]func([]byte, int){
// regexp.MustCompile(".*"): []func([]byte, int){},
},
logger: nopLogger{},
}
var capturedLogBuffer bytes.Buffer
originalLogger := kea.logger
kea.logger = &testLogger{log.New(&capturedLogBuffer, "", 0)}
bufExpect := "No handler for inbound data: test"
kea.dispatchEvent([]byte("test"))
if rcv := capturedLogBuffer.String(); !strings.Contains(rcv, bufExpect) {
t.Errorf("Expected %s but received %s", bufExpect, rcv)
}
kea.logger = originalLogger
}
// Test for KamEvapiPool
func TestNewKamEvapiPool(t *testing.T) {
var err error
if _, err = NewKamEvapiPool(2, "127.0.0.1:9435", 0, 3, 0, fibDuration, new(nopLogger)); err != nil {
t.Fatal("Could not create KamEvapi, error: ", err)
}
}
func TestPushKamEvapi(t *testing.T) { //When keap nor kea are nil
conns := make(chan *KamEvapi, 1)
keap := &KamEvapiPool{
allowedConns: make(chan struct{}, 1),
conns: conns,
}
kea := makeNewKea()
keap.PushKamEvapi(kea)
// fmt.Println(<-keap.conns)
// fmt.Println(kea)
if !reflect.DeepEqual(kea, <-keap.conns) {
t.Errorf("Expected %v but received %v", kea, keap.conns)
}
}
func TestPushKamEvapiErr1(t *testing.T) { //When kea is not connected
conns := make(chan *KamEvapi, 1)
keap := &KamEvapiPool{
allowedConns: make(chan struct{}, 1),
conns: conns,
}
kea := makeNewKea()
kea.conn = nil
keap.PushKamEvapi(kea)
}
func TestPushKamEvapiErr2(t *testing.T) { //When keap is nil
var kp *KamEvapiPool
kea := makeNewKea()
kp.PushKamEvapi(kea)
}
func TestPopKamEvapiErr(t *testing.T) { //When can't connect to Kameilio
conns := make(chan *KamEvapi, 1)
keap := &KamEvapiPool{
allowedConns: make(chan struct{}, 1),
conns: conns,
kamAddr: "127.0.0.1:9435",
connIdx: 0,
reconnects: 2,
logger: nopLogger{},
}
var test struct{}
keap.allowedConns <- test
errExpect := "KamEvapi dial tcp 127.0.0.1:9435: connect: connection refused"
if _, err := keap.PopKamEvapi(); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func TestPopKamEvapi(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:9435")
if err != nil {
t.Fatal(err)
}
go l.Accept()
defer l.Close()
conns := make(chan *KamEvapi, 1)
keap := &KamEvapiPool{
allowedConns: make(chan struct{}, 1),
conns: conns,
kamAddr: "127.0.0.1:9435",
connIdx: 0,
reconnects: 2,
logger: nopLogger{},
}
var idk struct{}
keap.allowedConns <- idk
if _, err := keap.PopKamEvapi(); err != nil {
t.Error(err)
}
}
func TestPopKamEvapi2(t *testing.T) { //When len(keap.conns) != 0
l, err := net.Listen("tcp", "127.0.0.1:9435")
if err != nil {
t.Fatal(err)
}
go l.Accept()
defer l.Close()
conns := make(chan *KamEvapi, 1)
keap := &KamEvapiPool{
allowedConns: make(chan struct{}, 1),
conns: conns,
kamAddr: "127.0.0.1:9435",
connIdx: 0,
reconnects: 2,
logger: nopLogger{},
}
// var idk struct{}
// keap.allowedConns <- idk
keap.conns <- &KamEvapi{}
if _, err := keap.PopKamEvapi(); err != nil {
t.Error(err)
}
}
func TestPopKamEvapi3(t *testing.T) {
var kp *KamEvapiPool
errExpect := "UNCONFIGURED_KAMAILIO_POOL"
if _, err := kp.PopKamEvapi(); err == nil || err.Error() != errExpect {
t.Errorf("Expected %v but received %v", errExpect, err)
}
}
func fibDuration(durationUnit, maxDuration time.Duration) func() time.Duration {
a, b := 0, 1
return func() time.Duration {
a, b = b, a+b
fibNrAsDuration := time.Duration(a) * durationUnit
if maxDuration > 0 && maxDuration < fibNrAsDuration {
return maxDuration
}
return fibNrAsDuration
}
}