itest: timeout while waiting for predicate result

This commit sends the returned value of pred() inside a goroutine such
that when a predicate function never returns during the first run, the
wait package can timeout properly.
This commit is contained in:
yyforyongyu committed 2022-10-14 15:45:24 +08:00
1 parent 2ab842c645
commit 9d79e76876
1 file changed
+14 -5
+14 -5
View File
@@ -15,17 +15,26 @@ const PollInterval = 200 * time.Millisecond
// some property is upheld within a particular time frame.
func Predicate(pred func() bool, timeout time.Duration) error {
exitTimer := time.After(timeout)
result := make(chan bool, 1)
for {
<-time.After(PollInterval)
go func() {
result <- pred()
}()
// Each time we call the pred(), we expect a result to be
// returned otherwise it will timeout.
select {
case <-exitTimer:
return fmt.Errorf("predicate not satisfied after time out")
default:
}
return fmt.Errorf("predicate not satisfied after " +
"time out")
if pred() {
return nil
case succeed := <-result:
if succeed {
return nil
}
}
}
}