Write E2E Tests
You can check the Kubebuilder/v4/test/e2e/utils package, which offers TestContext
with rich methods:
- NewTestContext helps define:
- A temporary folder for testing projects.
- A temporary controller-manager image.
- The Kubectl execution method.
- The CLI executable (whether
kubebuilder
,operator-sdk
, or your extended CLI).
Once defined, you can use TestContext
to:
-
Setup the testing environment, e.g.:
- Clean up the environment and create a temporary directory. See Prepare.
- Install prerequisite CRDs. See InstallCertManager, InstallPrometheusManager.
-
Validate the plugin behavior, e.g.:
- Trigger the plugin’s bound subcommands. See Init, CreateAPI.
- Use PluginUtil to verify scaffolded outputs. See InsertCode, ReplaceInFile, UncommentCode.
-
Ensure the scaffolded output works, e.g.:
- Execute commands in your
Makefile
. See Make. - Temporarily load an image of the testing controller. See LoadImageToKindCluster.
- Call Kubectl to validate running resources. See Kubectl.
- Execute commands in your
-
Cleanup temporary resources after testing:
- Uninstall prerequisite CRDs. See UninstallPrometheusOperManager.
- Delete the temporary directory. See Destroy.
References:
Generate Test Samples
It’s straightforward to view the content of sample projects generated by your plugin.
For example, Kubebuilder generates sample projects based on different plugins to validate the layouts.
You can also use TestContext
to generate folders of scaffolded
projects from your plugin. The commands are similar to those
mentioned in Extending CLI Features and Plugins.
Here’s a general workflow to create a sample project using the go/v4
plugin (kbc
is an instance of TestContext
):
-
To initialize a project:
By("initializing a project") err = kbc.Init( "--plugins", "go/v4", "--project-version", "3", "--domain", kbc.Domain, "--fetch-deps=false", ) ExpectWithOffset(1, err).NotTo(HaveOccurred())
-
To define API:
By("creating API definition") err = kbc.CreateAPI( "--group", kbc.Group, "--version", kbc.Version, "--kind", kbc.Kind, "--namespaced", "--resource", "--controller", "--make=false", ) ExpectWithOffset(1, err).NotTo(HaveOccurred())
-
To scaffold webhook configurations:
By("scaffolding mutating and validating webhooks") err = kbc.CreateWebhook( "--group", kbc.Group, "--version", kbc.Version, "--kind", kbc.Kind, "--defaulting", "--programmatic-validation", ) ExpectWithOffset(1, err).NotTo(HaveOccurred())