Skip to content

Latest commit

 

History

History
37 lines (23 loc) · 2.48 KB

File metadata and controls

37 lines (23 loc) · 2.48 KB

Writing controller tests

Testing Kubernetes controllers is a big subject, and the boilerplate testing files generated for you by kubebuilder are fairly minimal.

To walk you through integration testing patterns for Kubebuilder-generated controllers, we will revisit the CronJob we built in our first tutorial and write a simple test for it.

The basic approach is that, in your generated suite_test.go file, you will use envtest to create a local Kubernetes API server, instantiate and run your controllers, and then write additional *_test.go files to test it using Ginkgo.

If you want to tinker with how your envtest cluster is configured, see section Configuring envtest for integration tests as well as the envtest docs.

Other Examples

If you would like to see additional examples of controller tests generated by Kubebuilder, take a look at the Deploy Image plugin (deploy-image/v1-alpha). This plugin scaffolds APIs and controllers for managing an Operand (container image) on a cluster, following recommended patterns.

The plugin abstracts much of the complexity of managing Deployments while still allowing you to customize the generated code. When enabled, it also generates a controller test that uses ENV TEST to verify that the expected Deployment is created.

An example of this test can be found under the testdata directory in the Kubebuilder repository: testdata/project-v4-with-plugins/internal/controller/busybox_controller_test.go.

Test Environment Setup

{{#literatego ../cronjob-tutorial/testdata/project/internal/controller/suite_test.go}}

Testing your Controller's Behavior

{{#literatego ../cronjob-tutorial/testdata/project/internal/controller/cronjob_controller_test.go}}

This Status update example above demonstrates a general testing strategy for a custom Kind with downstream objects. By this point, you hopefully have learned the following methods for testing your controller behavior:

  • Setting up your controller to run on an envtest cluster
  • Writing stubs for creating test objects
  • Isolating changes to an object to test specific controller behavior