-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutbox_test.go
104 lines (88 loc) · 2.33 KB
/
outbox_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
package core
import (
"context"
"testing"
"time"
"github.com/libp2p/go-libp2p/core/peer"
)
type mockExpiry struct {
ID string
C time.Time
}
func (m *mockExpiry) id() string {
return m.ID
}
func (m *mockExpiry) createdAt() time.Time {
return m.C
}
func TestOutboxPutAndPop(t *testing.T) {
// Test values
key := peer.ID("testKey")
val1 := &mockExpiry{"val1", time.Now()}
val2 := &mockExpiry{"val2", time.Now()}
val3 := &mockExpiry{"val3", time.Now()}
// Create outbox with a timeout of 1 second and interval of 1 second
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
outbox := NewOutBox(ctx, Config{Keep: false, Timeout: 2 * time.Second, Interval: 1 * time.Second})
// Put values into outbox
outbox.Put(key, val1)
outbox.Put(key, val2)
// Test if values were put into outbox
msgs := outbox.Pop(key)
if len(msgs) != 2 {
t.Errorf("Expected 2 messages, got %d", len(msgs))
}
for _, msg := range msgs {
switch msg.id() {
case val1.id():
case val2.id():
default:
t.Errorf("Unexpected message: %v", msg)
}
}
// Put another value and test if it's still empty
outbox.Put(key, val3)
failedMsgs := outbox.C()
<-failedMsgs
time.Sleep(3 * time.Second)
msgs = outbox.Pop(key)
if len(msgs) != 1 {
t.Errorf("Expected 1 messages, got %d, %s", len(msgs), msgs)
}
}
func TestOutboxTimeOut(t *testing.T) {
key := peer.ID("testKey")
val1 := &mockExpiry{"val1", time.Now()}
val2 := &mockExpiry{"val2", time.Now()}
val3 := &mockExpiry{"val3", time.Now()}
// Create outbox with a timeout of 1 second and interval of 1 second
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
outbox := NewOutBox(ctx, Config{Keep: true, Timeout: 2 * time.Second, Interval: 1 * time.Second})
// Put values into outbox
outbox.Put(key, val1)
outbox.Put(key, val2)
// Test if values were put into outbox
msgs := outbox.Pop(key)
if len(msgs) != 2 {
t.Errorf("Expected 2 messages, got %d", len(msgs))
}
for _, msg := range msgs {
switch msg.id() {
case val1.id():
case val2.id():
default:
t.Errorf("Unexpected message: %v", msg)
}
}
// Put another value and test if it's still empty
outbox.Put(key, val3)
failedMsgs := outbox.C()
<-failedMsgs
time.Sleep(3 * time.Second)
msgs = outbox.Pop(key)
if len(msgs) != 1 {
t.Errorf("Expected 1 messages, got %d, %s", len(msgs), msgs)
}
}