From dab76ef8de9d9697033c13137c6ef3523704f968 Mon Sep 17 00:00:00 2001 From: Patrick Ohly Date: Tue, 9 Dec 2025 12:01:56 +0100 Subject: [PATCH] ktesting: add namespace support Many helper packages need to know the test namespace in addition to the client. Supporting passing of that information through the TContext avoids adding another parameter to such helper packages. This mirrors similar functionality in framework.Framework which also provides a namespace to the test and packages taking such a parameter. --- test/utils/ktesting/tcontext.go | 20 ++++++++++++++++++++ test/utils/ktesting/tcontext_test.go | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/test/utils/ktesting/tcontext.go b/test/utils/ktesting/tcontext.go index 11e6f93eb4b..8bc639c5af7 100644 --- a/test/utils/ktesting/tcontext.go +++ b/test/utils/ktesting/tcontext.go @@ -392,6 +392,9 @@ type TC struct { dynamic dynamic.Interface apiextensions apiextensions.Interface + // for WithNamespace + namespace string + // capture, if non-nil, changes Error/Errorf/Fatal/Fatalf/Fail/FailNow so // that they intercept the problem and convert to errors. Log messages // are passed through. @@ -598,3 +601,20 @@ func (tc *TC) Require(actual interface{}, extra ...interface{}) gomega.Assertion func (tc *TC) Assert(actual interface{}, extra ...interface{}) gomega.Assertion { return gomegaAssertion(tc, false, actual, extra...) } + +// WithNamespace creates a new context with a Kubernetes namespace name for retrieval through [Namespace]. +func (tc *TC) WithNamespace(namespace string) TContext { + tc = tc.clone() + tc.namespace = namespace + return tc +} + +// Namespace returns the Kubernetes namespace name that was set previously +// through WithNamespace and the empty string if none is available. +// +// This namespace is the one to be used by tests which need to create namespace-scoped +// objects. The name is guaranteed to be unique for the test context, so tests running +// in parallel need to be set up so that each test has its own namespace. +func (tc *TC) Namespace() string { + return tc.namespace +} diff --git a/test/utils/ktesting/tcontext_test.go b/test/utils/ktesting/tcontext_test.go index 09ca8b49696..dc5f969cc7d 100644 --- a/test/utils/ktesting/tcontext_test.go +++ b/test/utils/ktesting/tcontext_test.go @@ -20,6 +20,7 @@ import ( "sync" "testing" + "github.com/onsi/gomega" "github.com/stretchr/testify/assert" apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" @@ -128,3 +129,10 @@ func TestRun(t *testing.T) { t.Errorf("parent TContext should not have been cancelled: %v", err) } } + +func TestWithNamespace(t *testing.T) { + tCtx := ktesting.Init(t) + namespace := "foo" + tCtxWithNamespace := tCtx.WithNamespace(namespace) + tCtx.Expect(tCtxWithNamespace.Namespace()).To(gomega.Equal(namespace)) +}