environment: Error when t.Parallel was called before Protect

Protecting the environment relies on the shared state (containers,
images, etc) which might already be mutated by other tests if the test
opted in into the Parallel execution before Protect was called.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
This commit is contained in:
Paweł Gronowski 2024-01-17 10:36:39 +01:00
parent 2c47a6df0d
commit fa4deb02af
No known key found for this signature in database
GPG key ID: B85EFCFE26DEF92A
2 changed files with 22 additions and 0 deletions

View file

@ -10,6 +10,7 @@ import (
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/errdefs"
"github.com/docker/docker/testutil"
"go.opentelemetry.io/otel"
"gotest.tools/v3/assert"
)
@ -38,6 +39,8 @@ func newProtectedElements() protectedElements {
// volumes, and, on Linux, plugins) from being cleaned up at the end of test
// runs
func ProtectAll(ctx context.Context, t testing.TB, testEnv *Execution) {
testutil.CheckNotParallel(t)
t.Helper()
ctx, span := otel.Tracer("").Start(ctx, "ProtectAll")
defer span.End()

View file

@ -7,6 +7,7 @@ import (
"context"
"io"
"os"
"reflect"
"strings"
"sync"
"testing"
@ -156,3 +157,21 @@ func SetContext(t TestingT, ctx context.Context) {
func CleanupContext(t *testing.T) {
testContexts.Delete(t)
}
// CheckNotParallel checks if t.Parallel() was not called on the current test.
// There's no public method to check this, so we use reflection to check the
// internal field set by t.Parallel()
// https://github.com/golang/go/blob/8e658eee9c7a67a8a79a8308695920ac9917566c/src/testing/testing.go#L1449
//
// Since this is not a public API, it might change at any time.
func CheckNotParallel(t testing.TB) {
t.Helper()
field := reflect.ValueOf(t).Elem().FieldByName("isParallel")
if field.IsValid() {
if field.Bool() {
t.Fatal("t.Parallel() was called before")
}
} else {
t.Logf("FIXME: CheckParallel could not determine if test %s is parallel - did the t.Parallel() implementation change?", t.Name())
}
}