-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelay_test.go
More file actions
95 lines (79 loc) · 2.18 KB
/
relay_test.go
File metadata and controls
95 lines (79 loc) · 2.18 KB
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
// MIT License
//
// Copyright (c) 2026 sparetimecoders
package outbox_test
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
outbox "github.com/sparetimecoders/go-messaging-outbox"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type mockProcessor struct {
records []outbox.Record
calls atomic.Int32
}
func (m *mockProcessor) Process(_ context.Context, batchSize int, fn func([]outbox.Record) ([]string, error)) (int, error) {
m.calls.Add(1)
if len(m.records) == 0 {
return 0, nil
}
batch := m.records
if len(batch) > batchSize {
batch = batch[:batchSize]
}
publishedIDs, err := fn(batch)
if err != nil {
return 0, err
}
// Remove published records
remaining := make([]outbox.Record, 0)
published := make(map[string]bool)
for _, id := range publishedIDs {
published[id] = true
}
for _, r := range m.records {
if !published[r.ID] {
remaining = append(remaining, r)
}
}
m.records = remaining
return len(publishedIDs), nil
}
type mockRawPublisher struct {
mu sync.Mutex
published []outbox.Record
}
func (m *mockRawPublisher) PublishRaw(_ context.Context, routingKey string, payload []byte, headers map[string]string) error {
m.mu.Lock()
defer m.mu.Unlock()
m.published = append(m.published, outbox.Record{
RoutingKey: routingKey,
Payload: payload,
Headers: headers,
})
return nil
}
func TestRelay_ProcessesBatch(t *testing.T) {
store := &mockProcessor{
records: []outbox.Record{
{ID: "1", RoutingKey: "user.created", Payload: []byte(`{"id":1}`), Headers: map[string]string{"ce-id": "1"}},
{ID: "2", RoutingKey: "user.updated", Payload: []byte(`{"id":2}`), Headers: map[string]string{"ce-id": "2"}},
},
}
publisher := &mockRawPublisher{}
relay := outbox.NewRelay(store, publisher, outbox.RelayConfig{
PollInterval: 50 * time.Millisecond,
BatchSize: 100,
}, nil)
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
_ = relay.Start(ctx)
require.Len(t, publisher.published, 2)
assert.Equal(t, "user.created", publisher.published[0].RoutingKey)
assert.Equal(t, "user.updated", publisher.published[1].RoutingKey)
assert.Empty(t, store.records)
}