-
Notifications
You must be signed in to change notification settings - Fork 17
/
machine_test.go
83 lines (78 loc) · 1.81 KB
/
machine_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
package machine_test
import (
"context"
"strings"
"testing"
"time"
"github.com/autom8ter/machine/v4"
)
func Test(t *testing.T) {
var (
m = machine.New()
count = 0
)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
defer m.Close()
m.Go(ctx, func(ctx context.Context) error {
return m.Subscribe(ctx, "testing.*", func(ctx context.Context, msg machine.Message) (bool, error) {
t.Logf("(%s) got message: %v", msg.Channel, msg.Body)
if !strings.Contains(msg.Channel, "testing") {
t.Fatal("expected channel to contain 'testing'")
}
count++
return count < 3, nil
})
})
time.Sleep(1 * time.Second)
for i := 0; i < 3; i++ {
m.Publish(ctx, machine.Message{
Channel: "testing",
Body: "hello world",
})
}
if err := m.Wait(); err != nil {
t.Fatal(err)
}
if count < 3 {
t.Fatal("count < 3", count)
}
}
func TestWithThrottledRoutines(t *testing.T) {
max := 3
m := machine.New(machine.WithThrottledRoutines(max))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
defer m.Close()
for i := 0; i < 100; i++ {
i := i
m.Go(ctx, func(ctx context.Context) error {
if ctx.Err() != nil {
return ctx.Err()
}
if current := m.Current(); current > max {
t.Fatalf("more routines running %v than max threshold: %v", current, max)
}
t.Logf("(%v)", i)
time.Sleep(50 * time.Millisecond)
return nil
})
}
m.Wait()
}
func Benchmark(b *testing.B) {
b.Run("publish", func(b *testing.B) {
m := machine.New()
go func() {
m.Subscribe(context.Background(), "testing.*", func(ctx context.Context, _ machine.Message) (bool, error) {
return true, nil
})
}()
for i := 0; i < b.N; i++ {
m.Publish(context.Background(), machine.Message{
Channel: "testing",
Body: i,
})
}
})
}