Skip to content

Commit

Permalink
add Cancel as an example of an injector
Browse files Browse the repository at this point in the history
  • Loading branch information
muir committed Jul 26, 2024
1 parent a597d23 commit 72bc9c3
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
21 changes: 21 additions & 0 deletions injectors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ntest

import (
"context"
)

// This file contains example injectors that may be useful

// Cancel is the injected type for the function type that will cancel
// a Context that has been augmented with AutoCancel.
type Cancel func()

// AutoCancel adjusts context.Context so that it will be cancelled
// when the test finishes. It can be cancelled early by calling
// the returned Cancel function.
func AutoCancel(ctx context.Context, t T) (context.Context, Cancel) {
ctx, cancel := context.WithCancel(ctx)
onlyOnce := onceFunc(cancel)
t.Cleanup(onlyOnce)
return ctx, onlyOnce
}
29 changes: 29 additions & 0 deletions injectors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package ntest_test

import (
"context"
"testing"

"github.com/memsql/ntest"
)

func TestCancel(t *testing.T) {
t.Parallel()
ntest.RunTest(t, context.Background, ntest.AutoCancel, func(
ctx context.Context,
cancel ntest.Cancel,
) {
select {
case <-ctx.Done():
t.Fatal("context is cancelled before cancel()")
default:
}
cancel()
select {
case <-ctx.Done():
t.Log("context is cancelled")
default:
t.Fatal("context is not cancelled after cancel()")
}
})
}
7 changes: 7 additions & 0 deletions once.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//go:build go1.21

package ntest

import "sync"

var onceFunc = sync.OnceFunc
12 changes: 12 additions & 0 deletions once_old.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//go:build !go1.21

package ntest

import "sync"

func onceFunc(f func()) func() {
var once sync.Once
return func() {
once.Do(f)
}
}

0 comments on commit 72bc9c3

Please sign in to comment.