mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-08-04 01:40:07 +00:00
ktesting: add Parallel
It's useful for writing parallel unit tests.
This commit is contained in:
parent
87fcae2bc7
commit
c2ad724e9a
@ -75,6 +75,15 @@ type TContext interface {
|
|||||||
context.Context
|
context.Context
|
||||||
TB
|
TB
|
||||||
|
|
||||||
|
// Parallel signals that this test is to be run in parallel with (and
|
||||||
|
// only with) other parallel tests. In other words, it needs to be
|
||||||
|
// called in each test which is meant to run in parallel.
|
||||||
|
//
|
||||||
|
// Only supported in Go unit tests. When such a test is run multiple
|
||||||
|
// times due to use of -test.count or -test.cpu, multiple instances of
|
||||||
|
// a single test never run in parallel with each other.
|
||||||
|
Parallel()
|
||||||
|
|
||||||
// Cancel can be invoked to cancel the context before the test is completed.
|
// Cancel can be invoked to cancel the context before the test is completed.
|
||||||
// Tests which use the context to control goroutines and then wait for
|
// Tests which use the context to control goroutines and then wait for
|
||||||
// termination of those goroutines must call Cancel to avoid a deadlock.
|
// termination of those goroutines must call Cancel to avoid a deadlock.
|
||||||
@ -381,6 +390,12 @@ type testingTB struct {
|
|||||||
TB
|
TB
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (tCtx tContext) Parallel() {
|
||||||
|
if tb, ok := tCtx.TB().(interface{ Parallel() }); ok {
|
||||||
|
tb.Parallel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (tCtx tContext) Cancel(cause string) {
|
func (tCtx tContext) Cancel(cause string) {
|
||||||
if tCtx.cancel != nil {
|
if tCtx.cancel != nil {
|
||||||
tCtx.cancel(cause)
|
tCtx.cancel(cause)
|
||||||
|
@ -86,6 +86,23 @@ func TestCancelCtx(t *testing.T) {
|
|||||||
tCtx.Cancel("test is complete")
|
tCtx.Cancel("test is complete")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParallel(t *testing.T) {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(3)
|
||||||
|
|
||||||
|
tCtx := ktesting.Init(t)
|
||||||
|
|
||||||
|
// Each sub-test runs in parallel to the others and waits for the other two.
|
||||||
|
test := func(tCtx ktesting.TContext) {
|
||||||
|
tCtx.Parallel()
|
||||||
|
wg.Done()
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
tCtx.Run("one", test)
|
||||||
|
tCtx.Run("two", test)
|
||||||
|
tCtx.Run("three", test)
|
||||||
|
}
|
||||||
|
|
||||||
func TestWithTB(t *testing.T) {
|
func TestWithTB(t *testing.T) {
|
||||||
tCtx := ktesting.Init(t)
|
tCtx := ktesting.Init(t)
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user