|
| 1 | +package periodic_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "sync/atomic" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/cego/go-lib/v2/periodic" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | +) |
| 12 | + |
| 13 | +func TestRunExecutesImmediately(t *testing.T) { |
| 14 | + ctx, cancel := context.WithCancel(context.Background()) |
| 15 | + defer cancel() |
| 16 | + |
| 17 | + var count atomic.Int32 |
| 18 | + periodic.Run(ctx, time.Hour, 0, func() { |
| 19 | + count.Add(1) |
| 20 | + }) |
| 21 | + |
| 22 | + time.Sleep(50 * time.Millisecond) |
| 23 | + assert.Equal(t, int32(1), count.Load()) |
| 24 | +} |
| 25 | + |
| 26 | +func TestRunExecutesPeriodically(t *testing.T) { |
| 27 | + ctx, cancel := context.WithCancel(context.Background()) |
| 28 | + defer cancel() |
| 29 | + |
| 30 | + var count atomic.Int32 |
| 31 | + periodic.Run(ctx, 50*time.Millisecond, 0, func() { |
| 32 | + count.Add(1) |
| 33 | + }) |
| 34 | + |
| 35 | + time.Sleep(200 * time.Millisecond) |
| 36 | + assert.GreaterOrEqual(t, count.Load(), int32(3)) |
| 37 | +} |
| 38 | + |
| 39 | +func TestRunStopsOnContextCancel(t *testing.T) { |
| 40 | + ctx, cancel := context.WithCancel(context.Background()) |
| 41 | + |
| 42 | + var count atomic.Int32 |
| 43 | + periodic.Run(ctx, 50*time.Millisecond, 0, func() { |
| 44 | + count.Add(1) |
| 45 | + }) |
| 46 | + |
| 47 | + time.Sleep(100 * time.Millisecond) |
| 48 | + cancel() |
| 49 | + countAtCancel := count.Load() |
| 50 | + |
| 51 | + time.Sleep(200 * time.Millisecond) |
| 52 | + assert.Equal(t, countAtCancel, count.Load()) |
| 53 | +} |
| 54 | + |
| 55 | +func TestRunAppliesJitter(t *testing.T) { |
| 56 | + ctx, cancel := context.WithCancel(context.Background()) |
| 57 | + defer cancel() |
| 58 | + |
| 59 | + var count atomic.Int32 |
| 60 | + periodic.Run(ctx, time.Hour, 200*time.Millisecond, func() { |
| 61 | + count.Add(1) |
| 62 | + }) |
| 63 | + |
| 64 | + time.Sleep(50 * time.Millisecond) |
| 65 | + assert.Equal(t, int32(0), count.Load()) |
| 66 | + |
| 67 | + time.Sleep(200 * time.Millisecond) |
| 68 | + assert.Equal(t, int32(1), count.Load()) |
| 69 | +} |
| 70 | + |
| 71 | +func TestRunDoesNotBlock(t *testing.T) { |
| 72 | + ctx, cancel := context.WithCancel(context.Background()) |
| 73 | + defer cancel() |
| 74 | + |
| 75 | + returned := make(chan struct{}) |
| 76 | + go func() { |
| 77 | + periodic.Run(ctx, time.Hour, time.Hour, func() { /* no-op: testing that Run returns immediately */ }) |
| 78 | + close(returned) |
| 79 | + }() |
| 80 | + |
| 81 | + select { |
| 82 | + case <-returned: |
| 83 | + case <-time.After(50 * time.Millisecond): |
| 84 | + t.Fatal("Run blocked the caller") |
| 85 | + } |
| 86 | +} |
0 commit comments