github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/testutils/poll.go (about)

     1  package testutils
     2  
     3  import (
     4  	"time"
     5  
     6  	"code.cloudfoundry.org/clock/fakeclock"
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  // PollFuncWithTimeout is used to periodically execute a check function, it
    11  // returns error after timeout.
    12  func PollFuncWithTimeout(clockSource *fakeclock.FakeClock, f func() error, timeout time.Duration) error {
    13  	if f() == nil {
    14  		return nil
    15  	}
    16  	timer := time.NewTimer(timeout)
    17  	defer timer.Stop()
    18  	for i := 0; ; i++ {
    19  		if i%5 == 0 && clockSource != nil {
    20  			clockSource.Increment(time.Second)
    21  		}
    22  		err := f()
    23  		if err == nil {
    24  			return nil
    25  		}
    26  		select {
    27  		case <-timer.C:
    28  			return errors.Wrap(err, "polling failed")
    29  		case <-time.After(50 * time.Millisecond):
    30  		}
    31  	}
    32  }
    33  
    34  // PollFunc is like PollFuncWithTimeout with timeout=10s.
    35  func PollFunc(clockSource *fakeclock.FakeClock, f func() error) error {
    36  	return PollFuncWithTimeout(clockSource, f, 10*time.Second)
    37  }