converge/pkg/support/throttling/throtller_test.go

51 lines
1.2 KiB
Go

package throttling
import (
"github.com/stretchr/testify/assert"
"testing"
"time"
)
func Test_throttlerImmediateNotificationAfterInitialized(t *testing.T) {
value := 0
throttler := NewThrottler[int](func(v *int) {
value = *v
}, 1.0)
t0 := time.Now()
v := 1
throttler.Notify(t0, &v)
assert.Equal(t, v, value)
value = 0
// subsequent ping will not lead to a notification
throttler.Ping(t0.Add(10 * time.Second))
assert.Equal(t, 0, value)
}
func Test_TwoNotificationsInSHortSucessionSecondOneIsDeliverdWithDelay(t *testing.T) {
value := 0
delayMs := 1000
throttler := NewThrottler[int](func(v *int) {
value = *v
}, float64(delayMs)/1000.0)
t0 := time.Now()
v1 := 1
// v2 will not be delivered, the last value in the time interval will be
v2 := 2
v3 := 3
throttler.Notify(t0, &v1)
assert.Equal(t, v1, value)
throttler.Notify(t0, &v2)
throttler.Notify(t0, &v3)
assert.Equal(t, v1, value)
throttler.Ping(t0.Add(time.Duration(delayMs-1) * time.Millisecond))
assert.Equal(t, v1, value)
throttler.Ping(t0.Add(time.Duration(delayMs) * time.Millisecond))
assert.Equal(t, v3, value)
value = 0
// another ping won' deliver the same value again.
throttler.Ping(t0.Add(time.Duration(delayMs*2) * time.Millisecond))
assert.Equal(t, 0, value)
}