-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbuffered_test.go
64 lines (51 loc) · 1.24 KB
/
buffered_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
package snowflake_test
import (
"context"
"testing"
"time"
"github.com/savaki/snowflake"
"github.com/stretchr/testify/assert"
)
type Remote struct {
factory *snowflake.Factory
}
func (t *Remote) IntN(ctx context.Context, n int) ([]int64, error) {
return t.factory.IdN(n), nil
}
func TestGenerateIdStream(t *testing.T) {
buffer := 4
client := snowflake.NewBufferedClient(&Remote{snowflake.Mock})
uniques := map[int64]int64{}
iterations := buffer * 10
for i := 0; i < iterations; i++ {
id := client.Id()
uniques[id] = id
}
client.Close()
if v := len(uniques); v != iterations {
t.Errorf("expected %v; got %v\n", iterations, v)
}
}
type Mock struct {
count int
}
func (m *Mock) IntN(ctx context.Context, n int) ([]int64, error) {
now := time.Now().UnixNano()
ids := make([]int64, 0, n)
for i := 0; i < n; i++ {
ids = append(ids, now+int64(i))
}
m.count += n
return ids, nil
}
func TestWithBufferSize(t *testing.T) {
client := &Mock{}
buffered := snowflake.NewBufferedClient(client,
snowflake.WithBufferSize(1),
snowflake.WithWorkers(1),
)
id := buffered.Id()
assert.NotZero(t, id)
// expect < 3; 1 in buffer, 1 waiting to be pushed to buffer
assert.True(t, client.count <= 3, "expected < 3; got %v", client.count)
}