Tests: Add require.Eventually and fix a few test flakes (#16217)

**What type of PR is this?**

Other

**What does this PR do? Why is it needed?**

This is a better way to wait for a test condition to hit, rather than
time.Sleep.

**Which issues(s) does this PR fix?**


**Other notes for review**

**Acknowledgements**

- [x] I have read
[CONTRIBUTING.md](https://github.com/prysmaticlabs/prysm/blob/develop/CONTRIBUTING.md).
- [x] I have included a uniquely named [changelog fragment
file](https://github.com/prysmaticlabs/prysm/blob/develop/CONTRIBUTING.md#maintaining-changelogmd).
- [x] I have added a description with sufficient context for reviewers
to understand this PR.
- [x] I have tested that my changes work as expected and I added a
testing plan to the PR description (if applicable).
This commit is contained in:
Preston Van Loon
2026-01-06 12:20:27 -06:00
committed by GitHub
parent ffad861e2c
commit 27c009e7ff
12 changed files with 167 additions and 104 deletions

View File

@@ -8,6 +8,7 @@ import (
"runtime"
"sort"
"strings"
"time"
"github.com/OffchainLabs/prysm/v7/encoding/ssz/equality"
"github.com/d4l3k/messagediff"
@@ -138,12 +139,21 @@ func StringContains(loggerFn assertionLoggerFn, expected, actual string, flag bo
// NoError asserts that error is nil.
func NoError(loggerFn assertionLoggerFn, err error, msg ...any) {
// reflect.ValueOf is needed for nil instances of custom types implementing Error
if err != nil && !reflect.ValueOf(err).IsNil() {
errMsg := parseMsg("Unexpected error", msg...)
_, file, line, _ := runtime.Caller(2)
loggerFn("%s:%d %s: %v", filepath.Base(file), line, errMsg, err)
if err == nil {
return
}
// reflect.ValueOf is needed for nil instances of custom types implementing Error.
// Only check IsNil for types that support it to avoid panics on struct types.
v := reflect.ValueOf(err)
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
if v.IsNil() {
return
}
}
errMsg := parseMsg("Unexpected error", msg...)
_, file, line, _ := runtime.Caller(2)
loggerFn("%s:%d %s: %v", filepath.Base(file), line, errMsg, err)
}
// ErrorIs uses Errors.Is to recursively unwrap err looking for target in the chain.
@@ -341,3 +351,18 @@ func (tb *TBMock) Errorf(format string, args ...any) {
func (tb *TBMock) Fatalf(format string, args ...any) {
tb.FatalfMsg = fmt.Sprintf(format, args...)
}
// Eventually asserts that given condition will be met within waitFor time,
// periodically checking target function each tick.
func Eventually(loggerFn assertionLoggerFn, condition func() bool, waitFor, tick time.Duration, msg ...any) {
deadline := time.Now().Add(waitFor)
for time.Now().Before(deadline) {
if condition() {
return
}
time.Sleep(tick)
}
errMsg := parseMsg("Condition never satisfied", msg...)
_, file, line, _ := runtime.Caller(2)
loggerFn("%s:%d %s (waited %v)", filepath.Base(file), line, errMsg, waitFor)
}