Skip to content

Commit

Permalink
Update documentaiton on interactions with context.
Browse files Browse the repository at this point in the history
  • Loading branch information
DPJacques committed Dec 24, 2023
1 parent 95528df commit 72da535
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()

Expand Down
7 changes: 6 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ 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

// keyClock provides a clock for injecting during tests. If absent, a real clock should be used.
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)
}
Expand Down
10 changes: 8 additions & 2 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package clockwork

import (
"context"
"sync"
"testing"
"time"
Expand All @@ -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()

Expand All @@ -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)
Expand Down

0 comments on commit 72da535

Please sign in to comment.