github.com/yandex/pandora@v0.5.32/core/coreutil/waiter_test.go (about)

     1  package coreutil
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/require"
     9  	"github.com/yandex/pandora/core/schedule"
    10  )
    11  
    12  func TestWaiter_Unstarted(t *testing.T) {
    13  	sched := schedule.NewOnce(1)
    14  	ctx := context.Background()
    15  	w := NewWaiter(sched)
    16  	var i int
    17  	for ; w.Wait(ctx); i++ {
    18  	}
    19  	require.Equal(t, 1, i)
    20  }
    21  
    22  func TestWaiter_WaitAsExpected(t *testing.T) {
    23  	const (
    24  		duration = 100 * time.Millisecond
    25  		ops      = 100
    26  		times    = ops * duration / time.Second
    27  	)
    28  	sched := schedule.NewConst(ops, duration)
    29  	ctx := context.Background()
    30  	w := NewWaiter(sched)
    31  	start := time.Now()
    32  	sched.Start(start)
    33  	var i int
    34  	for ; w.Wait(ctx); i++ {
    35  	}
    36  	finish := time.Now()
    37  
    38  	require.Equal(t, int(times), i)
    39  	dur := finish.Sub(start)
    40  	require.True(t, dur >= duration*(times-1)/times)
    41  	require.True(t, dur < 3*duration) // Smaller interval will be more flaky.
    42  }
    43  func TestWaiter_ContextCanceledBeforeWait(t *testing.T) {
    44  	sched := schedule.NewOnce(1)
    45  	ctx, cancel := context.WithCancel(context.Background())
    46  	cancel()
    47  	w := NewWaiter(sched)
    48  	require.False(t, w.Wait(ctx))
    49  }
    50  
    51  func TestWaiter_ContextCanceledDuringWait(t *testing.T) {
    52  	sched := schedule.NewConstConf(schedule.ConstConfig{Ops: 0.1, Duration: 100 * time.Second})
    53  	timeout := 20 * time.Millisecond
    54  	start := time.Now()
    55  	ctx, cancel := context.WithTimeout(context.Background(), timeout)
    56  	defer cancel()
    57  	w := NewWaiter(sched)
    58  
    59  	require.True(t, w.Wait(ctx)) // 0
    60  	require.False(t, w.Wait(ctx))
    61  
    62  	since := time.Since(start)
    63  	require.True(t, since > timeout)
    64  	require.True(t, since < 10*timeout)
    65  }