Middle · Testing and performance

A cancellation test passes only when the machine is lucky

A worker test sleeps 10 ms, cancels and sleeps another 10 ms before checking a flag. How do you make the test prove the intended lifecycle?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

EXAMPLE · FRAGMENT UNLESS A COMPLETE PROGRAM IS SHOWN

go
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	started, exited := make(chan struct{}), make(chan struct{})
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() { defer close(exited); close(started); <-ctx.Done() }()
	<-started
	cancel()
	select {
	case <-exited:
		fmt.Println("joined")
	case <-time.After(time.Second):
		panic("worker did not exit")
	}
}
Reveal a strong answer
  1. Use explicit start and completion handshakes so the test knows which state it reached. Waiting an arbitrary wall-clock duration does not establish that the worker started, observed cancellation or completed its cleanup on a loaded machine.

  2. Cancellation signals a request to stop; receiving a completion signal or joining the goroutine proves the owned worker exited. Keep failure timeouts as backstops for a broken implementation, not as the mechanism that orders the happy path.

  3. Test the contract when work is waiting for input, attempting to publish output and shutting down. A closed start signal can establish one happens-before edge; it does not automatically synchronize every shared variable. Native race detection, deterministic fakes or suitable synctest support answer complementary questions.

Common trap

A timing-dependent green run does not prove the intended happens-before edges or absence of a goroutine leak.

Try it

Replace sleeps with started and exited channels, and add a bounded failure guard for a worker that ignores cancellation.

Worked solution

The test waits for started, cancels, then waits for exited. Cleanup completes before exited is closed, so the final assertion follows actual completion rather than a guessed delay. Add a timeout only to fail a stuck test. Extend the scenario with blocked output and verify that both producers and consumers have an owned exit path.

Change the constraint

How would a fake clock or testing/synctest change the proof when retry timers are involved?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-28. Use documentation for your pinned runtime, driver and tool version.