Codebase list golang-github-go-kit-kit / 62b26ab transport / amqp / subscriber_test.go
62b26ab

Tree @62b26ab (Download .tar.gz)

subscriber_test.go @62b26abraw · history · blame

  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
package amqp_test

import (
	"context"
	"encoding/json"
	"errors"
	"testing"
	"time"

	amqptransport "github.com/go-kit/kit/transport/amqp"
	"github.com/streadway/amqp"
)

var (
	errTypeAssertion = errors.New("type assertion error")
)

// mockChannel is a mock of *amqp.Channel.
type mockChannel struct {
	f          func(exchange, key string, mandatory, immediate bool)
	c          chan<- amqp.Publishing
	deliveries []amqp.Delivery
}

// Publish runs a test function f and sends resultant message to a channel.
func (ch *mockChannel) Publish(exchange, key string, mandatory, immediate bool, msg amqp.Publishing) error {
	ch.f(exchange, key, mandatory, immediate)
	ch.c <- msg
	return nil
}

var nullFunc = func(exchange, key string, mandatory, immediate bool) {
}

func (ch *mockChannel) Consume(queue, consumer string, autoAck, exclusive, noLocal, noWail bool, args amqp.Table) (<-chan amqp.Delivery, error) {
	c := make(chan amqp.Delivery, len(ch.deliveries))
	for _, d := range ch.deliveries {
		c <- d
	}
	return c, nil
}

// TestSubscriberBadDecode checks if decoder errors are handled properly.
func TestSubscriberBadDecode(t *testing.T) {
	sub := amqptransport.NewSubscriber(
		func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
		func(context.Context, *amqp.Delivery) (interface{}, error) { return nil, errors.New("err!") },
		func(context.Context, *amqp.Publishing, interface{}) error {
			return nil
		},
		amqptransport.SubscriberErrorEncoder(amqptransport.ReplyErrorEncoder),
	)

	outputChan := make(chan amqp.Publishing, 1)
	ch := &mockChannel{f: nullFunc, c: outputChan}
	sub.ServeDelivery(ch)(&amqp.Delivery{})

	var msg amqp.Publishing
	select {
	case msg = <-outputChan:
		break

	case <-time.After(100 * time.Millisecond):
		t.Fatal("Timed out waiting for publishing")
	}
	res, err := decodeSubscriberError(msg)
	if err != nil {
		t.Fatal(err)
	}
	if want, have := "err!", res.Error; want != have {
		t.Errorf("want %s, have %s", want, have)
	}
}

// TestSubscriberBadEndpoint checks if endpoint errors are handled properly.
func TestSubscriberBadEndpoint(t *testing.T) {
	sub := amqptransport.NewSubscriber(
		func(context.Context, interface{}) (interface{}, error) { return nil, errors.New("err!") },
		func(context.Context, *amqp.Delivery) (interface{}, error) { return struct{}{}, nil },
		func(context.Context, *amqp.Publishing, interface{}) error {
			return nil
		},
		amqptransport.SubscriberErrorEncoder(amqptransport.ReplyErrorEncoder),
	)

	outputChan := make(chan amqp.Publishing, 1)
	ch := &mockChannel{f: nullFunc, c: outputChan}
	sub.ServeDelivery(ch)(&amqp.Delivery{})

	var msg amqp.Publishing

	select {
	case msg = <-outputChan:
		break

	case <-time.After(100 * time.Millisecond):
		t.Fatal("Timed out waiting for publishing")
	}

	res, err := decodeSubscriberError(msg)
	if err != nil {
		t.Fatal(err)
	}
	if want, have := "err!", res.Error; want != have {
		t.Errorf("want %s, have %s", want, have)
	}
}

// TestSubscriberBadEncoder checks if encoder errors are handled properly.
func TestSubscriberBadEncoder(t *testing.T) {
	sub := amqptransport.NewSubscriber(
		func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
		func(context.Context, *amqp.Delivery) (interface{}, error) { return struct{}{}, nil },
		func(context.Context, *amqp.Publishing, interface{}) error {
			return errors.New("err!")
		},
		amqptransport.SubscriberErrorEncoder(amqptransport.ReplyErrorEncoder),
	)

	outputChan := make(chan amqp.Publishing, 1)
	ch := &mockChannel{f: nullFunc, c: outputChan}
	sub.ServeDelivery(ch)(&amqp.Delivery{})

	var msg amqp.Publishing

	select {
	case msg = <-outputChan:
		break

	case <-time.After(100 * time.Millisecond):
		t.Fatal("Timed out waiting for publishing")
	}

	res, err := decodeSubscriberError(msg)
	if err != nil {
		t.Fatal(err)
	}
	if want, have := "err!", res.Error; want != have {
		t.Errorf("want %s, have %s", want, have)
	}
}

