forked from Wr4thon/gorabbitmq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue_test.go
276 lines (229 loc) · 5.67 KB
/
queue_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
package gorabbitmq
import (
"context"
"encoding/json"
"fmt"
"reflect"
"sync"
"testing"
"time"
"github.com/labstack/gommon/log"
"github.com/pkg/errors"
)
// TestTask is used to test
type TestTask struct {
ID int `json:"id,omitempty"`
}
func TestConsume(t *testing.T) {
enqueue, err := connectToRabbit("test_queue")
if err != nil {
t.Error(err)
}
err = enqueue.Send(context.TODO(), TestTask{ID: 1337})
if err != nil {
t.Error("Could not enqueue Task: ", err)
}
fetchqueue, err := connectToRabbit("test_queue")
if err != nil {
t.Error(err)
}
go consume(fetchqueue, t)
time.Sleep(500 * time.Millisecond)
}
func consume(queue Queue, t *testing.T) {
consumerSettings := ConsumerSettings{AutoAck: false, Exclusive: false, NoLocal: false, NoWait: false}
deliveryConsumer := func(context Context) error {
if queue.IsClosed() {
return errors.New("queue channel was closed")
}
var task TestTask
err := json.Unmarshal(context.Delivery().Body, &task)
if err != nil {
log.Error(err)
nackError := context.Nack(false, true)
if nackError != nil {
fmt.Println("Failed to nack message")
}
return err
}
time.Sleep(10 * time.Millisecond)
fmt.Println("Successfully handled message")
err = context.Ack(false)
if err != nil {
fmt.Println("Failed to ack message")
}
return nil
}
err := queue.RegisterConsumer(consumerSettings, deliveryConsumer)
if err != nil {
log.Error(err)
}
}
func connectToRabbit(queueName string) (Queue, error) {
rabbitMQHost := "localhost"
if rabbitMQHost == "" {
const errMessage = "RabbitMQHost must not be empty"
return nil, errors.New(errMessage)
}
rabbitMQUser := "guest"
if rabbitMQUser == "" {
const errMessage = "RabbitMQUser must not be empty"
return nil, errors.New(errMessage)
}
rabbitMQPassword := "guest"
if rabbitMQPassword == "" {
const errMessage = "RabbitMQPassword must not be empty"
return nil, errors.New(errMessage)
}
const rabbitPort = 5672
connectionSettings := ConnectionSettings{
UserName: rabbitMQUser,
Password: rabbitMQPassword,
Host: rabbitMQHost,
Port: rabbitPort,
}
rabbit, err := NewConnection(connectionSettings, ChannelSettings{})
if err != nil {
const errMessage = "Failed to initialize rabbitmq"
return nil, errors.Wrap(err, errMessage)
}
settings := QueueSettings{
QueueName: queueName,
Durable: true,
DeleteWhenUnused: false,
Exclusive: false,
NoWait: false,
}
rabbitQueue, err := rabbit.ConnectToQueue(settings)
if err != nil {
return nil, errors.Wrap(err, "could not connect to rabbitMQ")
}
return rabbitQueue, nil
}
type loggingContextKey struct{}
func TestSendWithContext(t *testing.T) {
connection, err := NewConnection(ConnectionSettings{
Host: "localhost",
Password: "guest",
UserName: "guest",
Port: 5672,
}, ChannelSettings{
UsePrefetch: false,
})
if err != nil {
t.Log("error while creating the connection", err)
t.FailNow()
}
inputLoggingContext := map[string]interface{}{
"foo": "bar",
}
queue, err := connection.ConnectToQueue(QueueSettings{
QueueName: "test",
DeleteWhenUnused: true,
Durable: false,
Exclusive: true,
NoWait: false,
}, WithContextExtractor(func(c context.Context) (map[string]interface{}, error) {
return inputLoggingContext, nil
}), WithContextBuilder(func(m map[string]interface{}) (context.Context, error) {
return context.WithValue(context.Background(), loggingContextKey{}, m), nil
}))
if err != nil {
t.Log("error while connecting to queue", err)
t.FailNow()
}
var wg sync.WaitGroup
go func() {
queue.ConsumeOnce(ConsumerSettings{
AutoAck: false,
Exclusive: true,
NoLocal: false,
NoWait: false,
}, func(ctx Context) error {
defer wg.Done()
out, ok := ctx.DeliveryContext().Value(loggingContextKey{}).(map[string]interface{})
if !ok {
t.Fail()
}
t.Log(out)
if !validateContext(inputLoggingContext, out) {
t.Fail()
}
return nil
})
}()
wg.Add(1)
if err = queue.Send(context.TODO(), TestTask{ID: 1337}); err != nil {
panic(err)
}
wg.Wait()
}
func validateContext(in, out map[string]interface{}) bool {
return reflect.DeepEqual(in, out)
}
func Test_Middleware(t *testing.T) {
connection, err := NewConnection(ConnectionSettings{
Host: "localhost",
Password: "guest",
UserName: "guest",
Port: 5672,
}, ChannelSettings{
UsePrefetch: false,
})
if err != nil {
t.Log("error while creating the connection", err)
t.FailNow()
}
queue, err := connection.ConnectToQueue(QueueSettings{
QueueName: "test",
DeleteWhenUnused: true,
Durable: false,
Exclusive: true,
NoWait: false,
})
if err != nil {
t.Log("error while connecting to queue", err)
t.FailNow()
}
queue.SendPlainString("")
mw := Middleware()
queue.ConsumeOnce(
ConsumerSettings{
AutoAck: false,
Exclusive: true,
NoLocal: false,
NoWait: false,
}, func(ctx Context) error {
return errors.New("something")
}, mw)
}
type customContext struct {
Context
errorCounter int
}
func Middleware() MiddlewareFunc {
return func(hf HandlerFunc) HandlerFunc {
return func(c Context) error {
ctx := customContext{
Context: c,
}
if v, ok := ctx.Delivery().Headers["@errorCounter"]; ok {
if i, ok := v.(int); ok {
ctx.errorCounter = i
}
}
err := hf(ctx)
if err != nil {
ctx.errorCounter++
ctx.Ack(false)
table := ctx.Delivery().Headers
if table == nil {
table = make(map[string]interface{})
}
table["@errorCounter"] = ctx.errorCounter
c.Queue().SendWithTable(ctx.Context.DeliveryContext(), ctx.Delivery().Body, table)
}
return err
}
}
}