WaitOrTimeoutN tries to wait on the given channel for N values to come through, and returns it if they do, but times out after a reasonable amount of time. Useful to guarantee that test cases don't hang forever, even in the event of something wrong.
(tb testutil.TestingTB, waitChan <-chan T, numValues int)
| 294 | // of time. Useful to guarantee that test cases don't hang forever, even in the |
| 295 | // event of something wrong. |
| 296 | func WaitOrTimeoutN[T any](tb testutil.TestingTB, waitChan <-chan T, numValues int) []T { |
| 297 | tb.Helper() |
| 298 | |
| 299 | var ( |
| 300 | timeout = WaitTimeout() |
| 301 | deadline = time.Now().Add(timeout) |
| 302 | values = make([]T, 0, numValues) |
| 303 | ) |
| 304 | |
| 305 | for { |
| 306 | select { |
| 307 | case value := <-waitChan: |
| 308 | values = append(values, value) |
| 309 | |
| 310 | if len(values) >= numValues { |
| 311 | return values |
| 312 | } |
| 313 | |
| 314 | case <-time.After(time.Until(deadline)): |
| 315 | require.FailNowf(tb, "WaitOrTimeout timed out", |
| 316 | "WaitOrTimeout timed out after waiting %s (received %d value(s), wanted %d)", timeout, len(values), numValues) |
| 317 | return nil |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | // WaitTimeout returns a duration broadly appropriate for waiting on an expected |
| 323 | // event in a test, and which is used for `TestSignal.WaitOrTimeout` in the main |
searching dependent graphs…