Skip to content

Commit

Permalink
make backoff retry handler unit test faster
Browse files Browse the repository at this point in the history
  • Loading branch information
freehan committed Jan 24, 2019
1 parent b26979d commit b66eb72
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
3 changes: 2 additions & 1 deletion pkg/neg/syncers/retry_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ func (h *backoffRetryHandler) Retry() error {
}

h.retrying = true
ch := h.clock.After(delay)
go func() {
<-h.clock.After(delay)
<-ch
func() {
h.stateLock.Lock()
defer h.stateLock.Unlock()
Expand Down
29 changes: 23 additions & 6 deletions pkg/neg/syncers/retry_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ limitations under the License.
package syncers

import (
"k8s.io/apimachinery/pkg/util/wait"
"sync"
"testing"
"time"

"k8s.io/apimachinery/pkg/util/clock"
"k8s.io/apimachinery/pkg/util/wait"
)

const (
Expand All @@ -46,7 +48,7 @@ func (h *retryHandlerTestHelper) getCount() int {
}

func verifyRetryHandler(t *testing.T, expectCount int, helper *retryHandlerTestHelper) {
if err := wait.PollImmediate(time.Second, 2*smallTestRetryDelay, func() (bool, error) {
if err := wait.PollImmediate(time.Microsecond, 2*time.Second, func() (bool, error) {
if helper.getCount() == expectCount {
return true, nil
}
Expand All @@ -59,27 +61,42 @@ func verifyRetryHandler(t *testing.T, expectCount int, helper *retryHandlerTestH
func TestBackoffRetryHandler_Retry(t *testing.T) {
helper := &retryHandlerTestHelper{}
handler := NewDelayRetryHandler(helper.incrementCount, NewExponentialBackendOffHandler(testMaxRetries, smallTestRetryDelay, testMaxRetryDelay))
fakeClock := clock.NewFakeClock(time.Now())
handler.clock = fakeClock
delay := smallTestRetryDelay

// Trigger 2 Retries and expect one actual retry happens
if err := handler.Retry(); err != nil {
t.Fatalf("Expect no error, but got %v", err)
}

if err := handler.Retry(); err != ErrHandlerRetrying {
t.Fatalf("Expect error %v, but got %v", ErrHandlerRetrying, err)
}

fakeClock.Step(delay)
verifyRetryHandler(t, 1, helper)

// Trigger exponential backoff retry
if err := handler.Retry(); err != nil {
t.Fatalf("Expect no error, but got %v", err)
}

delay *= 2
fakeClock.Step(delay)
verifyRetryHandler(t, 2, helper)

handler.Reset()
// Trigger exponential backoff retry #2
if err := handler.Retry(); err != nil {
t.Fatalf("Expect no error, but got %v", err)
}

delay *= 2
fakeClock.Step(delay)
verifyRetryHandler(t, 3, helper)

// Trigger reset and retry again
handler.Reset()
if err := handler.Retry(); err != nil {
t.Fatalf("Expect no error, but got %v", err)
}
fakeClock.Step(smallTestRetryDelay)
verifyRetryHandler(t, 4, helper)
}

0 comments on commit b66eb72

Please sign in to comment.