// TestSubscriberSuccess checks if CorrelationId and ReplyTo are set properly
// and if the payload is encoded properly.
func TestSubscriberSuccess(t *testing.T) {
	cid := "correlation"
	replyTo := "sender"
	obj := testReq{
		Squadron: 436,
	}
	b, err := json.Marshal(obj)
	if err != nil {
		t.Fatal(err)
	}

	sub := amqptransport.NewSubscriber(
		testEndpoint,
		testReqDecoder,
		amqptransport.EncodeJSONResponse,
		amqptransport.SubscriberErrorEncoder(amqptransport.ReplyErrorEncoder),
	)

	checkReplyToFunc := func(exchange, key string, mandatory, immediate bool) {
		if want, have := replyTo, key; want != have {
			t.Errorf("want %s, have %s", want, have)
		}
	}

	outputChan := make(chan amqp.Publishing, 1)
	ch := &mockChannel{f: checkReplyToFunc, c: outputChan}
	sub.ServeDelivery(ch)(&amqp.Delivery{
		CorrelationId: cid,
		ReplyTo:       replyTo,
		Body:          b,
	})

	var msg amqp.Publishing

	select {
	case msg = <-outputChan:
		break

	case <-time.After(100 * time.Millisecond):
		t.Fatal("Timed out waiting for publishing")
	}

	if want, have := cid, msg.CorrelationId; want != have {
		t.Errorf("want %s, have %s", want, have)
	}

	// check if error is not thrown
	errRes, err := decodeSubscriberError(msg)
	if err != nil {
		t.Fatal(err)
	}
	if errRes.Error != "" {
		t.Error("Received error from subscriber", errRes.Error)
		return
	}

	// check obj vals
	response, err := testResDecoder(msg.Body)
	if err != nil {
		t.Fatal(err)
	}
	res, ok := response.(testRes)
	if !ok {
		t.Error(errTypeAssertion)
	}

	if want, have := obj.Squadron, res.Squadron; want != have {
		t.Errorf("want %d, have %d", want, have)
	}
	if want, have := names[obj.Squadron], res.Name; want != have {
		t.Errorf("want %s, have %s", want, have)
	}
}

// TestNopResponseSubscriber checks if setting responsePublisher to
// NopResponsePublisher works properly by disabling response.
func TestNopResponseSubscriber(t *testing.T) {
	cid := "correlation"
	replyTo := "sender"
	obj := testReq{
		Squadron: 436,
	}
	b, err := json.Marshal(obj)
	if err != nil {
		t.Fatal(err)
	}

	sub := amqptransport.NewSubscriber(
		testEndpoint,
		testReqDecoder,
		amqptransport.EncodeJSONResponse,
		amqptransport.SubscriberResponsePublisher(amqptransport.NopResponsePublisher),
		amqptransport.SubscriberErrorEncoder(amqptransport.ReplyErrorEncoder),
	)

	checkReplyToFunc := func(exchange, key string, mandatory, immediate bool) {}

	outputChan := make(chan amqp.Publishing, 1)
	ch := &mockChannel{f: checkReplyToFunc, c: outputChan}
	sub.ServeDelivery(ch)(&amqp.Delivery{
		CorrelationId: cid,
		ReplyTo:       replyTo,
		Body:          b,
	})

	select {
	case <-outputChan:
		t.Fatal("Subscriber with NopResponsePublisher replied.")
	case <-time.After(100 * time.Millisecond):
		break
	}
}

