envtest

package
v0.21.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 20, 2025 License: Apache-2.0 Imports: 48 Imported by: 286

Documentation

Overview

Package envtest provides libraries for integration testing by starting a local control plane

Control plane binaries (etcd and kube-apiserver) are loaded by default from /usr/local/kubebuilder/bin. This can be overridden by setting the KUBEBUILDER_ASSETS environment variable, or by directly creating a ControlPlane for the Environment to use.

Environment can also be configured to work with an existing cluster, and simply load CRDs and provide client configuration.

Index

Constants

View Source
const (
	StartTimeout = 60
	StopTimeout  = 60
)

It's possible to override some defaults, by setting the following environment variables: * USE_EXISTING_CLUSTER (boolean): if set to true, envtest will use an existing cluster * TEST_ASSET_KUBE_APISERVER (string): path to the api-server binary to use * TEST_ASSET_ETCD (string): path to the etcd binary to use * TEST_ASSET_KUBECTL (string): path to the kubectl binary to use * KUBEBUILDER_ASSETS (string): directory containing the binaries to use (api-server, etcd and kubectl). Defaults to /usr/local/kubebuilder/bin. * KUBEBUILDER_CONTROLPLANE_START_TIMEOUT (string supported by time.ParseDuration): timeout for test control plane to start. Defaults to 20s. * KUBEBUILDER_CONTROLPLANE_STOP_TIMEOUT (string supported by time.ParseDuration): timeout for test control plane to start. Defaults to 20s. * KUBEBUILDER_ATTACH_CONTROL_PLANE_OUTPUT (boolean): if set to true, the control plane's stdout and stderr are attached to os.Stdout and os.Stderr

Variables

View Source
var DefaultBinaryAssetsIndexURL = "https://raw.githubusercontent.com/kubernetes-sigs/controller-tools/HEAD/envtest-releases.yaml"

DefaultBinaryAssetsIndexURL is the default index used in HTTPClient.

View Source
var DefaultKubeAPIServerFlags = controlplane.APIServerDefaultArgs //nolint:staticcheck

DefaultKubeAPIServerFlags exposes the default args for the APIServer so that you can use those to append your own additional arguments.

Deprecated: use APIServer.Configure() instead.

View Source
var (
	// EmptyArguments constructs a new set of flags with nothing set.
	//
	// This is mostly useful for testing helper methods -- you'll want to call
	// Configure on the APIServer (or etcd) to configure their arguments.
	EmptyArguments = process.EmptyArguments
)

Functions

func CreateCRDs

func CreateCRDs(config *rest.Config, crds []*apiextensionsv1.CustomResourceDefinition) error

CreateCRDs creates the CRDs.

func InstallCRDs

func InstallCRDs(config *rest.Config, options CRDInstallOptions) ([]*apiextensionsv1.CustomResourceDefinition, error)

InstallCRDs installs a collection of CRDs into a cluster by reading the crd yaml files from a directory.

func ReadCRDFiles added in v0.20.3

func ReadCRDFiles(options *CRDInstallOptions) error

ReadCRDFiles reads the directories of CRDs in options.Paths and adds the CRD structs to options.CRDs.

func SetupEnvtestDefaultBinaryAssetsDirectory added in v0.21.0

func SetupEnvtestDefaultBinaryAssetsDirectory() (string, error)

SetupEnvtestDefaultBinaryAssetsDirectory returns the default location that setup-envtest uses to store envtest binaries. Setting BinaryAssetsDirectory to this directory allows sharing envtest binaries with setup-envtest.

The directory is dependent on operating system:

- Windows: %LocalAppData%\kubebuilder-envtest - OSX: ~/Library/Application Support/io.kubebuilder.envtest - Others: ${XDG_DATA_HOME:-~/.local/share}/kubebuilder-envtest

Otherwise, it errors out. Note that these paths must not be relied upon manually.

func UninstallCRDs added in v0.5.0

func UninstallCRDs(config *rest.Config, options CRDInstallOptions) error

UninstallCRDs uninstalls a collection of CRDs by reading the crd yaml files from a directory.

func WaitForCRDs

func WaitForCRDs(config *rest.Config, crds []*apiextensionsv1.CustomResourceDefinition, options CRDInstallOptions) error

WaitForCRDs waits for the CRDs to appear in discovery.

func WaitForWebhooks added in v0.5.1

func WaitForWebhooks(config *rest.Config,
	mutatingWebhooks []*admissionv1.MutatingWebhookConfiguration,
	validatingWebhooks []*admissionv1.ValidatingWebhookConfiguration,
	options WebhookInstallOptions,
) error

WaitForWebhooks waits for the Webhooks to be available through API server.

Types

type APIServer added in v0.5.7

type APIServer = controlplane.APIServer

APIServer is the re-exported APIServer from the internal testing package.

type Arg added in v0.9.0

type Arg = process.Arg

Arg is a single flag with one or more values.

type Arguments added in v0.9.0

type Arguments = process.Arguments

