envtest

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Package envtest provides a test environment for testing code against a kcp control plane.

Index

Constants

This section is empty.

Variables

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 Eventually

func Eventually(t TestingT, condition func() (success bool, reason string), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{})

Eventually asserts that given condition will be met in waitFor time, periodically checking target function each tick. In addition to require.Eventually, this function t.Logs the reason string value returned by the condition function (eventually after 20% of the wait time) to aid in debugging.

func EventuallyCondition

func EventuallyCondition(t TestingT, getter func() (conditions.Getter, error), evaluator *ConditionEvaluator, msgAndArgs ...interface{})

EventuallyCondition asserts that the object returned by getter() eventually has a condition that matches the evaluator.

func EventuallyReady

func EventuallyReady(t TestingT, getter func() (conditions.Getter, error), msgAndArgs ...interface{})

EventuallyReady asserts that the object returned by getter() eventually has a ready condition.

func NewInitializingWorkspaceFixture added in v0.2.0

func NewInitializingWorkspaceFixture(t TestingT, clusterClient kcpclient.ClusterClient, parent logicalcluster.Path, options ...WorkspaceOption) (*tenancyv1alpha1.Workspace, logicalcluster.Path)

NewInitializingWorkspaceFixture creates a new workspace under the given parent using the given client, and waits for it to be stuck in the initializing phase.

func NewWorkspaceFixture

func NewWorkspaceFixture(t TestingT, clusterClient kcpclient.ClusterClient, parent logicalcluster.Path, options ...WorkspaceOption) (*tenancyv1alpha1.Workspace, logicalcluster.Path)

NewWorkspaceFixture creates a new workspace under the given parent using the given client.

func WorkspaceShard

func WorkspaceShard(ctx context.Context, kcpClient kcpclient.ClusterClient, ws *tenancyv1alpha1.Workspace) (*corev1alpha1.Shard, error)

WorkspaceShard returns the shard that a workspace is scheduled on.

func WorkspaceShardOrDie

func WorkspaceShardOrDie(t TestingT, kcpClient kcpclient.ClusterClient, ws *tenancyv1alpha1.Workspace) *corev1alpha1.Shard

WorkspaceShardOrDie returns the shard that a workspace is scheduled on, or fails the test on error.

Types

type Arg

type Arg = process.Arg

Arg is a single flag with one or more values.

type Arguments

type Arguments = process.Arguments

Arguments allows configuring a process's flags.

type AuthenticatedUser

type AuthenticatedUser = controlplane.AuthenticatedUser

AuthenticatedUser represets a Kubernetes user that's been provisioned.

type Authn

type Authn = controlplane.Authn

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

type ConditionEvaluator

type ConditionEvaluator struct {
	// contains filtered or unexported fields
}

ConditionEvaluator is a helper for evaluating conditions.

func Is

Is matches if the given condition type is of the given value.

func IsNot

IsNot matches if the given condition type is not of the given value.

func (*ConditionEvaluator) WithReason

func (c *ConditionEvaluator) WithReason(reason string) *ConditionEvaluator

WithReason matches if the given condition type has the given reason.

type Environment

type Environment struct {
	// Kcp is the Kcp instance.
	Kcp controlplane.Kcp

	// 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

	// BinaryAssetsDirectory is the path where the binaries required for the envtest are
	// located in the local environment. This field can be overridden by setting TEST_KCP_ASSETS.
	BinaryAssetsDirectory string

	// UseExistingCluster indicates that this environments should use an
	// existing kubeconfig, instead of trying to stand up a new kcp.
	// It defaults to the USE_EXISTING_KCP environment variable if unspecified.
	UseExistingKcp *bool

	// ExistingKcpContext indicates that when UseExistingKcp is set to true,
	// a specific context should be loaded from a kubeconfig instead of the
	// current one. It defaults to the EXISTING_KCP_CONTEXT environment variable
	// if unspecified.
	ExistingKcpContext string

	// KcpStartTimeout is the maximum duration each kcp component
	// may take to start. It defaults to the TEST_KCP_START_TIMEOUT
	// environment variable or 20 seconds if unspecified.
	KcpStartTimeout time.Duration

	// KcpStopTimeout is the maximum duration each kcp component
	// may take to stop. It defaults to the TEST_KCP_STOP_TIMEOUT
	// environment variable or 20 seconds if unspecified.
	KcpStopTimeout time.Duration

	// AttachKcpOutput indicates if kcp output will be attached to os.Stdout and os.Stderr.
	// Enable this to get more visibility of the testing kcp.
	// It respects the the TEST_ATTACH_KCP_OUTPUT environment variable.
	AttachKcpOutput bool
}

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

func (*Environment) AddUser

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 Kcp.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 Kcp

