package throttling import ( "time" ) func (suite *ThrottlerTestSuite) Test_throttlerImmediateNotificationAfterInitialized() { value := 0 throttler := NewThrottler[int](func(v int) { value = v }, 1.0) t0 := time.Now() v := 1 currentTime.now = t0 throttler.Notify(v) suite.Equal(v, value) value = 0 // subsequent ping will not lead to a notification currentTime.now = t0.Add(10 * time.Second) throttler.Ping() suite.Equal(0, value) } func (suite *ThrottlerTestSuite) Test_TwoNotificationsInSHortSucessionSecondOneIsDeliverdWithDelay() { value := 0 delayMs := 1000 throttler := NewThrottler[int](func(v int) { value = v }, time.Duration(delayMs)*time.Millisecond) t0 := time.Now() v1 := 1 // v2 will not be delivered, the last value in the time interval will be v2 := 2 v3 := 3 currentTime.now = t0 throttler.Notify(v1) suite.Equal(v1, value) throttler.Notify(v2) throttler.Notify(v3) suite.Equal(v1, value) currentTime.now = t0.Add(time.Duration(delayMs-1) * time.Millisecond) throttler.Ping() suite.Equal(v1, value) currentTime.now = t0.Add(time.Duration(delayMs) * time.Millisecond) throttler.Ping() suite.Equal(v3, value) // another ping won't deliver the same value again. value = 0 currentTime.now = t0.Add(time.Duration(delayMs) * time.Millisecond) throttler.Ping() suite.Equal(0, value) } func (suite *ThrottlerTestSuite) Test_DuplicateEventsIgnored() { value := 0 mindelay := 1 * time.Second throttler := NewThrottler[int](func(v int) { value = v }, mindelay) t0 := time.Now() v := 1 currentTime.now = t0 throttler.Notify(v) suite.Equal(v, value) // sending the same value again will not lead to a notification value = 0 currentTime.now = currentTime.now.Add(2 * mindelay) throttler.Notify(v) suite.Equal(0, value) // sending a different value later will lead to a new notification currentTime.now = currentTime.now.Add(2 * mindelay) v++ throttler.Notify(v) suite.Equal(v, value) }