-
Notifications
You must be signed in to change notification settings - Fork 2
/
rabbit_test.go
124 lines (111 loc) · 2.48 KB
/
rabbit_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
package rabbit_test
import (
"encoding/json"
"log"
"os"
"testing"
"time"
"github.com/brettallred/go-rabbit"
"github.com/streadway/amqp"
"github.com/stretchr/testify/assert"
)
type TestEvent struct {
Name string `json:"Name"`
Email string `json:"Email"`
}
func sampleTestEventCreatedHandler(delivery amqp.Delivery) bool {
event := TestEvent{}
json.Unmarshal(delivery.Body, &event)
log.Printf("%s", event)
return true
}
/*
TESTS
*/
var subscriber = rabbit.Subscriber{
Concurrency: 5,
Durable: true,
Exchange: "events_test",
Queue: "test.sample.event.created",
RoutingKey: "sample.event.created",
}
func init() {
os.Setenv("RABBITMQ_URL", "amqp://guest:guest@localhost:5672/")
}
func TestRegister(t *testing.T) {
rabbit.Register(subscriber, sampleTestEventCreatedHandler)
assert := assert.New(t)
assert.Equal(1, len(rabbit.Subscribers), "Expected 1 Subscriber")
assert.Equal(1, len(rabbit.Handlers), "Expected 1 Handler")
}
func TestNack(t *testing.T) {
recreateQueue(t, &subscriber)
counter := 0
done := make(chan bool, 2)
nackHandler := func(delivery amqp.Delivery) bool {
counter++
done <- true
if counter == 1 {
return false
}
return true
}
rabbit.Register(subscriber, nackHandler)
rabbit.StartSubscribers()
rabbit.NewPublisher(make(chan bool)).Publish("{}", &subscriber)
for i := 0; i < 2; i++ {
select {
case <-done:
break
case <-time.After(1 * time.Second):
break
}
}
rabbit.CloseSubscribers()
assert.Equal(t, 2, counter)
}
func TestStartingSubscribers(t *testing.T) {
rabbit.Register(subscriber, sampleTestEventCreatedHandler)
rabbit.StartSubscribers()
}
func recreateQueue(t *testing.T, subscriber *rabbit.Subscriber) {
done := make(chan bool)
publisher := rabbit.NewPublisher(make(chan bool))
go func() {
for {
if _, err := publisher.GetChannel().QueueDelete(subscriber.Queue, false, false, true); err == nil {
close(done)
return
} else {
log.Printf("Error on removing queue: %+#v", err)
publisher.Close()
}
}
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("Can't delete queue")
t.Fail()
return
}
done = make(chan bool)
go func() {
for {
if err := rabbit.CreateQueue(publisher.GetChannel(), subscriber); err == nil {
close(done)
return
} else {
log.Printf("Error on creating queue: %+#v", err)
publisher.Close()
}
}
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("Can't create queue")
t.Fail()
return
}
}