Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

编写控制器测试

测试 Kubernetes 控制器是一个大主题,而 kubebuilder 为您生成的样板测试文件相对较少。

为了引导您了解用于 Kubebuilder 生成的控制器的集成测试模式,我们将重新审视在首个教程中构建的 CronJob,并为其编写一个简单的测试。

基本的方法是,在您生成的 suite_test.go 文件中,您将使用 envtest 创建一个本地 Kubernetes API 服务器,实例化并运行您的控制器,然后编写额外的 *_test.go 文件,通过 Ginkgo 来进行测试。

如果您想要调整您的 envtest 集群的配置,请参阅为集成测试配置 envtest一节,以及envtest 文档。

测试环境设置

../../cronjob-tutorial/testdata/project/internal/controller/suite_test.go
Apache License

Copyright 2026 The Kubernetes authors.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Imports

当我们在上一章用 kubebuilder create api 创建 CronJob API 时,Kubebuilder 已为你做了一些测试工作。Kubebuilder 脚手架生成了 internal/controller/suite_test.go,完成了测试环境的基础设置。

首先,它将包含必要的 import。

package controller

import (
	"context"
	"os"
	"path/filepath"
	"testing"

	ctrl "sigs.k8s.io/controller-runtime"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"

	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/envtest"
	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"

	batchv1 "tutorial.kubebuilder.io/project/api/v1"
	// +kubebuilder:scaffold:imports
)

// These tests use Ginkgo (BDD-style Go testing framework). Refer to
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.

现在,我们来过一遍生成的代码。

var (
	ctx       context.Context
	cancel    context.CancelFunc
	testEnv   *envtest.Environment
	cfg       *rest.Config
	k8sClient client.Client // You'll be using this client in your tests.
)

func TestControllers(t *testing.T) {
	RegisterFailHandler(Fail)

	RunSpecs(t, "Controller Suite")
}

var _ = BeforeSuite(func() {
	logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

	ctx, cancel = context.WithCancel(context.TODO())

	var err error

CronJob Kind 被加入测试环境使用的运行时 Scheme。这确保 CronJob API 已向 Scheme 注册,使测试控制器能够识别并与 CronJob 资源交互。

	err = batchv1.AddToScheme(scheme.Scheme)
	Expect(err).NotTo(HaveOccurred())

在 schemas 之后,你会看到以下标记。正是此标记允许在向项目添加新 API 时自动在此处加入新 schema。

	// +kubebuilder:scaffold:scheme

envtest 环境配置为从指定目录加载自定义资源定义(CRD)。此设置使测试环境能够识别并与这些 CRD 定义的自定义资源交互。

	By("bootstrapping test environment")
	testEnv = &envtest.Environment{
		CRDDirectoryPaths:     []string{filepath.Join("..", "..", "config", "crd", "bases")},
		ErrorIfCRDPathMissing: true,
	}

	// Retrieve the first found binary directory to allow running tests from IDEs
	if getFirstFoundEnvTestBinaryDir() != "" {
		testEnv.BinaryAssetsDirectory = getFirstFoundEnvTestBinaryDir()
	}

然后,我们启动 envtest 集群。

	// cfg is defined in this file globally.
	cfg, err = testEnv.Start()
	Expect(err).NotTo(HaveOccurred())
	Expect(cfg).NotTo(BeNil())

创建一个用于测试 CRUD 操作的客户端。

	k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
	Expect(err).NotTo(HaveOccurred())
	Expect(k8sClient).NotTo(BeNil())

不过,此自动生成文件缺少的一点是实际启动控制器的方式。上面的代码会设置用于与自定义 Kind 交互的客户端,但无法测试控制器行为。若要测试自定义控制器逻辑,需要在 BeforeSuite() 函数中加入一些眼熟的 manager 逻辑,以便把自定义控制器注册到此测试集群上运行。

你可能注意到下面的代码以与 CronJob 项目 main.go 几乎相同的逻辑运行控制器!唯一区别是 manager 在单独的 goroutine 中启动,以免在测试结束后阻塞 envtest 的清理。

注意我们同时设置了「实时」k8s 客户端与来自 manager 的单独客户端。这是因为在测试中做断言时,通常希望针对 API 服务器的实时状态断言。若使用 manager 的客户端(k8sManager.GetClient),会针对缓存内容断言,更慢且可能使测试不稳定。也可用 manager 的 APIReader 达到同样效果,但那样测试断言与设置中会有两个客户端(一个读、一个写),容易出错。

不过请注意,我们仍让 reconciler 针对 manager 的缓存客户端运行——我们希望控制器表现得像生产环境,并且使用了直接与 API 服务器通信时不可用的缓存功能(如索引)。

	k8sManager, err := ctrl.NewManager(cfg, ctrl.Options{
		Scheme: scheme.Scheme,
	})
	Expect(err).ToNot(HaveOccurred())

	err = (&CronJobReconciler{
		Client: k8sManager.GetClient(),
		Scheme: k8sManager.GetScheme(),
	}).SetupWithManager(k8sManager)
	Expect(err).ToNot(HaveOccurred())

	go func() {
		defer GinkgoRecover()
		err = k8sManager.Start(ctx)
		Expect(err).ToNot(HaveOccurred(), "failed to run manager")
	}()
})

