coder/testutil/ctx.go

35 lines
581 B
Go
Raw Permalink Normal View History

2022-10-10 20:37:06 +00:00
package testutil
import (
"context"
"testing"
"time"
2022-10-10 20:37:06 +00:00
)
func Context(t *testing.T, dur time.Duration) context.Context {
ctx, cancel := context.WithTimeout(context.Background(), dur)
2022-10-10 20:37:06 +00:00
t.Cleanup(cancel)
return ctx
2022-10-10 20:37:06 +00:00
}
func RequireRecvCtx[A any](ctx context.Context, t testing.TB, c <-chan A) (a A) {
t.Helper()
select {
case <-ctx.Done():
t.Fatal("timeout")
return a
case a = <-c:
return a
}
}
func RequireSendCtx[A any](ctx context.Context, t testing.TB, c chan<- A, a A) {
t.Helper()
select {
case <-ctx.Done():
t.Fatal("timeout")
case c <- a:
// OK!
}
}