Skip to content

Commit

Permalink
Mock time functions to make tests more reliable
Browse files Browse the repository at this point in the history
  • Loading branch information
L3n41c committed Jan 17, 2023
1 parent 4bd4cc3 commit 4b5818d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
16 changes: 11 additions & 5 deletions pkg/util/aggregatingqueue/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,36 @@
package queue

import (
"time"
"github.com/benbjohnson/clock"
)

type queue[T any] struct {
clock clock.Clock
maxNbItem int
maxRetentionTime time.Duration
maxRetentionTime clock.Duration
flushCB func([]T)
enqueueCh chan T
data []T
timer *time.Timer
timer *clock.Timer
}

// NewQueue returns a chan to enqueue elements
// The flushCB function will be called with a slice of elements as soon as
// * either maxNbItem elements have been enqueued since the last flush
// * or maxRetentionTime has elapsed since the first element has been enqueued after the last flush.
func NewQueue[T any](maxNbItem int, maxRetentionTime time.Duration, flushCB func([]T)) chan T {
func NewQueue[T any](maxNbItem int, maxRetentionTime clock.Duration, flushCB func([]T)) chan T {
return newQueue(maxNbItem, maxRetentionTime, flushCB, clock.New())
}

func newQueue[T any](maxNbItem int, maxRetentionTime clock.Duration, flushCB func([]T), cl clock.Clock) chan T {
q := queue[T]{
clock: cl,
maxNbItem: maxNbItem,
maxRetentionTime: maxRetentionTime,
flushCB: flushCB,
enqueueCh: make(chan T),
data: make([]T, 0, maxNbItem),
timer: time.NewTimer(maxRetentionTime),
timer: cl.Timer(maxRetentionTime),
}

if !q.timer.Stop() {
Expand Down
6 changes: 4 additions & 2 deletions pkg/util/aggregatingqueue/queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"testing"
"time"

"github.com/benbjohnson/clock"
"github.com/stretchr/testify/assert"
)

Expand All @@ -34,7 +35,8 @@ func newMockFlush[T any]() (callback func([]T), getAccumulator func() [][]T) {

func TestQueue(t *testing.T) {
callback, accumulator := newMockFlush[int]()
queue := NewQueue(3, 50*time.Millisecond, callback)
cl := clock.NewMock()
queue := newQueue(3, 1*time.Minute, callback, cl)

for i := 0; i <= 10; i++ {
queue <- i
Expand All @@ -50,7 +52,7 @@ func TestQueue(t *testing.T) {
},
)

time.Sleep(100 * time.Millisecond)
cl.Add(2 * time.Minute)

assert.Equal(
t,
Expand Down

0 comments on commit 4b5818d

Please sign in to comment.