Skip to content

fix: Fix cleanup in test helpers, prefer defer in tests #3113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: Run ctx cancel first in t.Cleanup
  • Loading branch information
mafredri committed Jul 25, 2022
commit f245f64b849550feed4acbdaf51a7e0f9e22efdb
2 changes: 1 addition & 1 deletion coderd/coderd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
t.Cleanup(func() { close(tickerCh) })

ctx, cancelFunc := context.WithCancel(context.Background())
t.Cleanup(cancelFunc)
defer t.Cleanup(cancelFunc) // Defer to ensure cancelFunc is executed first.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does defer cancelFunc() not work here? I would expect defer to run before cleanups.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See comment on the other instance: https://github.com/coder/coder/pull/3113/files#r928922910.


lifecycleExecutor := executor.New(
ctx,
Expand Down
2 changes: 1 addition & 1 deletion coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func newWithCloser(t *testing.T, options *Options) (*codersdk.Client, io.Closer)
}

ctx, cancelFunc := context.WithCancel(context.Background())
t.Cleanup(cancelFunc)
defer t.Cleanup(cancelFunc) // Defer to ensure cancelFunc is executed first.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is a helper function, defer cancelFunc() would run before the calling test gets a chance to do anything with it. And a t.Cleanup without defer would cancel the context too late, it would not trigger teardown. So I realize this is a bit of a sneaky way to do it, but this way t.Cleanup(cancelFunc) will be left on top of the cleanup stack when this function exits, triggering the teardown we want (and same order as before the refactor).


lifecycleExecutor := executor.New(
ctx,
Expand Down