Kubebuilder 还会生成用于清理 envtest 以及在 controllers/ 目录实际运行测试文件的样板函数。你无需改动这些。

var _ = AfterSuite(func() {
	By("tearing down the test environment")
	cancel()
	err := testEnv.Stop()
	Expect(err).NotTo(HaveOccurred())
})

现在控制器已在测试集群上运行,且客户端已准备好对 CronJob 执行操作,我们可以开始编写集成测试!

// getFirstFoundEnvTestBinaryDir locates the first binary in the specified path.
// ENVTEST-based tests depend on specific binaries, usually located in paths set by
// controller-runtime. When running tests directly (e.g., via an IDE) without using
// Makefile targets, the 'BinaryAssetsDirectory' must be explicitly configured.
//
// This function streamlines the process by finding the required binaries, similar to
// setting the 'KUBEBUILDER_ASSETS' environment variable. To ensure the binaries are
// properly set up, run 'make setup-envtest' beforehand.
func getFirstFoundEnvTestBinaryDir() string {
	basePath := filepath.Join("..", "..", "bin", "k8s")
	entries, err := os.ReadDir(basePath)
	if err != nil {
		logf.Log.Error(err, "Failed to read directory", "path", basePath)
		return ""
	}
	for _, entry := range entries {
		if entry.IsDir() {
			return filepath.Join(basePath, entry.Name())
		}
	}
	return ""
}

测试您的控制器行为

../../cronjob-tutorial/testdata/project/internal/controller/cronjob_controller_test.go
Apache License

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

理想情况下,应为每个脚手架生成并在 suite_test.go 中调用的控制器准备一个 <kind>_controller_test.go。因此,我们为 CronJob 控制器编写示例测试(cronjob_controller_test.go)。

Imports

照例,我们从必要的 import 开始。

package controller

import (
	"context"
	"reflect"
	"time"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	batchv1 "k8s.io/api/batch/v1"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"

	cronjobv1 "tutorial.kubebuilder.io/project/api/v1"
)

编写简单集成测试的第一步是实际创建一个可对之运行测试的 CronJob 实例。注意要创建 CronJob,需要创建一个包含 CronJob 规格的桩 CronJob 结构体。

注意:创建桩 CronJob 时,CronJob 还需要其必需下游对象的桩。若没有下面的桩 Job 模板 spec 与 Pod 模板 spec,Kubernetes API 将无法创建 CronJob。

