Skip to content

Commit 34c6ad6

Browse files
authored
fix(clitest): use separate channel when waiting for exit (coder#7231)
1 parent ad00703 commit 34c6ad6

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

cli/clitest/clitest.go

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ func extractTar(t *testing.T, data []byte, directory string) {
127127
}
128128
}
129129

130-
// Start runs the command in a goroutine and cleans it up when
131-
// the test completed.
130+
// Start runs the command in a goroutine and cleans it up when the test
131+
// completed.
132132
func Start(t *testing.T, inv *clibase.Invocation) {
133133
t.Helper()
134134

@@ -170,7 +170,7 @@ func (w *ErrorWaiter) Wait() error {
170170
var ok bool
171171
w.cachedError, ok = <-w.c
172172
if !ok {
173-
panic("unexpoected channel close")
173+
panic("unexpected channel close")
174174
}
175175
})
176176
return w.cachedError
@@ -196,18 +196,18 @@ func (w *ErrorWaiter) RequireAs(want interface{}) {
196196
require.ErrorAs(w.t, w.Wait(), want)
197197
}
198198

199-
// StartWithWaiter runs the command in a goroutine but returns the error
200-
// instead of asserting it. This is useful for testing error cases.
199+
// StartWithWaiter runs the command in a goroutine but returns the error instead
200+
// of asserting it. This is useful for testing error cases.
201201
func StartWithWaiter(t *testing.T, inv *clibase.Invocation) *ErrorWaiter {
202202
t.Helper()
203203

204-
errCh := make(chan error, 1)
205-
206-
var cleaningUp atomic.Bool
207-
208204
var (
209205
ctx = inv.Context()
210206
cancel func()
207+
208+
cleaningUp atomic.Bool
209+
errCh = make(chan error, 1)
210+
doneCh = make(chan struct{})
211211
)
212212
if _, ok := ctx.Deadline(); !ok {
213213
ctx, cancel = context.WithDeadline(ctx, time.Now().Add(testutil.WaitMedium))
@@ -218,12 +218,13 @@ func StartWithWaiter(t *testing.T, inv *clibase.Invocation) *ErrorWaiter {
218218
inv = inv.WithContext(ctx)
219219

220220
go func() {
221+
defer close(doneCh)
221222
defer close(errCh)
222223
err := inv.Run()
223224
if cleaningUp.Load() && errors.Is(err, context.DeadlineExceeded) {
224-
// If we're cleaning up, this error is likely related to the
225-
// CLI teardown process. E.g., the server could be slow to shut
226-
// down Postgres.
225+
// If we're cleaning up, this error is likely related to the CLI
226+
// teardown process. E.g., the server could be slow to shut down
227+
// Postgres.
227228
t.Logf("command %q timed out during test cleanup", inv.Command.FullName())
228229
}
229230
// Whether or not this fails the test is left to the caller.
@@ -235,7 +236,7 @@ func StartWithWaiter(t *testing.T, inv *clibase.Invocation) *ErrorWaiter {
235236
t.Cleanup(func() {
236237
cancel()
237238
cleaningUp.Store(true)
238-
<-errCh
239+
<-doneCh
239240
})
240241
return &ErrorWaiter{c: errCh, t: t}
241242
}

0 commit comments

Comments
 (0)