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.
This commit is contained in:
Patrick Ohly
2025-12-09 12:01:56 +01:00
parent 57ae8e991a
commit dab76ef8de
2 changed files with 28 additions and 0 deletions

View File

@@ -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
}

View File

@@ -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))
}