From fa4deb02afc15c02b7c28788d057e54952c0fa66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Gronowski?= Date: Wed, 17 Jan 2024 10:36:39 +0100 Subject: [PATCH] environment: Error when t.Parallel was called before Protect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- testutil/environment/protect.go | 3 +++ testutil/helpers.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/testutil/environment/protect.go b/testutil/environment/protect.go index 34a5cc5805..14bb569928 100644 --- a/testutil/environment/protect.go +++ b/testutil/environment/protect.go @@ -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() diff --git a/testutil/helpers.go b/testutil/helpers.go index 5c99e7bba4..dfc8c5d344 100644 --- a/testutil/helpers.go +++ b/testutil/helpers.go @@ -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()) + } +}