type Kcp = controlplane.Kcp

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

type ListenAddr

type ListenAddr = process.ListenAddr

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

type SecureServing

type SecureServing = controlplane.SecureServing

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

type Shard

type Shard = controlplane.Shard

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

type Sharded added in v0.9.0

type Sharded struct {
	// NumberOfShards is passed to -number-of-shards. Defaults to
	// $KCP_NUMBER_OF_SHARDS if set, otherwise 2.
	NumberOfShards int

	// WorkDir is passed to -work-dir-path. Defaults to $KCP_TEST_WORK_DIR
	// if set, otherwise the current working directory.
	WorkDir string

	// ExtraArgs are appended to the sharded-test-server invocation. Use for
	// --proxy-*, --shard-*, --quiet, etc.
	ExtraArgs []string

	// StartTimeout is how long Start waits for the readiness sentinel.
	// Defaults to $TEST_KCP_START_TIMEOUT or 2m.
	StartTimeout time.Duration

	// StopTimeout is how long Stop waits for the subprocess after SIGTERM
	// before sending SIGKILL. Defaults to $TEST_KCP_STOP_TIMEOUT or 20s.
	StopTimeout time.Duration
	// contains filtered or unexported fields
}

Sharded runs kcp's sharded-test-server as a subprocess. It is the recommended way to drive multicluster-provider e2e tests against a realistic multi-shard kcp topology.

Set the desired fields on a zero value, call Start with a context, and retrieve the admin rest.Config via Config. Use Stop (or t.Cleanup) to terminate the subprocess.

To run the following binaries must be available either in PATH or set in the respective environment variables:

sharded-test-server KCP_ASSET_SHARDED_TEST_SERVER
kcp                 KCP_ASSET_KCP
kcp-front-proxy     KCP_ASSET_KCP_FRONT_PROXY
cache-server        KCP_ASSET_CACHE_SERVER

func (*Sharded) Config added in v0.9.0

func (s *Sharded) Config() *rest.Config

Config returns the admin rest.Config for the front-proxy, or nil if Start has not succeeded. The same pointer is returned on each call; copy it with rest.CopyConfig before mutating.

func (*Sharded) ShardNames added in v0.9.0

func (s *Sharded) ShardNames() []string

ShardNames returns the names of the configured shards.

func (*Sharded) Start added in v0.9.0

func (s *Sharded) Start(ctx context.Context) error

Start launches sharded-test-server and blocks until it is ready or ctx is cancelled. Start must be called at most once per Sharded instance.

func (*Sharded) Stop added in v0.9.0

func (s *Sharded) Stop() error

Stop terminates the subprocess (SIGTERM, then SIGKILL after StopTimeout) and closes the subprocess log file. Stop is idempotent and not safe for concurrent calls.

type TestingT

type TestingT interface {
	Cleanup(func())
	Error(args ...any)
	Errorf(format string, args ...any)
	FailNow()
	Failed() bool
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Helper()
	Log(args ...any)
	Logf(format string, args ...any)
	Name() string
	TempDir() string
}

TestingT is implemented by *testing.T and potentially other test frameworks.

type User

type User = controlplane.User

User represents a Kubernetes user to provision for auth purposes.

type WorkspaceOption

type WorkspaceOption func(ws *tenancyv1alpha1.Workspace)

WorkspaceOption is an option for creating a workspace.

func WithLocation

WithLocation sets the location of the workspace.

func WithName

func WithName(s string, formatArgs ...interface{}) WorkspaceOption

WithName sets the name of the workspace.

func WithNamePrefix

func WithNamePrefix(prefix string) WorkspaceOption

WithNamePrefix make the workspace be named with the given prefix plus "-".

func WithRootShard

func WithRootShard() WorkspaceOption

WithRootShard schedules the workspace on the root shard.

func WithShard

func WithShard(name string) WorkspaceOption

WithShard schedules the workspace on the given shard.

func WithSpreadAcrossShards added in v0.9.0

func WithSpreadAcrossShards(t TestingT, shardNames []string) WorkspaceOption

WithSpreadAcrossShards ensures that workspaces are spread across the available shards unless the workspace has an explicit location set. Taken from https://github.com/kcp-dev/kcp/blob/32d5f90a15e1187d92cb535dd0d3f9529696ad26/staging/src/github.com/kcp-dev/sdk/testing/workspaces.go#L114-L145

func WithType

WithType sets the type of the workspace.

Directories

Path Synopsis
internal
flock
Package flock is copied from k8s.io/kubernetes/pkg/util/flock to avoid importing k8s.io/kubernetes as a dependency.
Package flock is copied from k8s.io/kubernetes/pkg/util/flock to avoid importing k8s.io/kubernetes as a dependency.

Jump to

Keyboard shortcuts

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