-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmq_test.go
660 lines (561 loc) · 15.8 KB
/
mq_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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
package mq
import (
"encoding/json"
"flag"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/NeowayLabs/wabbit/amqptest/server"
"gopkg.in/yaml.v1"
)
const (
dsnForTests = "amqp://guest:guest@localhost:5672/"
defaultConsumerName = "default_consumer"
defaultExchangeName = "default_exchange"
defaultExchangeType = "direct"
defaultQueueName = "default_queue"
defaultAsyncProducerName = "default_async_producer"
defaultSyncProducerName = "default_sync_producer"
defaultRoutingKey = "routing_key"
)
func init() {
flag.BoolVar(&brokerIsMocked, "mock-broker", true, "Whether to mock broker or to use a real one. 0: use real broker. 1: use mocked broker.")
}
func TestMq_ConnectToStoppedBroker(t *testing.T) {
if !brokerIsMocked {
t.Skip("We can't stop real broker from test.")
}
_, err := New(Config{
DSN: dsnForTests,
})
if err == nil {
t.Error("Mq must not successfully connect to the broker when it's stopped.")
}
}
func TestMq_ProduceConsume(t *testing.T) {
if brokerIsMocked {
broker := server.NewServer(dsnForTests)
requireNoError(t, broker.Start(), "Failed to start broker")
defer broker.Stop()
}
cases := []struct {
Name string
Config func() (Config, error)
}{
{
"with internal struct config",
func() (Config, error) {
return newDefaultConfig(), nil
},
},
{
"with json config",
func() (Config, error) {
marshaled, err := json.Marshal(newDefaultConfig())
requireNoError(t, err, "Failed marshal config to json")
config := Config{}
err = json.Unmarshal(marshaled, &config)
requireNoError(t, err, "Failed unmarshal test data")
return config, nil
},
},
{
"with yaml config",
func() (Config, error) {
marshaled, err := yaml.Marshal(newDefaultConfig())
requireNoError(t, err, "Failed marshal config to yaml")
config := Config{}
err = yaml.Unmarshal(marshaled, &config)
requireNoError(t, err, "Failed unmarshal test data")
return config, err
},
},
}
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
config, err := tc.Config()
requireNoError(t, err, "Failed to get config for test")
mq, err := New(config)
requireNoError(t, err, "Failed to create a new instance of MessageQueue")
defer mq.Close()
done := make(chan struct{})
go func() {
for {
select {
case err := <-mq.Error():
assertNoError(t, err, "Unexpected error from queue")
case <-done:
return
}
}
}()
expectedMessage := []byte("test")
asyncProducer, err := mq.AsyncProducer(defaultAsyncProducerName)
requireNoError(t, err, "Failed to get registered producer")
asyncProducer.Produce(expectedMessage)
syncProducer, err := mq.SyncProducer(defaultSyncProducerName)
requireNoError(t, err, "Failed to get registered producer")
err = syncProducer.Produce(expectedMessage)
requireNoError(t, err, "Failed to produce message")
var messageWasRead int32
handler := func(message Message) {
atomic.AddInt32(&messageWasRead, 1)
if !isSliceOfBytesIsEqual(expectedMessage, message.Body()) {
assertNoError(t, message.Reject(false))
t.Errorf("Actual message '%s' is not equal to expected '%s'", message.Body(), expectedMessage)
}
assertNoError(t, message.Ack(false))
}
err = mq.SetConsumerHandler(defaultConsumerName, handler)
requireNoError(t, err)
waitForMessageDelivery()
readMessages := atomic.LoadInt32(&messageWasRead)
if readMessages != 2 {
t.Errorf("Consumer did not read messages. Produced %d, read %d", 2, readMessages)
}
assertNoMqError(t, mq)
done <- struct{}{}
})
}
}
func newDefaultConfig() Config {
return Config{
DSN: dsnForTests,
Consumers: Consumers{{
Name: defaultConsumerName,
Queue: defaultQueueName,
PrefetchCount: 1,
Workers: 4,
Options: Options{
"no_local": false, // Just for example.
},
}},
Exchanges: Exchanges{{
Name: defaultExchangeName,
Type: defaultExchangeType,
Options: Options{
"durable": false,
},
}},
Queues: Queues{{
Name: defaultQueueName,
Exchange: defaultExchangeName,
RoutingKey: defaultRoutingKey,
Options: Options{
"durable": false,
"args": map[string]interface{}{
"x-max-priority": 9,
},
},
}},
Producers: Producers{
{
Name: defaultAsyncProducerName,
Exchange: defaultExchangeName,
RoutingKey: defaultRoutingKey,
Options: Options{
"delivery_mode": 1,
},
},
{
Name: defaultSyncProducerName,
Exchange: defaultExchangeName,
RoutingKey: defaultRoutingKey,
Sync: true,
Options: Options{
"delivery_mode": 1,
},
},
},
}
}
func TestMq_Reconnect(t *testing.T) {
if !brokerIsMocked {
t.Skip("We can't stop real broker from test.")
}
broker := server.NewServer(dsnForTests)
requireNoError(t, broker.Start(), "Failed to start broker")
messageQueue, err := New(Config{
DSN: dsnForTests,
ReconnectDelay: time.Nanosecond,
Consumers: Consumers{{
Name: defaultConsumerName,
Queue: defaultQueueName,
PrefetchCount: 1,
Workers: 1,
}},
Exchanges: Exchanges{{
Name: defaultExchangeName,
Type: defaultExchangeType,
}},
Queues: Queues{{
Name: defaultQueueName,
Exchange: defaultExchangeName,
RoutingKey: defaultRoutingKey,
}},
Producers: Producers{
{
BufferSize: 1,
Name: defaultAsyncProducerName,
Exchange: defaultExchangeName,
RoutingKey: defaultRoutingKey,
},
{
Name: defaultSyncProducerName,
Exchange: defaultExchangeName,
RoutingKey: defaultRoutingKey,
Sync: true,
},
},
})
requireNoError(t, err, "Can't create a new instance of MessageQueue")
expectedMessage := []byte("test")
var messageWasRead int32
handler := func(message Message) {
atomic.AddInt32(&messageWasRead, 1)
if !isSliceOfBytesIsEqual(expectedMessage, message.Body()) {
assertNoError(t, message.Reject(false))
t.Errorf("Actual message '%s' is not equal to expected '%s'", message.Body(), expectedMessage)
}
assertNoError(t, message.Ack(false))
}
err = messageQueue.SetConsumerHandler(defaultConsumerName, handler)
requireNoError(t, err, "Failed to set consumer handler")
runtime.Gosched() // Required for running tests in build machine where only 1 cpu is available.
// Force reconnect
requireNoError(t, broker.Stop(), "Failed to stop broker")
// Produce when connection to broker is down.
asyncProducer, err := messageQueue.AsyncProducer(defaultAsyncProducerName)
requireNoError(t, err, "Failed to get registered producer")
asyncProducer.Produce(expectedMessage)
syncProducer, err := messageQueue.SyncProducer(defaultSyncProducerName)
requireNoError(t, err, "Failed to get registered producer")
requireNoError(t, syncProducer.Produce(expectedMessage), "Sync producer error")
requireNoError(t, broker.Start(), "Failed to start broker")
defer broker.Stop()
waitForMessageDelivery()
readMessages := atomic.LoadInt32(&messageWasRead)
if readMessages != 2 {
t.Errorf("Consumer did not read messages. Produced %d, read %d", 2, readMessages)
}
messageQueue.Close()
}
func TestMq_Consumer_Exists(t *testing.T) {
if brokerIsMocked {
broker := server.NewServer(dsnForTests)
requireNoError(t, broker.Start())
defer broker.Stop()
}
mq, err := New(Config{
DSN: dsnForTests,
Consumers: Consumers{{
Name: defaultConsumerName,
Queue: defaultQueueName,
}},
Exchanges: Exchanges{{
Name: defaultExchangeName,
Type: defaultExchangeType,
}},
Queues: Queues{{
Name: defaultQueueName,
Exchange: defaultExchangeName,
Options: Options{
"args": map[interface{}]interface{}{
"x-max-priority": byte(9),
},
},
}},
})
requireNoError(t, err, "Can't create a new instance of MessageQueue")
defer mq.Close()
_, err = mq.Consumer(defaultConsumerName)
assertNoError(t, err, "Failed to get a consumer")
assertNoMqError(t, mq)
}
func TestMq_Consumer_NotExists(t *testing.T) {
if brokerIsMocked {
broker := server.NewServer(dsnForTests)
requireNoError(t, broker.Start())
defer broker.Stop()
}
mq, err := New(Config{
DSN: dsnForTests,
})
requireNoError(t, err, "Can't create a new instance of MessageQueue")
defer mq.Close()
_, err = mq.Consumer("nonexistent_consumer")
if err == nil {
t.Error("Did not catch an error during the retrieval of non-existent consumer.")
}
assertNoMqError(t, mq)
}
func TestMq_Producer_Exists(t *testing.T) {
if brokerIsMocked {
broker := server.NewServer(dsnForTests)
requireNoError(t, broker.Start())
defer broker.Stop()
}
mq, err := New(Config{
DSN: dsnForTests,
Exchanges: Exchanges{{
Name: defaultExchangeName,
Type: defaultExchangeType,
}},
Queues: Queues{{
Name: defaultQueueName,
Exchange: defaultExchangeName,
Options: Options{
"args": map[interface{}]interface{}{
"x-max-priority": byte(9),
},
},
}},
Producers: Producers{
{
Name: defaultAsyncProducerName,
Exchange: defaultExchangeName,
},
{
Name: defaultSyncProducerName,
Exchange: defaultExchangeName,
Sync: true,
},
},
})
requireNoError(t, err, "Can't create a new instance of MessageQueue")
defer mq.Close()
_, err = mq.AsyncProducer(defaultAsyncProducerName)
assertNoError(t, err, "Failed to get an async producer")
_, err = mq.SyncProducer(defaultSyncProducerName)
assertNoError(t, err, "Failed to get an sync producer")
assertNoMqError(t, mq)
}
func TestMq_Producer_NonExistent(t *testing.T) {
if brokerIsMocked {
broker := server.NewServer(dsnForTests)
requireNoError(t, broker.Start())
defer broker.Stop()
}
mq, err := New(Config{
DSN: dsnForTests,
})
requireNoError(t, err, "Can't create a new instance of MessageQueue")
defer mq.Close()
_, err = mq.AsyncProducer("nonexistent_producer")
if err == nil {
t.Error("No error got during getting non existent async producer")
}
_, err = mq.SyncProducer("nonexistent_producer")
if err == nil {
t.Error("No error got during getting non existent sync producer")
}
assertNoMqError(t, mq)
}
func TestMq_SetConsumerHandler_NonExistentConsumer(t *testing.T) {
if brokerIsMocked {
broker := server.NewServer(dsnForTests)
requireNoError(t, broker.Start())
defer broker.Stop()
}
mq, err := New(Config{
DSN: dsnForTests,
})
requireNoError(t, err, "Can't create a new instance of MessageQueue")
defer mq.Close()
err = mq.SetConsumerHandler("unknown consumer", func(_ Message) {})
if err == nil {
t.Error("No error got during setting handler for non existent consumer")
}
assertNoMqError(t, mq)
}
func TestMq_New_InvalidQueueConfiguration(t *testing.T) {
if brokerIsMocked {
t.Skip("Wabbit can't validate configuration.")
}
_, err := New(Config{
DSN: dsnForTests,
Queues: Queues{{
Exchange: "unknown exchange",
}},
})
if err == nil {
t.Error("New must return error if invalid configuration is provided")
}
}
func TestMq_New_InvalidExchangeConfiguration(t *testing.T) {
if brokerIsMocked {
t.Skip("Wabbit can't validate configuration.")
}
_, err := New(Config{
DSN: dsnForTests,
Exchanges: Exchanges{{
Type: "invalid",
}},
})
if err == nil {
t.Error("New must return error if invalid configuration is provided")
}
}
func TestMq_New_InvalidConsumerConfiguration(t *testing.T) {
if brokerIsMocked {
t.Skip("Wabbit can't validate configuration.")
}
_, err := New(Config{
DSN: dsnForTests,
Consumers: Consumers{{
Queue: "unknown queue",
}},
})
if err == nil {
t.Error("New must return error if invalid configuration is provided")
}
}
func Test_mq_createConnection(t *testing.T) {
cases := []struct {
name string
dsn string
checkList []string
}{
{name: "single dsn", dsn: dsnForTests, checkList: []string{dsnForTests}},
{name: "cluster dsn", dsn: "amqp://guest:guest@localhost:5672/1,amqp://guest:guest@localhost:5672/2,amqp://guest:guest@localhost:5672/3",
checkList: []string{"amqp://guest:guest@localhost:5672/1", "amqp://guest:guest@localhost:5672/2", "amqp://guest:guest@localhost:5672/3", "amqp://guest:guest@localhost:5672/1"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cfg := newDefaultConfig()
cfg.DSN = tc.dsn
cfg.TestMode = true
cfg.normalize()
mq := &MessageQueue{
config: cfg,
errorChannel: make(chan error),
internalErrorChannel: make(chan error),
consumers: newConsumersRegistry(len(cfg.Consumers)),
producers: newProducersRegistry(len(cfg.Producers)),
}
defer mq.Close()
for _, dsn := range tc.checkList {
_, _ = mq.createConnection()
curBroker := mq.config.dsnList[mq.cluster.currentNode]
if curBroker != dsn {
t.Errorf("createConnection() current broker %v, expected broker %v", curBroker, dsn)
return
}
}
})
}
}
func TestMq_ConnectionState(t *testing.T) {
cases := []struct {
name string
expected ConnectionState
}{
{name: "status disconnected", expected: ConnectionStateDisconnected},
{name: "status changed", expected: ConnectionStateConnecting},
}
for _, tc := range cases {
cfg := newDefaultConfig()
cfg.TestMode = true
cfg.normalize()
mq := &MessageQueue{
config: cfg,
errorChannel: make(chan error),
internalErrorChannel: make(chan error),
consumers: newConsumersRegistry(len(cfg.Consumers)),
producers: newProducersRegistry(len(cfg.Producers)),
state: new(int32),
}
atomic.StoreInt32(mq.state, int32(tc.expected))
t.Run(tc.name, func(t *testing.T) {
defer mq.Close()
if mq.ConnectionState() != tc.expected {
t.Errorf("ConnectionState() current value %v, expected broker %v", mq.ConnectionState(), tc.expected)
}
})
}
}
func TestMq_connect(t *testing.T) {
s := server.NewServer(dsnForTests)
_ = s.Start()
defer func() { _ = s.Stop() }()
cases := []struct {
name string
expected ConnectionState
isConnectError bool
isChannelError bool
}{
{name: "success connect", expected: ConnectionStateConnected},
{name: "failed to connect", expected: ConnectionStateDisconnected, isConnectError: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cfg := newDefaultConfig()
cfg.TestMode = true
cfg.normalize()
mq := &MessageQueue{
config: cfg,
errorChannel: make(chan error),
internalErrorChannel: make(chan error),
consumers: newConsumersRegistry(len(cfg.Consumers)),
producers: newProducersRegistry(len(cfg.Producers)),
state: new(int32),
}
defer mq.Close()
if tc.isConnectError {
_ = s.Stop()
}
err := mq.connect()
if err != nil && !tc.isConnectError {
t.Errorf("connect() no error expected, but got: %v", err)
}
if mq.ConnectionState() != tc.expected {
t.Errorf("connect() expected state %v, got: %v", tc.expected, mq.ConnectionState())
}
})
}
}
func assertNoMqError(t *testing.T, mq *MessageQueue) {
select {
case err := <-mq.Error():
t.Error("Caught an unexpected error from MessageQueue: ", err)
default:
}
}
func waitForMessageDelivery() {
time.Sleep(10 * time.Millisecond)
}
func isSliceOfBytesIsEqual(expected, actual []byte) bool {
if expected == nil && actual == nil {
return true
}
if expected == nil || actual == nil {
return false
}
if len(expected) != len(actual) {
return false
}
for i := range expected {
if expected[i] != actual[i] {
return false
}
}
return true
}
func assertNoError(t *testing.T, err error, message ...string) {
if err != nil {
if len(message) == 0 {
message = []string{"Unexpected error"}
}
t.Error(strings.Join(message, " ")+":", err)
}
}
func requireNoError(t *testing.T, err error, message ...string) {
if err != nil {
if len(message) == 0 {
message = []string{"Unexpected error"}
}
t.Fatal(strings.Join(message, " ")+":", err)
}
}