github.com/cilium/cilium@v1.16.2/pkg/testutils/condition.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package testutils 5 6 import ( 7 "fmt" 8 "time" 9 ) 10 11 // ConditionFunc is the function implementing the condition, it must return 12 // true if the condition has been met 13 type ConditionFunc func() bool 14 15 // WaitUntil evaluates the condition every 10 milliseconds and waits for the 16 // condition to be met. The function will time out and return an error after 17 // timeout 18 func WaitUntil(condition ConditionFunc, timeout time.Duration) error { 19 return WaitUntilWithSleep(condition, timeout, 10*time.Millisecond) 20 } 21 22 // WaitUntilWithSleep does the same as WaitUntil except that the sleep time 23 // between the condition checks is given. 24 func WaitUntilWithSleep(condition ConditionFunc, timeout, sleep time.Duration) error { 25 now := time.Now() 26 for { 27 if time.Since(now) > timeout { 28 return fmt.Errorf("timeout reached while waiting for condition") 29 } 30 31 if condition() { 32 return nil 33 } 34 35 time.Sleep(sleep) 36 } 37 }