Test cancellation and worker shutdown
Test cancellation and worker shutdown
Calling cancel requests cancellation; it does not join a worker. Test a readiness signal, send cancellation, then observe completion and the relevant result. A timeout is a failure guard, not a way to schedule the worker.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "context" "testing" "time")
func TestLesson(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ready := make(chan struct{}) done := make(chan error, 1) go func() { close(ready); <-ctx.Done(); done <- ctx.Err() }() <-ready cancel() select { case err := <-done: if err != context.Canceled { t.Fatal(err) } case <-time.After(2 * time.Second): t.Fatal("worker did not stop") }}The result is buffered so that an early test failure does not strand a worker sending its result. A two-second guard is deliberately generous for this tiny fixture; a slow environment can still produce a false failure. Keep the actual assertion independent of elapsed wall time.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonAssert cleanup before completion
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "context" "testing")
func TestLesson(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan struct{}) cleaned := false go func() { defer close(done); defer func() { cleaned = true }(); <-ctx.Done() }() cancel() <-done if !cleaned { t.Fatal("cleanup missing") }}Deferred functions run in reverse registration order. Cleanup writes cleaned before closing done, and the receive from the closed channel orders the test read. Invert the defer order and the assertion is no longer synchronized. Do not call Fatal inside a worker; send the result to the test goroutine instead.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Cancel two workers sharing a context; join both and assert both observed cancellation using a buffered channel. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency testing 02: Test cancellation and worker shutdown
Check the lesson objective before moving on.
What does cancel guarantee by itself?
Why close done after cleanup?