-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlock_test.go
63 lines (52 loc) · 1.27 KB
/
lock_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
package worker_test
import (
"context"
"errors"
"sync/atomic"
"testing"
"github.com/chapsuk/worker"
. "github.com/smartystreets/goconvey/convey"
)
func TestWithLock(t *testing.T) {
Convey("Given waitnig context job", t, func() {
var (
i int32
start = make(chan struct{})
stop = make(chan struct{})
job = func(ctx context.Context) {
atomic.AddInt32(&i, 1)
start <- struct{}{}
<-ctx.Done()
atomic.AddInt32(&i, 1)
stop <- struct{}{}
}
)
Convey("When run worker with custom locker", func() {
wrk := worker.New(job).WithLock(&customLocker{})
ctx, cancel := context.WithCancel(context.Background())
go wrk.Run(ctx)
So(readFromChannelWithTimeout(start), ShouldBeTrue)
Convey("repeat run should not be execute job", func() {
wrk.Run(ctx)
So(atomic.LoadInt32(&i), ShouldEqual, 1)
})
Convey("cancel context should complete job", func() {
cancel()
So(readFromChannelWithTimeout(stop), ShouldBeTrue)
So(atomic.LoadInt32(&i), ShouldEqual, 2)
})
})
})
}
type customLocker struct {
locked int32
}
func (c *customLocker) Lock() error {
if atomic.CompareAndSwapInt32(&c.locked, 0, 1) {
return nil
}
return errors.New("locked")
}
func (c *customLocker) Unlock() {
atomic.StoreInt32(&c.locked, 0)
}