test: reduce unnecessary sleep durations in tests (#22552)

## Summary

Removes `time.Sleep` calls in two test files by replacing them with
deterministic or event-driven alternatives.

### Changes

**`coderd/provisionerjobs_test.go`** (34.5s → 0.25s)

Replaced `time.Sleep(1500ms)` with a direct SQL `UPDATE` to bump
`created_at` by 2 seconds. The sleep existed purely to ensure different
timestamps for sort-order testing. The fix is deterministic and cannot
flake. Uses `NewDBWithSQLDB` (the test already required real Postgres
via `WithDumpOnFailure`).

**`coderd/database/pubsub/pubsub_test.go`** (2.05s → 1.3s)

Replaced `time.Sleep(1s)` with a `testutil.Eventually` retry loop that
publishes and checks for subscriber receipt. This is the idiomatic
pattern in the codebase. The old sleep waited for pq.Listener to
re-issue LISTEN after reconnect; the new code polls until it actually
works.
This commit is contained in:
Kyle Carberry
2026-03-03 10:19:00 -05:00
committed by GitHub
parent 10a33ebc75
commit 2d7009e50d
2 changed files with 35 additions and 13 deletions
+26 -10
View File
@@ -151,7 +151,10 @@ func TestPGPubsubDriver(t *testing.T) {
gotChan := make(chan struct{}, 1)
defer close(gotChan)
subCancel, err := subber.Subscribe("test", func(_ context.Context, _ []byte) {
gotChan <- struct{}{}
select {
case gotChan <- struct{}{}:
default:
}
})
require.NoError(t, err)
defer subCancel()
@@ -174,14 +177,27 @@ func TestPGPubsubDriver(t *testing.T) {
// wait for the reconnect
_ = testutil.TryReceive(ctx, t, subDriver.Connections)
// we need to sleep because the raw connection notification
// is sent before the pq.Listener can reestablish it's listeners
time.Sleep(1 * time.Second)
// ensure our old subscription still fires
err = pubber.Publish("test", []byte("hello-again"))
require.NoError(t, err)
// wait for the message on the old subscription
_ = testutil.TryReceive(ctx, t, gotChan)
// The raw connection notification is sent before the
// pq.Listener re-issues LISTEN on the new connection.
// Rather than sleeping a fixed duration, retry publishing
// until the subscriber receives a message, which proves
// that the LISTEN has been re-established.
testutil.Eventually(ctx, t, func(_ context.Context) bool {
// Drain any stale signals before publishing.
select {
case <-gotChan:
default:
}
err := pubber.Publish("test", []byte("hello-again"))
if err != nil {
return false
}
select {
case <-gotChan:
return true
case <-time.After(testutil.IntervalFast):
return false
}
}, testutil.IntervalMedium, "subscriber did not receive message after reconnect")
}