// TestSubscriberMultipleBefore checks if options to set exchange, key, deliveryMode
// are working.
func TestSubscriberMultipleBefore(t *testing.T) {
	exchange := "some exchange"
	key := "some key"
	deliveryMode := uint8(127)
	contentType := "some content type"
	contentEncoding := "some content encoding"
	sub := amqptransport.NewSubscriber(
		func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
		func(context.Context, *amqp.Delivery) (interface{}, error) { return struct{}{}, nil },
		amqptransport.EncodeJSONResponse,
		amqptransport.SubscriberErrorEncoder(amqptransport.ReplyErrorEncoder),
		amqptransport.SubscriberBefore(
			amqptransport.SetPublishExchange(exchange),
			amqptransport.SetPublishKey(key),
			amqptransport.SetPublishDeliveryMode(deliveryMode),
			amqptransport.SetContentType(contentType),
			amqptransport.SetContentEncoding(contentEncoding),
		),
	)
	checkReplyToFunc := func(exch, k string, mandatory, immediate bool) {
		if want, have := exchange, exch; want != have {
			t.Errorf("want %s, have %s", want, have)
		}
		if want, have := key, k; want != have {
			t.Errorf("want %s, have %s", want, have)
		}
	}

	outputChan := make(chan amqp.Publishing, 1)
	ch := &mockChannel{f: checkReplyToFunc, c: outputChan}
	sub.ServeDelivery(ch)(&amqp.Delivery{})

	var msg amqp.Publishing

	select {
	case msg = <-outputChan:
		break

	case <-time.After(100 * time.Millisecond):
		t.Fatal("Timed out waiting for publishing")
	}

	// check if error is not thrown
	errRes, err := decodeSubscriberError(msg)
	if err != nil {
		t.Fatal(err)
	}
	if errRes.Error != "" {
		t.Error("Received error from subscriber", errRes.Error)
		return
	}

	if want, have := contentType, msg.ContentType; want != have {
		t.Errorf("want %s, have %s", want, have)
	}

	if want, have := contentEncoding, msg.ContentEncoding; want != have {
		t.Errorf("want %s, have %s", want, have)
	}

	if want, have := deliveryMode, msg.DeliveryMode; want != have {
		t.Errorf("want %d, have %d", want, have)
	}
}

// TestDefaultContentMetaData checks that default ContentType and Content-Encoding
// is not set as mentioned by AMQP specification.
func TestDefaultContentMetaData(t *testing.T) {
	defaultContentType := ""
	defaultContentEncoding := ""
	sub := amqptransport.NewSubscriber(
		func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
		func(context.Context, *amqp.Delivery) (interface{}, error) { return struct{}{}, nil },
		amqptransport.EncodeJSONResponse,
		amqptransport.SubscriberErrorEncoder(amqptransport.ReplyErrorEncoder),
	)
	checkReplyToFunc := func(exch, k string, mandatory, immediate bool) {}
	outputChan := make(chan amqp.Publishing, 1)
	ch := &mockChannel{f: checkReplyToFunc, c: outputChan}
	sub.ServeDelivery(ch)(&amqp.Delivery{})

	var msg amqp.Publishing

	select {
	case msg = <-outputChan:
		break

	case <-time.After(100 * time.Millisecond):
		t.Fatal("Timed out waiting for publishing")
	}

	// check if error is not thrown
	errRes, err := decodeSubscriberError(msg)
	if err != nil {
		t.Fatal(err)
	}
	if errRes.Error != "" {
		t.Error("Received error from subscriber", errRes.Error)
		return
	}

	if want, have := defaultContentType, msg.ContentType; want != have {
		t.Errorf("want %s, have %s", want, have)
	}
	if want, have := defaultContentEncoding, msg.ContentEncoding; want != have {
		t.Errorf("want %s, have %s", want, have)
	}
}

func decodeSubscriberError(pub amqp.Publishing) (amqptransport.DefaultErrorResponse, error) {
	var res amqptransport.DefaultErrorResponse
	err := json.Unmarshal(pub.Body, &res)
	return res, err
}

type testReq struct {
	Squadron int `json:"s"`
}
type testRes struct {
	Squadron int    `json:"s"`
	Name     string `json:"n"`
}

func testEndpoint(_ context.Context, request interface{}) (interface{}, error) {
	req, ok := request.(testReq)
	if !ok {
		return nil, errTypeAssertion
	}
	name, prs := names[req.Squadron]
	if !prs {
		return nil, errors.New("unknown squadron name")
	}
	res := testRes{
		Squadron: req.Squadron,
		Name:     name,
	}
	return res, nil
}

func testReqDecoder(_ context.Context, d *amqp.Delivery) (interface{}, error) {
	var obj testReq
	err := json.Unmarshal(d.Body, &obj)
	return obj, err
}

func testReqEncoder(_ context.Context, p *amqp.Publishing, request interface{}) error {
	req, ok := request.(testReq)
	if !ok {
		return errors.New("type assertion failure")
	}
	b, err := json.Marshal(req)
	if err != nil {
		return err
	}
	p.Body = b
	return nil
}

func testResDeliveryDecoder(_ context.Context, d *amqp.Delivery) (interface{}, error) {
	return testResDecoder(d.Body)
}

func testResDecoder(b []byte) (interface{}, error) {
	var obj testRes
	err := json.Unmarshal(b, &obj)
	return obj, err
}

var names = map[int]string{
	424: "tiger",
	426: "thunderbird",
	429: "bison",
	436: "tusker",
	437: "husky",
}