diff --git a/lntest/harness.go b/lntest/harness.go index 03ea96ee4..858a4cd61 100644 --- a/lntest/harness.go +++ b/lntest/harness.go @@ -846,6 +846,32 @@ func WaitPredicate(pred func() bool, timeout time.Duration) error { } } +// WaitInvariant is a helper test function that will wait for a timeout period +// of time, verifying that a statement remains true for the entire duration. +// This function is helpful as timing doesn't always line up well when running +// integration tests with several running lnd nodes. This function gives callers +// a way to assert that some property is maintained over a particular time +// frame. +func WaitInvariant(statement func() bool, timeout time.Duration) error { + const pollInterval = 20 * time.Millisecond + + exitTimer := time.After(timeout) + for { + <-time.After(pollInterval) + + // Fail if the invariant is broken while polling. + if !statement() { + return fmt.Errorf("invariant broken before time out") + } + + select { + case <-exitTimer: + return nil + default: + } + } +} + // DumpLogs reads the current logs generated by the passed node, and returns // the logs as a single string. This function is useful for examining the logs // of a particular node in the case of a test failure.