-
Notifications
You must be signed in to change notification settings - Fork 0
/
entry_test.go
98 lines (80 loc) · 1.96 KB
/
entry_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
package cron
import (
"context"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestEntry_Attributes(t *testing.T) {
entry := newEntry(1, nil, JobFunc(func(context.Context) error {
return nil
}))
assert.Equal(t, entry.ID(), EntryID(1))
assert.NotNil(t, entry.WrappedJob())
assert.NotNil(t, entry.Job())
assert.Nil(t, entry.Schedule())
assert.Zero(t, entry.Next())
assert.Zero(t, entry.Prev())
assert.True(t, entry.Valid())
}
func TestEntry_Context(t *testing.T) {
tests := []struct {
name string
id EntryID
}{
{"", 1},
{"", 2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
// non-existent entry
entry, ok := EntryFromContext(ctx)
assert.False(t, ok)
assert.Nil(t, entry)
// existent entry
entry = newEntry(tt.id, nil, JobFunc(func(ctx context.Context) error {
entry, ok := EntryFromContext(ctx)
assert.True(t, ok)
assert.Equal(t, entry.ID(), tt.id)
return nil
}))
assert.NoError(t, entry.WrappedJob().Run(ctx))
})
}
}
func TestEntry_ContextUseCron(t *testing.T) {
cron := newWithSeconds()
var e1, e2 atomic.Value
var wg sync.WaitGroup
wg.Add(2)
_, err := cron.AddFunc("* * * * *", func(ctx context.Context) error {
defer wg.Done()
entry, ok := EntryFromContext(ctx)
assert.True(t, ok)
assert.True(t, entry.Valid())
e1.Store(entry)
t.Logf("entry id: %d", entry.ID())
return nil
})
assert.NoError(t, err)
_, err = cron.AddFunc("* * * * *", func(ctx context.Context) error {
defer wg.Done()
entry, ok := EntryFromContext(ctx)
assert.True(t, ok)
assert.True(t, entry.Valid())
e2.Store(entry)
t.Logf("entry id: %d", entry.ID())
return nil
})
assert.NoError(t, err)
cron.Start()
defer cron.Stop()
// wait for the job to run
wg.Wait()
// ensure the entries are different
assert.NotNil(t, e1.Load())
assert.NotNil(t, e2.Load())
assert.NotEqual(t, e1.Load().(*Entry).id, e2.Load().(*Entry).id)
}