diff --git a/README.md b/README.md index 42970da..5e9d472 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ Now you can easily test `myFunc` with a `FakeClock`: ```go func TestMyFunc(t *testing.T) { + ctx := context.Background() c := clockwork.NewFakeClock() // Start our sleepy function @@ -46,8 +47,12 @@ func TestMyFunc(t *testing.T) { wg.Done() }() - // Ensure we wait until myFunc is sleeping - c.BlockUntil(1) + // Ensure we wait until myFunc is waiting on the clock. + // Use a context to avoid blocking forever if something + // goes wrong. + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + c.BlockUntilContext(ctx, 1) assertState() diff --git a/context.go b/context.go index d17a56f..40906e7 100644 --- a/context.go +++ b/context.go @@ -4,7 +4,7 @@ import ( "context" ) -// contextKey is private to this package, so we can ensure uniqueness here. This +// contextKey is private to this package so we can ensure uniqueness here. This // type identifies context values provided by this package. type contextKey string @@ -12,6 +12,11 @@ type contextKey string var keyClock = contextKey("clock") // clockwork.Clock // AddToContext creates a derived context that references the specified clock. +// +// Be aware this doesn't change the behavior of standard library functions, such +// as [context.WithTimeout] or [context.WithDeadline]. For this reason, users +// should prefer passing explicit [clockwork.Clock] variables rather can passing +// the clock via the context. func AddToContext(ctx context.Context, clock Clock) context.Context { return context.WithValue(ctx, keyClock, clock) } diff --git a/example_test.go b/example_test.go index 2631c5a..efd4c3d 100644 --- a/example_test.go +++ b/example_test.go @@ -1,6 +1,7 @@ package clockwork import ( + "context" "sync" "testing" "time" @@ -21,6 +22,7 @@ func assertState(t *testing.T, i, j int) { // TestMyFunc tests myFunc's behaviour with a FakeClock. func TestMyFunc(t *testing.T) { + ctx := context.Background() var i int c := NewFakeClock() @@ -31,8 +33,12 @@ func TestMyFunc(t *testing.T) { wg.Done() }() - // Wait until myFunc is actually sleeping on the clock. - c.BlockUntil(1) + // Ensure we wait until myFunc is waiting on the clock. + // Use a context to avoid blocking forever if something + // goes wrong. + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + c.BlockUntilContext(ctx, 1) // Assert the initial state. assertState(t, i, 0)