var _ = Describe("CronJob controller", func() {
	Context("CronJob controller test", func() {

		const (
			CronjobName        = "test-cronjob"
			testContainerName  = "test-container"
			testContainerImage = "test-image"
		)

		ctx := context.Background()

		namespace := &v1.Namespace{
			ObjectMeta: metav1.ObjectMeta{
				Name:      CronjobName,
				Namespace: CronjobName,
			},
		}

		typeNamespacedName := types.NamespacedName{
			Name:      CronjobName,
			Namespace: CronjobName,
		}
		cronJob := &cronjobv1.CronJob{}

		SetDefaultEventuallyTimeout(2 * time.Minute)
		SetDefaultEventuallyPollingInterval(time.Second)

		BeforeEach(func() {
			By("Creating the Namespace to perform the tests")
			err := k8sClient.Get(ctx, types.NamespacedName{Name: CronjobName}, &v1.Namespace{})
			if err != nil && errors.IsNotFound(err) {
				err = k8sClient.Create(ctx, namespace)
				Expect(err).NotTo(HaveOccurred())
			}

			By("creating the custom resource for the Kind CronJob")
			cronJob = &cronjobv1.CronJob{}
			err = k8sClient.Get(ctx, typeNamespacedName, cronJob)
			if err != nil && errors.IsNotFound(err) {
			

让我们以与从 config/samples 下的清单应用相同的方式 mock 自定义资源

				cronJob = &cronjobv1.CronJob{
					ObjectMeta: metav1.ObjectMeta{
						Name:      CronjobName,
						Namespace: namespace.Name,
					},
					Spec: cronjobv1.CronJobSpec{
						Schedule: "1 * * * *",
						JobTemplate: batchv1.JobTemplateSpec{
							Spec: batchv1.JobSpec{
								Template: v1.PodTemplateSpec{
									Spec: v1.PodSpec{
										Containers: []v1.Container{
											{
												Name:  testContainerName,
												Image: testContainerImage,
											},
										},
										RestartPolicy: v1.RestartPolicyOnFailure,
									},
								},
							},
						},
					},
				}

				err = k8sClient.Create(ctx, cronJob)
				Expect(err).NotTo(HaveOccurred())
			}
		})

	

每个测试后,清理上面创建的资源。

		AfterEach(func() {
			By("removing the custom resource for the Kind CronJob")
			found := &cronjobv1.CronJob{}
			err := k8sClient.Get(ctx, typeNamespacedName, found)
			Expect(err).NotTo(HaveOccurred())

			Eventually(func(g Gomega) {
				g.Expect(k8sClient.Delete(context.TODO(), found)).To(Succeed())
			}).Should(Succeed())

			// TODO(user): Attention if you improve this code by adding other context test you MUST
			// be aware of the current delete namespace limitations.
			// More info: https://book.kubebuilder.io/reference/envtest.html#testing-considerations
			By("Deleting the Namespace to perform the tests")
			_ = k8sClient.Delete(ctx, namespace)
		})

	

现在我们可以开始实现校验控制器协调行为的测试。

		It("should successfully reconcile a custom resource for CronJob", func() {
			By("Checking if the custom resource was successfully created")
			Eventually(func(g Gomega) {
				found := &cronjobv1.CronJob{}
				g.Expect(k8sClient.Get(ctx, typeNamespacedName, found)).To(Succeed())
			}).Should(Succeed())

		

创建此 CronJob 后,验证控制器是否正确初始化 status 条件。控制器在后台运行(在 suite_test.go 中启动),因此会自动检测我们的 CronJob 并设置初始条件。

			By("Checking that status conditions are initialized")
			Eventually(func(g Gomega) {
				g.Expect(k8sClient.Get(ctx, typeNamespacedName, cronJob)).To(Succeed())
				g.Expect(cronJob.Status.Conditions).NotTo(BeEmpty())
			}).Should(Succeed())

		

现在验证 CronJob 最初没有活动 Job。这里使用 Gomega 的 Consistently() 检查以确保 status 保持稳定,确认控制器未过早创建 Job。

			By("Checking that the CronJob has zero active Jobs")
			Consistently(func(g Gomega) {
				g.Expect(k8sClient.Get(ctx, typeNamespacedName, cronJob)).To(Succeed())
				g.Expect(cronJob.Status.Active).To(BeEmpty())
			}).WithTimeout(time.Second * 10).WithPolling(time.Millisecond * 250).Should(Succeed())

		

接下来,我们实际创建一个属于 CronJob 的桩 Job。将 Job 的 status Active 计数设为 2,以模拟正在运行两个 Pod,即 Job 处于活动运行中。

然后我们将 Job 的所有者引用指向测试 CronJob。这确保测试 Job 属于并被我们的测试 CronJob 跟踪。

			By("Creating a new Job owned by the CronJob")
			testJob := &batchv1.Job{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-job",
					Namespace: namespace.Name,
				},
				Spec: batchv1.JobSpec{
					Template: v1.PodTemplateSpec{
						Spec: v1.PodSpec{
							Containers: []v1.Container{
								{
									Name:  testContainerName,
									Image: testContainerImage,
								},
							},
							RestartPolicy: v1.RestartPolicyOnFailure,
						},
					},
				},
			}

			// Note that your CronJob’s GroupVersionKind is required to set up this owner reference.
			kind := reflect.TypeFor[cronjobv1.CronJob]().Name()
			gvk := cronjobv1.GroupVersion.WithKind(kind)

			controllerRef := metav1.NewControllerRef(cronJob, gvk)
			testJob.SetOwnerReferences([]metav1.OwnerReference{*controllerRef})
			Expect(k8sClient.Create(ctx, testJob)).To(Succeed())
			// Note that you can not manage the status values while creating the resource.
			// The status field is managed separately to reflect the current state of the resource.
			// Therefore, it should be updated using a PATCH or PUT operation after the resource has been created.
			// Additionally, it is recommended to use StatusConditions to manage the status. For further information see:
			// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
			testJob.Status.Active = 2
			Expect(k8sClient.Status().Update(ctx, testJob)).To(Succeed())

		

将此 Job 添加到测试 CronJob 应触发控制器的 reconciler 逻辑。之后,我们可以验证控制器最终是否按预期更新了 CronJob 的 Status 字段!

			By("Checking that the CronJob has one active Job in status")
			Eventually(func(g Gomega) {
				g.Expect(k8sClient.Get(ctx, typeNamespacedName, cronJob)).To(Succeed())
				g.Expect(cronJob.Status.Active).To(HaveLen(1), "should have exactly one active job")
				g.Expect(cronJob.Status.Active[0].Name).To(Equal("test-job"), "the active job name should match")
			}).Should(Succeed())

		

最后,验证控制器是否正确设置了 status 条件。Status 条件是 Kubernetes API 约定的关键部分,让用户和其他控制器能够理解资源状态。

当有活动 Job 时,Available 条件应为 True,原因为 JobsActive。

			By("Checking the latest Status Condition added to the CronJob instance")
			Expect(k8sClient.Get(ctx, typeNamespacedName, cronJob)).To(Succeed())
			var conditions []metav1.Condition
			Expect(cronJob.Status.Conditions).To(ContainElement(
				HaveField("Type", Equal("Available")), &conditions))
			Expect(conditions).To(HaveLen(1), "should have one Available condition")
			Expect(conditions[0].Status).To(Equal(metav1.ConditionTrue), "Available should be True")
			Expect(conditions[0].Reason).To(Equal("JobsActive"), "reason should be JobsActive")

		

接下来,验证控制器是否根据历史限制裁剪旧的已完成 Job。

			By("Checking that old finished Jobs are pruned by history limits")
			failedJobsHistoryLimit := int32(1)
			successfulJobsHistoryLimit := int32(1)
			Eventually(func(g Gomega) {
				g.Expect(k8sClient.Get(ctx, typeNamespacedName, cronJob)).To(Succeed())
				cronJob.Spec.FailedJobsHistoryLimit = &failedJobsHistoryLimit
				cronJob.Spec.SuccessfulJobsHistoryLimit = &successfulJobsHistoryLimit
				g.Expect(k8sClient.Update(ctx, cronJob)).To(Succeed())
			}).Should(Succeed())

			createFinishedJob := func(name string, conditionType batchv1.JobConditionType, startTime *metav1.Time) *batchv1.Job {
				finishedJob := &batchv1.Job{
					ObjectMeta: metav1.ObjectMeta{
						Name:      name,
						Namespace: namespace.Name,
					},
					Spec: batchv1.JobSpec{
						Template: v1.PodTemplateSpec{
							Spec: v1.PodSpec{
								Containers: []v1.Container{
									{
										Name:  testContainerName,
										Image: testContainerImage,
									},
								},
								RestartPolicy: v1.RestartPolicyOnFailure,
							},
						},
					},
				}
				finishedJob.SetOwnerReferences([]metav1.OwnerReference{*controllerRef})
				Expect(k8sClient.Create(ctx, finishedJob)).To(Succeed())

				finishedJob.Status.StartTime = startTime
				finishedJob.Status.Conditions = []batchv1.JobCondition{{
					Type:   conditionType,
					Status: v1.ConditionTrue,
				}}
				if conditionType == batchv1.JobFailed {
					finishedJob.Status.Conditions = append([]batchv1.JobCondition{{
						Type:   batchv1.JobFailureTarget,
						Status: v1.ConditionTrue,
					}}, finishedJob.Status.Conditions...)
				}
				if conditionType == batchv1.JobComplete {
					finishedJob.Status.CompletionTime = startTime
					finishedJob.Status.Conditions = append([]batchv1.JobCondition{{
						Type:   batchv1.JobSuccessCriteriaMet,
						Status: v1.ConditionTrue,
					}}, finishedJob.Status.Conditions...)
				}
				Expect(k8sClient.Status().Update(ctx, finishedJob)).To(Succeed())

				return finishedJob
			}

			baseTime := time.Now()
			failedOldStartTime := metav1.NewTime(baseTime.Add(-time.Minute))
			failedNewStartTime := metav1.NewTime(baseTime.Add(time.Second))
			successfulOldStartTime := metav1.NewTime(baseTime.Add(-time.Minute))
			successfulNewStartTime := metav1.NewTime(baseTime.Add(time.Second))

			failedOldJob := createFinishedJob("test-failed-job-old", batchv1.JobFailed, &failedOldStartTime)
			failedNewJob := createFinishedJob("test-failed-job-new", batchv1.JobFailed, &failedNewStartTime)
			successfulOldJob := createFinishedJob("test-successful-job-old", batchv1.JobComplete, &successfulOldStartTime)
			successfulNewJob := createFinishedJob("test-successful-job-new", batchv1.JobComplete, &successfulNewStartTime)

			assertJobDeleted := func(g Gomega, job *batchv1.Job) {
				found := &batchv1.Job{}
				err := k8sClient.Get(ctx, types.NamespacedName{Name: job.Name, Namespace: job.Namespace}, found)
				g.Expect(errors.IsNotFound(err)).To(BeTrue())
			}
			assertJobExists := func(g Gomega, job *batchv1.Job) {
				found := &batchv1.Job{}
				g.Expect(k8sClient.Get(ctx, types.NamespacedName{Name: job.Name, Namespace: job.Namespace}, found)).To(Succeed())
			}

			Eventually(func(g Gomega) {
				assertJobDeleted(g, failedOldJob)
				assertJobDeleted(g, successfulOldJob)
				assertJobExists(g, failedNewJob)
				assertJobExists(g, successfulNewJob)
			}).Should(Succeed())
		})
	})
})

写完这些代码后,可以再次在 controllers/ 目录运行 make test 或 go test ./... 来运行新测试!

以上的状态更新示例展示了一种针对自定义 Kind 及其下游对象的一般测试策略。到目前为止,希望您已经学习了以下测试控制器行为的方法:

  • 在 envtest 集群上设置您的控制器
  • 为创建测试对象编写存根
  • 将变化孤立到一个对象,以测试特定控制器的行为