Skip to content

Commit c2ad724

Browse files
committed
ktesting: add Parallel
It's useful for writing parallel unit tests.
1 parent 87fcae2 commit c2ad724

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

test/utils/ktesting/tcontext.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,15 @@ type TContext interface {
7575
context.Context
7676
TB
7777

78+
// Parallel signals that this test is to be run in parallel with (and
79+
// only with) other parallel tests. In other words, it needs to be
80+
// called in each test which is meant to run in parallel.
81+
//
82+
// Only supported in Go unit tests. When such a test is run multiple
83+
// times due to use of -test.count or -test.cpu, multiple instances of
84+
// a single test never run in parallel with each other.
85+
Parallel()
86+
7887
// Cancel can be invoked to cancel the context before the test is completed.
7988
// Tests which use the context to control goroutines and then wait for
8089
// termination of those goroutines must call Cancel to avoid a deadlock.
@@ -381,6 +390,12 @@ type testingTB struct {
381390
TB
382391
}
383392

393+
func (tCtx tContext) Parallel() {
394+
if tb, ok := tCtx.TB().(interface{ Parallel() }); ok {
395+
tb.Parallel()
396+
}
397+
}
398+
384399
func (tCtx tContext) Cancel(cause string) {
385400
if tCtx.cancel != nil {
386401
tCtx.cancel(cause)

test/utils/ktesting/tcontext_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,23 @@ func TestCancelCtx(t *testing.T) {
8686
tCtx.Cancel("test is complete")
8787
}
8888

89+
func TestParallel(t *testing.T) {
90+
var wg sync.WaitGroup
91+
wg.Add(3)
92+
93+
tCtx := ktesting.Init(t)
94+
95+
// Each sub-test runs in parallel to the others and waits for the other two.
96+
test := func(tCtx ktesting.TContext) {
97+
tCtx.Parallel()
98+
wg.Done()
99+
wg.Wait()
100+
}
101+
tCtx.Run("one", test)
102+
tCtx.Run("two", test)
103+
tCtx.Run("three", test)
104+
}
105+
89106
func TestWithTB(t *testing.T) {
90107
tCtx := ktesting.Init(t)
91108

0 commit comments

Comments
 (0)