-
Notifications
You must be signed in to change notification settings - Fork 0
/
with_idempotent_test.go
92 lines (87 loc) · 2.61 KB
/
with_idempotent_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
package opinionatedsagas
import (
"context"
"database/sql"
"fmt"
"math/rand"
"sync"
"sync/atomic"
"testing"
events "github.com/markusylisiurunen/go-opinionatedevents"
"github.com/stretchr/testify/assert"
_ "github.com/lib/pq"
)
func TestWithIdempotentSequentially(t *testing.T) {
r := rand.New(rand.NewSource(5348997842))
// init database connection
connectionString := "postgres://postgres:password@localhost:6632/dev?sslmode=disable"
schema := fmt.Sprintf("opinionatedsagas_%d", r.Int())
db, err := sql.Open("postgres", connectionString)
assert.NoError(t, err)
// ensure migrations
err = migrate(db, schema)
assert.NoError(t, err)
// execute the same test for `n` times
for i := 0; i < 3; i += 1 {
// init a handler
var handlerCount atomic.Int64
var handler events.OnMessageHandler = func(ctx context.Context, delivery events.Delivery) error {
handlerCount.Add(1)
return nil
}
// execute the (wrapped) handler `n` times
var successCount atomic.Int64
var failureCount atomic.Int64
wrapped := withIdempotent(db, schema)(handler)
delivery := newTestDelivery(1, "tasks", 0)
for i := 0; i < 32; i += 1 {
result := wrapped(context.Background(), delivery)
if result != nil {
failureCount.Add(1)
} else {
successCount.Add(1)
}
}
// the handler should have been called only once
assert.Equal(t, int64(1), handlerCount.Load())
// every call should have returned a success
assert.Equal(t, int64(32), successCount.Load())
assert.Equal(t, int64(0), failureCount.Load())
}
db.Close()
}
func TestWithIdempotentConcurrently(t *testing.T) {
r := rand.New(rand.NewSource(1234893457))
// init database connection
connectionString := "postgres://postgres:password@localhost:6632/dev?sslmode=disable"
schema := fmt.Sprintf("opinionatedsagas_%d", r.Int())
db, err := sql.Open("postgres", connectionString)
assert.NoError(t, err)
// ensure migrations
err = migrate(db, schema)
assert.NoError(t, err)
// execute the same test for `n` times
for i := 0; i < 3; i += 1 {
// init a handler
var handlerCount atomic.Int64
var handler events.OnMessageHandler = func(ctx context.Context, delivery events.Delivery) error {
handlerCount.Add(1)
return nil
}
// execute the (wrapped) handler `n` times
wrapped := withIdempotent(db, schema)(handler)
delivery := newTestDelivery(1, "tasks", 0)
var wg sync.WaitGroup
for i := 0; i < 64; i += 1 {
wg.Add(1)
go func() {
defer wg.Done()
wrapped(context.Background(), delivery) //nolint
}()
}
wg.Wait()
// the handler should have been called only once
assert.Equal(t, int64(1), handlerCount.Load())
}
db.Close()
}