chore: add testutil.Eventually and friends (#3389)
This PR adds a `testutil` function aimed to replace `require.Eventually`.
Before:
```go
require.Eventually(t, func() bool { ... }, testutil.WaitShort, testutil.IntervalFast)
```
After:
```go
require.True(t, testutil.EventuallyShort(t, func(ctx context.Context) bool { ... }))
// or the full incantation if you need more control
ctx, cancel := context.WithTimeout(ctx.Background(), testutil.WaitLong)
require.True(t, testutil.Eventually(t, ctx, func(ctx context.Context) bool { ... }, testutil.IntervalSlow))
```
Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
2022-08-05 15:34:44 +00:00
|
|
|
package testutil_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"go.uber.org/goleak"
|
|
|
|
|
2023-08-18 18:55:43 +00:00
|
|
|
"github.com/coder/coder/v2/testutil"
|
chore: add testutil.Eventually and friends (#3389)
This PR adds a `testutil` function aimed to replace `require.Eventually`.
Before:
```go
require.Eventually(t, func() bool { ... }, testutil.WaitShort, testutil.IntervalFast)
```
After:
```go
require.True(t, testutil.EventuallyShort(t, func(ctx context.Context) bool { ... }))
// or the full incantation if you need more control
ctx, cancel := context.WithTimeout(ctx.Background(), testutil.WaitLong)
require.True(t, testutil.Eventually(t, ctx, func(ctx context.Context) bool { ... }, testutil.IntervalSlow))
```
Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
2022-08-05 15:34:44 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestMain(m *testing.M) {
|
|
|
|
goleak.VerifyTestMain(m)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestEventually(t *testing.T) {
|
|
|
|
t.Parallel()
|
|
|
|
t.Run("OK", func(t *testing.T) {
|
|
|
|
t.Parallel()
|
|
|
|
state := 0
|
|
|
|
condition := func(_ context.Context) bool {
|
|
|
|
defer func() {
|
|
|
|
state++
|
|
|
|
}()
|
|
|
|
return state > 2
|
|
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
|
|
|
|
defer cancel()
|
|
|
|
testutil.Eventually(ctx, t, condition, testutil.IntervalFast)
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("Panic", func(t *testing.T) {
|
|
|
|
t.Parallel()
|
|
|
|
|
|
|
|
panicky := func() {
|
|
|
|
mockT := new(testing.T)
|
|
|
|
condition := func(_ context.Context) bool { return true }
|
|
|
|
testutil.Eventually(context.Background(), mockT, condition, testutil.IntervalFast)
|
|
|
|
}
|
|
|
|
assert.Panics(t, panicky)
|
|
|
|
})
|
|
|
|
}
|