Arguments allows configuring a process's flags.

type AuthenticatedUser added in v0.9.0

type AuthenticatedUser = controlplane.AuthenticatedUser

AuthenticatedUser represets a Kubernetes user that's been provisioned.

type Authn added in v0.9.0

type Authn = controlplane.Authn

Authn is an authentication method that can be used with the control plane to provision users.

type CRDInstallOptions

type CRDInstallOptions struct {
	// Scheme is used to determine if conversion webhooks should be enabled
	// for a particular CRD / object.
	//
	// Conversion webhooks are going to be enabled if an object in the scheme
	// implements Hub and Spoke conversions.
	//
	// If nil, scheme.Scheme is used.
	Scheme *runtime.Scheme

	// Paths is a list of paths to the directories or files containing CRDs
	Paths []string

	// CRDs is a list of CRDs to install
	CRDs []*apiextensionsv1.CustomResourceDefinition

	// ErrorIfPathMissing will cause an error if a Path does not exist
	ErrorIfPathMissing bool

	// MaxTime is the max time to wait
	MaxTime time.Duration

	// PollInterval is the interval to check
	PollInterval time.Duration

	// CleanUpAfterUse will cause the CRDs listed for installation to be
	// uninstalled when terminating the test environment.
	// Defaults to false.
	CleanUpAfterUse bool

	// WebhookOptions contains the conversion webhook information to install
	// on the CRDs. This field is usually inherited by the EnvTest options.
	//
	// If you're passing this field manually, you need to make sure that
	// the CA information and host port is filled in properly.
	WebhookOptions WebhookInstallOptions
}

CRDInstallOptions are the options for installing CRDs.

type ControlPlane added in v0.5.7

type ControlPlane = controlplane.ControlPlane

ControlPlane is the re-exported ControlPlane type from the internal testing package.

type Environment

type Environment struct {
	// ControlPlane is the ControlPlane including the apiserver and etcd
	ControlPlane controlplane.ControlPlane

	// Scheme is used to determine if conversion webhooks should be enabled
	// for a particular CRD / object.
	//
	// Conversion webhooks are going to be enabled if an object in the scheme
	// implements Hub and Spoke conversions.
	//
	// If nil, scheme.Scheme is used.
	Scheme *runtime.Scheme

	// Config can be used to talk to the apiserver.  It's automatically
	// populated if not set using the standard controller-runtime config
	// loading.
	Config *rest.Config

	// KubeConfig provides []byte of a kubeconfig file to talk to the apiserver
	// It's automatically populated if not set based on the `Config`
	KubeConfig []byte

	// CRDInstallOptions are the options for installing CRDs.
	CRDInstallOptions CRDInstallOptions

	// WebhookInstallOptions are the options for installing webhooks.
	WebhookInstallOptions WebhookInstallOptions

	// ErrorIfCRDPathMissing provides an interface for the underlying
	// CRDInstallOptions.ErrorIfPathMissing. It prevents silent failures
	// for missing CRD paths.
	ErrorIfCRDPathMissing bool

	// CRDs is a list of CRDs to install.
	// If both this field and CRDs field in CRDInstallOptions are specified, the
	// values are merged.
	CRDs []*apiextensionsv1.CustomResourceDefinition

	// CRDDirectoryPaths is a list of paths containing CRD yaml or json configs.
	// If both this field and Paths field in CRDInstallOptions are specified, the
	// values are merged.
	CRDDirectoryPaths []string

	// DownloadBinaryAssets indicates that the envtest binaries should be downloaded.
	// If BinaryAssetsDirectory is also set, it is used to store the downloaded binaries,
	// otherwise a tmp directory is created.
	DownloadBinaryAssets bool

	// DownloadBinaryAssetsVersion is the version of envtest binaries to download.
	// Defaults to the latest stable version (i.e. excluding alpha / beta / RC versions).
	DownloadBinaryAssetsVersion string

	// DownloadBinaryAssetsIndexURL is the index used to discover envtest binaries to download.
	// Defaults to https://raw.githubusercontent.com/kubernetes-sigs/controller-tools/HEAD/envtest-releases.yaml.
	DownloadBinaryAssetsIndexURL string

	// BinaryAssetsDirectory is the path where the binaries required for the envtest are
	// located in the local environment. This field can be overridden by setting KUBEBUILDER_ASSETS.
	// Set this field to SetupEnvtestDefaultBinaryAssetsDirectory() to share binaries with setup-envtest.
	BinaryAssetsDirectory string

	// UseExistingCluster indicates that this environments should use an
	// existing kubeconfig, instead of trying to stand up a new control plane.
	// This is useful in cases that need aggregated API servers and the like.
	UseExistingCluster *bool

	// ControlPlaneStartTimeout is the maximum duration each controlplane component
	// may take to start. It defaults to the KUBEBUILDER_CONTROLPLANE_START_TIMEOUT
	// environment variable or 20 seconds if unspecified
	ControlPlaneStartTimeout time.Duration

	// ControlPlaneStopTimeout is the maximum duration each controlplane component
	// may take to stop. It defaults to the KUBEBUILDER_CONTROLPLANE_STOP_TIMEOUT
	// environment variable or 20 seconds if unspecified
	ControlPlaneStopTimeout time.Duration

	// AttachControlPlaneOutput indicates if control plane output will be attached to os.Stdout and os.Stderr.
	// Enable this to get more visibility of the testing control plane.
	// It respect KUBEBUILDER_ATTACH_CONTROL_PLANE_OUTPUT environment variable.
	AttachControlPlaneOutput bool
}

