Refactor NewTestContext to return Context instead of TContext

This commit is contained in:
Karthik Bhat
2026-01-23 14:54:16 +05:30
parent 761638907a
commit 43bfd8615d
9 changed files with 46 additions and 33 deletions

View File

@@ -919,8 +919,9 @@ func TestGarbageCollectorSync(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
logger, tCtx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
defer tCtx.Cancel("test has completed")
logger := tCtx.Logger()
alwaysStarted := make(chan struct{})
close(alwaysStarted)

View File

@@ -168,8 +168,9 @@ func TestServiceAccountCreation(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
logger, ctx := ktesting.NewTestContext(t)
defer ctx.Cancel("test case terminating")
tCtx := ktesting.Init(t)
logger := tCtx.Logger()
defer tCtx.Cancel("test case terminating")
controller, err := NewServiceAccountsController(
logger,
@@ -200,7 +201,7 @@ func TestServiceAccountCreation(t *testing.T) {
stopCh := make(chan struct{})
defer close(stopCh)
wg.Go(func() {
controller.Run(ctx, 1)
controller.Run(tCtx, 1)
})
if tc.ExistingNamespace != nil {

View File

@@ -85,7 +85,8 @@ func Test_NewAttachDetachController_Positive(t *testing.T) {
}
func Test_AttachDetachControllerStateOfWorldPopulators_Positive(t *testing.T) {
logger, tCtx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
logger := tCtx.Logger()
// Arrange
fakeKubeClient := controllervolumetesting.CreateTestClient(logger)
@@ -203,7 +204,7 @@ func BenchmarkPopulateActualStateOfWorld(b *testing.B) {
fakeKubeClient := largeClusterClient(b, 10000)
informerFactory := informers.NewSharedInformerFactory(fakeKubeClient, controller.NoResyncPeriodFunc())
logger, tCtx := ktesting.NewTestContext(b)
tCtx := ktesting.Init(b)
adc := createADC(b, tCtx, fakeKubeClient, informerFactory, nil)
// Act
@@ -212,7 +213,7 @@ func BenchmarkPopulateActualStateOfWorld(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
err := adc.populateActualStateOfWorld(logger)
err := adc.populateActualStateOfWorld(tCtx.Logger())
if err != nil {
b.Fatalf("Run failed with error. Expected: <no error> Actual: <%v>", err)
}
@@ -223,7 +224,8 @@ func BenchmarkNodeUpdate(b *testing.B) {
fakeKubeClient := largeClusterClient(b, 3000)
informerFactory := informers.NewSharedInformerFactory(fakeKubeClient, controller.NoResyncPeriodFunc())
logger, tCtx := ktesting.NewTestContext(b)
tCtx := ktesting.Init(b)
logger := tCtx.Logger()
adc := createADC(b, tCtx, fakeKubeClient, informerFactory, nil)
informerFactory.Start(tCtx.Done())
@@ -282,7 +284,9 @@ func Test_AttachDetachControllerRecovery(t *testing.T) {
func attachDetachRecoveryTestCase(t *testing.T, extraPods1 []*v1.Pod, extraPods2 []*v1.Pod) {
tCtx := ktesting.Init(t)
fakeKubeClient := controllervolumetesting.CreateTestClient(tCtx.Logger())
logger := tCtx.Logger()
fakeKubeClient := controllervolumetesting.CreateTestClient(logger)
informerFactory := informers.NewSharedInformerFactory(fakeKubeClient, time.Second*1)
plugins := controllervolumetesting.CreateTestPlugin(true)
var prober volume.DynamicPluginProber = nil // TODO (#51147) inject mock
@@ -294,7 +298,6 @@ func attachDetachRecoveryTestCase(t *testing.T, extraPods1 []*v1.Pod, extraPods2
// Create the controller
var wg sync.WaitGroup
defer wg.Wait()
logger, tCtx := ktesting.NewTestContext(t)
defer tCtx.Cancel("test case terminating")
adcObj, err := NewAttachDetachController(
@@ -538,7 +541,9 @@ func Test_ADC_VolumeAttachmentRecovery(t *testing.T) {
func volumeAttachmentRecoveryTestCase(t *testing.T, tc vaTest) {
tCtx := ktesting.Init(t)
fakeKubeClient := controllervolumetesting.CreateTestClient(tCtx.Logger())
logger := tCtx.Logger()
fakeKubeClient := controllervolumetesting.CreateTestClient(logger)
informerFactory := informers.NewSharedInformerFactory(fakeKubeClient, time.Second*1)
var plugins []volume.VolumePlugin
@@ -553,7 +558,6 @@ func volumeAttachmentRecoveryTestCase(t *testing.T, tc vaTest) {
// Create the controller
var wg sync.WaitGroup
defer wg.Wait()
logger, tCtx := ktesting.NewTestContext(t)
defer tCtx.Cancel("test case terminating")
adc := createADC(t, tCtx, fakeKubeClient, informerFactory, plugins)
@@ -738,8 +742,10 @@ func verifyAttachDetachCalls(t *testing.T, testPlugin *controllervolumetesting.T
}
func TestPodDelete_Tombstone(t *testing.T) {
_, tCtx := ktesting.NewTestContext(t)
fakeKubeClient := controllervolumetesting.CreateTestClient(tCtx.Logger())
tCtx := ktesting.Init(t)
logger := tCtx.Logger()
fakeKubeClient := controllervolumetesting.CreateTestClient(logger)
informerFactory := informers.NewSharedInformerFactory(fakeKubeClient, controller.NoResyncPeriodFunc())
adc := createADC(t, tCtx, fakeKubeClient, informerFactory,
@@ -749,14 +755,14 @@ func TestPodDelete_Tombstone(t *testing.T) {
volumeName := v1.UniqueVolumeName(csiPDUniqueNamePrefix + "pdName")
adc.desiredStateOfWorld.AddNode("node1")
adc.podAdd(tCtx.Logger(), pod)
adc.podAdd(logger, pod)
if !adc.desiredStateOfWorld.VolumeExists(volumeName, "node1") {
t.Fatalf("expected volume %s to exist in dsw", volumeName)
}
// Tombstone
adc.podDelete(tCtx.Logger(), kcache.DeletedFinalStateUnknown{Key: "mynamespace/pod1", Obj: pod})
adc.podDelete(logger, kcache.DeletedFinalStateUnknown{Key: "mynamespace/pod1", Obj: pod})
if adc.desiredStateOfWorld.VolumeExists(volumeName, "node1") {
t.Errorf("expected volume %s to be removed from dsw", volumeName)

View File

@@ -198,8 +198,9 @@ func TestPodVolumesExist(t *testing.T) {
},
}
logger, tCtx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
defer tCtx.Cancel("test has completed")
go kubelet.volumeManager.Run(tCtx, kubelet.sourcesReady)
kubelet.podManager.SetPods(pods)
@@ -209,7 +210,7 @@ func TestPodVolumesExist(t *testing.T) {
}
for _, pod := range pods {
podVolumesExist := kubelet.podVolumesExist(logger, pod.UID)
podVolumesExist := kubelet.podVolumesExist(tCtx.Logger(), pod.UID)
assert.True(t, podVolumesExist, "pod %q", pod.UID)
}
}

View File

@@ -80,7 +80,7 @@ func TestTCPPortExhaustion(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
logger, tCtx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
podManager := kubepod.NewBasicPodManager()
podStartupLatencyTracker := kubeletutil.NewPodStartupLatencyTracker()
m := NewManager(
@@ -134,7 +134,7 @@ func TestTCPPortExhaustion(t *testing.T) {
})
}
podManager.AddPod(&pod)
m.statusManager.SetPodStatus(logger, &pod, pod.Status)
m.statusManager.SetPodStatus(tCtx.Logger(), &pod, pod.Status)
m.AddPod(tCtx, &pod)
}
t.Logf("Adding %d pods with %d containers each in %v", numTestPods, numContainers, time.Since(now))

View File

@@ -426,7 +426,7 @@ func TestPolicyAdmission(t *testing.T) {
}
func testPolicyAdmission(t *testing.T, supportV1Beta1 bool) {
_, ctx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
supportedVersions := []string{}
if supportV1Beta1 {
supportedVersions = append(supportedVersions, "v1beta1")
@@ -466,7 +466,7 @@ func testPolicyAdmission(t *testing.T, supportV1Beta1 bool) {
// create CRDs
etcd.CreateTestCRDs(t, apiextensionsclientset.NewForConfigOrDie(server.ClientConfig), false, etcd.GetCustomResourceDefinitionData()...)
if _, err := client.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}, metav1.CreateOptions{}); err != nil {
if _, err := client.CoreV1().Namespaces().Create(tCtx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}, metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
@@ -563,11 +563,11 @@ func testPolicyAdmission(t *testing.T, supportV1Beta1 bool) {
}
if supportV1Beta1 {
if err := createV1beta1ValidatingPolicyAndBinding(ctx, client, convertedV1beta1Rules); err != nil {
if err := createV1beta1ValidatingPolicyAndBinding(tCtx, client, convertedV1beta1Rules); err != nil {
t.Fatal(err)
}
} else {
if err := createV1ValidatingPolicyAndBinding(ctx, client, convertedV1Rules); err != nil {
if err := createV1ValidatingPolicyAndBinding(tCtx, client, convertedV1Rules); err != nil {
t.Fatal(err)
}
}
@@ -577,13 +577,13 @@ func testPolicyAdmission(t *testing.T, supportV1Beta1 bool) {
Name: "test-k8s",
},
}
_, err = client.CoreV1().ConfigMaps(testNamespace).Create(ctx, &testConfigmap, metav1.CreateOptions{})
_, err = client.CoreV1().ConfigMaps(testNamespace).Create(tCtx, &testConfigmap, metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
// Try to patch the configmap and look for the warning message.
if err := wait.PollUntilContextTimeout(ctx, time.Millisecond*100, time.Second*5, false, func(ctx context.Context) (bool, error) {
if err := wait.PollUntilContextTimeout(tCtx, time.Millisecond*100, time.Second*5, false, func(ctx context.Context) (bool, error) {
holder.reset(t)
_, err = client.CoreV1().ConfigMaps(testNamespace).Patch(ctx, testConfigmap.Name, types.JSONPatchType, []byte("[]"), metav1.PatchOptions{})
if err != nil {
@@ -599,7 +599,7 @@ func testPolicyAdmission(t *testing.T, supportV1Beta1 bool) {
t.Errorf("timed out waiting policy and binding to establish: %v", err)
}
err = client.CoreV1().ConfigMaps(testNamespace).Delete(ctx, testConfigmap.Name, metav1.DeleteOptions{})
err = client.CoreV1().ConfigMaps(testNamespace).Delete(tCtx, testConfigmap.Name, metav1.DeleteOptions{})
if err != nil {
t.Errorf("failed to delete ConfigMap with error: %+v", err)
}

View File

@@ -496,7 +496,7 @@ type batchGetter interface {
}
func runScenario(t *testing.T, tt *scenario, batch bool) ([]*v1.Pod, []bool) {
_, tCtx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
cfg, err := newDefaultComponentConfig()
if err != nil {

View File

@@ -213,7 +213,7 @@ func TestRunOp(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, tCtx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
client := fake.NewSimpleClientset()
tCtx = tCtx.WithClients(nil, nil, client, nil, nil)
@@ -618,7 +618,7 @@ func TestMetricThreshold(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
_, tCtx := ktesting.NewTestContext(t)
tCtx := ktesting.Init(t)
var capturedErr error
capturingCtx, finalize := tCtx.WithError(&capturedErr)
defer finalize()

View File

@@ -17,6 +17,7 @@ limitations under the License.
package ktesting
import (
"context"
"flag"
"fmt"
"testing"
@@ -43,9 +44,12 @@ func SetDefaultVerbosity(v int) {
_ = f.Value.Set(fmt.Sprintf("%d", v))
}
// NewTestContext is a replacement for ktesting.NewTestContext
// which returns a more versatile context.
func NewTestContext(tb testing.TB) (klog.Logger, TContext) {
// NewTestContext is a drop-in replacement for ktesting.NewTestContext.
//
// The result can be cast to a TContext and has the same functionality
// (for example, it gets cancelled at the end of the test).
// It's returned as a context.Context to avoid breaking code which expects that type.
func NewTestContext(tb testing.TB) (klog.Logger, context.Context) {
tCtx := Init(tb)
return tCtx.Logger(), tCtx
}