Environment creates a Kubernetes test environment that will start / stop the Kubernetes control plane and install extension APIs.

func (*Environment) AddUser added in v0.9.0

func (te *Environment) AddUser(user User, baseConfig *rest.Config) (*AuthenticatedUser, error)

AddUser provisions a new user for connecting to this Environment. The user will have the specified name & belong to the specified groups.

If you specify a "base" config, the returned REST Config will contain those settings as well as any required by the authentication method. You can use this to easily specify options like QPS.

This is effectively a convinience alias for ControlPlane.AddUser -- see that for more low-level details.

func (*Environment) Start

func (te *Environment) Start() (*rest.Config, error)

Start starts a local Kubernetes server and updates te.ApiserverPort with the port it is listening on.

func (*Environment) Stop

func (te *Environment) Stop() error

Stop stops a running server. Previously installed CRDs, as listed in CRDInstallOptions.CRDs, will be uninstalled if CRDInstallOptions.CleanUpAfterUse are set to true.

type Etcd added in v0.5.7

type Etcd = controlplane.Etcd

Etcd is the re-exported Etcd from the internal testing package.

type ListenAddr added in v0.9.0

type ListenAddr = process.ListenAddr

ListenAddr indicates the address and port that the API server should listen on.

type SecureServing added in v0.9.0

type SecureServing = controlplane.SecureServing

SecureServing contains details describing how the API server should serve its secure endpoint.

type User added in v0.9.0

type User = controlplane.User

User represents a Kubernetes user to provision for auth purposes.

type WebhookInstallOptions added in v0.5.1

type WebhookInstallOptions struct {
	// Paths is a list of paths to the directories or files containing the mutating or validating webhooks yaml or json configs.
	Paths []string

	// MutatingWebhooks is a list of MutatingWebhookConfigurations to install
	MutatingWebhooks []*admissionv1.MutatingWebhookConfiguration

	// ValidatingWebhooks is a list of ValidatingWebhookConfigurations to install
	ValidatingWebhooks []*admissionv1.ValidatingWebhookConfiguration

	// IgnoreSchemeConvertible, will modify any CRD conversion webhook to use the local serving host and port,
	// bypassing the need to have the types registered in the Scheme. This is useful for testing CRD conversion webhooks
	// with unregistered or unstructured types.
	IgnoreSchemeConvertible bool

	// IgnoreErrorIfPathMissing will ignore an error if a DirectoryPath does not exist when set to true
	IgnoreErrorIfPathMissing bool

	// LocalServingHost is the host for serving webhooks on.
	// it will be automatically populated
	LocalServingHost string

	// LocalServingPort is the allocated port for serving webhooks on.
	// it will be automatically populated by a random available local port
	LocalServingPort int

	// LocalServingCertDir is the allocated directory for serving certificates.
	// it will be automatically populated by the local temp dir
	LocalServingCertDir string

	// CAData is the CA that can be used to trust the serving certificates in LocalServingCertDir.
	LocalServingCAData []byte

	// LocalServingHostExternalName is the hostname to use to reach the webhook server.
	LocalServingHostExternalName string

	// MaxTime is the max time to wait
	MaxTime time.Duration

	// PollInterval is the interval to check
	PollInterval time.Duration
}

WebhookInstallOptions are the options for installing mutating or validating webhooks.

func (*WebhookInstallOptions) Cleanup added in v0.5.1

func (o *WebhookInstallOptions) Cleanup() error

Cleanup cleans up cert directories.

func (*WebhookInstallOptions) Install added in v0.5.1

func (o *WebhookInstallOptions) Install(config *rest.Config) error

Install installs specified webhooks to the API server.

func (*WebhookInstallOptions) ModifyWebhookDefinitions added in v0.5.1

func (o *WebhookInstallOptions) ModifyWebhookDefinitions() error

ModifyWebhookDefinitions modifies webhook definitions by: - applying CABundle based on the provided tinyca - if webhook client config uses service spec, it's removed and replaced with direct url.

func (*WebhookInstallOptions) PrepWithoutInstalling added in v0.6.4

func (o *WebhookInstallOptions) PrepWithoutInstalling() error

PrepWithoutInstalling does the setup parts of Install (populating host-port, setting up CAs, etc), without actually truing to do anything with webhook definitions. This is largely useful for internal testing of controller-runtime, where we need a random host-port & caData for webhook tests, but may be useful in similar scenarios.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
OSZAR »