envtest

package
v2.3.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: Apache-2.0 Imports: 74 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// ManagerStartupWaitTime is the time to wait for the manager to start.
	ManagerStartupWaitTime = 5 * time.Second

	// ManagerStartupWaitInterval is the interval to wait for the manager to start.
	ManagerStartupWaitInterval = time.Millisecond
)
View Source
const (
	// ErrBodyDataConstraintError is a JSON error response body for a data constraint error.
	ErrBodyDataConstraintError = consts.ErrBodyDataConstraintError
)

Variables

View Source
var DefaultEnvTestOpts = Options{
	InstallGatewayCRDs: false,
	InstallKongCRDs:    true,
}

Functions

func AdminAPIOptFns added in v2.1.1

func AdminAPIOptFns(fns ...mocks.AdminAPIHandlerOpt) []mocks.AdminAPIHandlerOpt

AdminAPIOptFns wraps a variadic list of mocks.AdminAPIHandlerOpt and returns a slice containing all of them. The purpose of this is func is to make the call sites a bit less verbose.

NOTE: Ideally we'd refactor the RunManager() so that it'd not need to accept an empty slice of mocks.AdminAPIHandlerOpt or a call to AdminAPIOptFns() with no arguments but we can't accept 2 variadic list parameters. A slight refactor might be beneficial here.

func AssertCollectObjectExistsAndHasKonnectID added in v2.3.0

func AssertCollectObjectExistsAndHasKonnectID(
	t *testing.T,
	ctx context.Context,
	clientNamespaced client.Client,
	obj interface {
		client.Object
		GetKonnectID() string
		GetTypeName() string
	},
	konnectID string,
) func(c *assert.CollectT)

func AssertNot added in v2.3.0

func AssertNot[
	T client.Object,
](
	assert func(T) bool,
) func(objToMatch T) bool

AssertNot returns a function that negates the given assert.

func AssertsAnd added in v2.3.0

func AssertsAnd[
	T client.Object,
](
	asserts ...func(T) bool,
) func(objToMatch T) bool

AssertsAnd returns a function that performs a logical AND of the given asserts.

func ConditionProgrammedIsSetToTrueAndCPRefIsKonnectNamespacedRef added in v2.3.0

func ConditionProgrammedIsSetToTrueAndCPRefIsKonnectNamespacedRef[
	T interface {
		client.Object
		k8sutils.ConditionsAware
		GetControlPlaneRef() *commonv1alpha1.ControlPlaneRef
		GetKonnectID() string
	},
](objToMatch T, id string) func(T) bool

func ConditionsAreSetWhenReferencedControlPlaneIsMissing added in v2.3.0

func ConditionsAreSetWhenReferencedControlPlaneIsMissing[
	T interface {
		client.Object
		k8sutils.ConditionsAware
		GetControlPlaneRef() *commonv1alpha1.ControlPlaneRef
	},
](objToMatch T) func(obj T) bool

func ConditionsContainProgrammed added in v2.3.0

func ConditionsContainProgrammed(conds []metav1.Condition, status metav1.ConditionStatus) bool

func ConditionsContainProgrammedFalse added in v2.3.0

func ConditionsContainProgrammedFalse(conds []metav1.Condition) bool

func ConditionsContainProgrammedTrue added in v2.3.0

func ConditionsContainProgrammedTrue(conds []metav1.Condition) bool

func Context

Context creates a context for tests with deadline if it was provided. It also cancels the context on test cleanup.

func CreateNamespace added in v2.1.1

func CreateNamespace(ctx context.Context, t *testing.T, client ctrlclient.Client) corev1.Namespace

CreateNamespace creates namespace using the provided client and returns it.

func CreatePod added in v2.1.1

func CreatePod(ctx context.Context, t *testing.T, client ctrlclient.Client, ns string) corev1.Pod

CreatePod creates pod using the provided client and returns it.

func DumpLogsIfTestFailed

func DumpLogsIfTestFailed(t *testing.T, logs LogsObserver)

DumpLogsIfTestFailed dumps the provided logs the if the test failed.

func EventuallyAssertSDKExpectations added in v2.3.0

func EventuallyAssertSDKExpectations(
	t *testing.T,
	sdk interface {
		AssertExpectations(mock.TestingT) bool
	},
	waitTime time.Duration,
	tickTime time.Duration,
)

EventuallyAssertSDKExpectations waits for the SDK to have all its expectations met. This is useful to ensure that all expected calls to the SDK have been made up to a certain point in the test.

Thanks to using the require.EventuallyWithT and assert.CollectT, the test is not marked as failed on first assertion failure.

This function uses an adapter for assert.CollectT to allow it to be used with AssertExpectations, which requires a mock.TestingT interface.

func NameFromT

func NameFromT(t *testing.T) string

NameFromT returns a name suitable for use in Kubernetes resources for a given test. This is used e.g. when setting kong addon's name.

func NewControllerClient added in v2.1.1

func NewControllerClient(t *testing.T, scheme *runtime.Scheme, cfg *rest.Config) ctrlclient.Client

NewControllerClient returns a new controller-runtime Client for provided runtime.Scheme and rest.Config.

func ObjectHasConditionProgrammedSetToTrue added in v2.3.0

func ObjectHasConditionProgrammedSetToTrue[
	T k8sutils.ConditionsAware,
]() func(T) bool

ObjectHasConditionProgrammedSetToTrue returns a function that checks if the given object has the "Programmed" condition set to true.

func ObjectHasFinalizer added in v2.3.0

func ObjectHasFinalizer[
	T client.Object,
](finalizer string) func(obj T) bool

ObjectHasFinalizer returns a function that checks if the given object has the specified finalizer.

func ObjectMatchesKonnectID added in v2.3.0

func ObjectMatchesKonnectID[
	T interface {
		GetKonnectID() string
	},
](id string) func(T) bool

ObjectMatchesKonnectID returns a function that checks if an object's Konnect ID matches the given ID.

func ObjectMatchesName added in v2.3.0

func ObjectMatchesName[
	T client.Object,
](objToMatch T) func(T) bool

ObjectMatchesName returns a function that checks if the given object has the same name as the provided object to match.

func ProgrammedCondition added in v2.3.0

func ProgrammedCondition(generation int64) metav1.Condition

func Scheme added in v2.1.1

func Scheme(t *testing.T, opts ...SchemeOption) *k8sruntime.Scheme

Scheme returns a new scheme with the default Kubernetes types registered. It accepts optional SchemeOptions to register additional types.

func Setup

func Setup(t *testing.T, ctx context.Context, scheme *k8sruntime.Scheme, optModifiers ...OptionModifier) (*rest.Config, *corev1.Namespace)

Setup sets up a test k8s API server environment and returned the configuration.

func SetupManager added in v2.1.1

func SetupManager(
	ctx context.Context,
	t *testing.T,
	mgrID manager.ID,
	envcfg *rest.Config,
	adminAPIOpts []mocks.AdminAPIHandlerOpt,
	modifyCfgFns ...managercfg.Opt,
) *manager.Manager

func SetupWatch added in v2.3.0

func SetupWatch[
	TList interface {
		GetItems() []T
	},
	TObjectList interface {
		*TList
		client.ObjectList
	},
	T any,
	TPtr interface {
		*T
		client.Object
	},
](
	t *testing.T,
	ctx context.Context,
	cl client.WithWatch,
	opts ...client.ListOption,
) watch[TPtr]

SetupWatch sets up a watch.Interface for the provided client.ObjectList. It is useful if an action needs to be performed between setting up the watch and starting to watch for actual events on that watch. It returns the watch.Interface and registers its cleanup using t.Cleanup.

func StartAdminAPIServerMock added in v2.1.1

func StartAdminAPIServerMock(t *testing.T, opts ...mocks.AdminAPIHandlerOpt) *httptest.Server

StartAdminAPIServerMock starts a mock Kong Admin API server. It accepts a variadic list of options which can configure the test server.

Server's .Close() method will be called during test's cleanup.

func StartReconciler added in v2.1.1

func StartReconciler(
	ctx context.Context, t *testing.T, scheme *runtime.Scheme, cfg *rest.Config, r IngressReconciler, opts ...func(*manager.Options),
)

StartReconciler creates a controller manager and starts the provided reconciler as its runnable. It also adds a t.Cleanup which waits for the manager to exit so that the test can be self contained and logs from different tests' managers don't mix up.

func StartReconcilers

func StartReconcilers(
	ctx context.Context,
	t *testing.T,
	mgr manager.Manager,
	logs LogsObserver,
	reconcilers ...Reconciler,
)

StartReconcilers creates a controller manager and starts the provided reconciler as its runnable. It also adds a t.Cleanup which waits for the manager to exit so that the test can be self contained and logs from different tests' managers don't mix up.

func UpdateKongConsumerGroupStatusWithKonnectID added in v2.3.0

func UpdateKongConsumerGroupStatusWithKonnectID(
	t *testing.T,
	ctx context.Context,
	cl client.Client,
	obj *configurationv1beta1.KongConsumerGroup,
	id string,
	cpID string,
)

func UpdateKongConsumerStatusWithKonnectID added in v2.3.0

func UpdateKongConsumerStatusWithKonnectID(
	t *testing.T,
	ctx context.Context,
	cl client.Client,
	obj *configurationv1.KongConsumer,
	id string,
	cpID string,
)

func UpdateKongKeySetStatusWithProgrammed added in v2.3.0

func UpdateKongKeySetStatusWithProgrammed(
	t *testing.T,
	ctx context.Context,
	cl client.Client,
	obj *configurationv1alpha1.KongKeySet,
	id, cpID string,
)

func UpdateKongRouteStatusWithProgrammed added in v2.3.0

func UpdateKongRouteStatusWithProgrammed(
	t *testing.T,
	ctx context.Context,
	cl client.Client,
	obj *configurationv1alpha1.KongRoute,
	id string,
	cpID string,
	serviceID string,
)

func UpdateKongServiceStatusWithProgrammed added in v2.3.0

func UpdateKongServiceStatusWithProgrammed(
	t *testing.T,
	ctx context.Context,
	cl client.Client,
	obj *configurationv1alpha1.KongService,
	id string,
	cpID string,
)

func UpdateKongUpstreamStatusWithProgrammed added in v2.3.0

func UpdateKongUpstreamStatusWithProgrammed(
	t *testing.T,
	ctx context.Context,
	cl client.Client,
	obj *configurationv1alpha1.KongUpstream,
	id string,
	cpID string,
)

func UpdateKonnectEventGatewayStatusWithProgrammed added in v2.3.0

func UpdateKonnectEventGatewayStatusWithProgrammed(
	t *testing.T,
	ctx context.Context,
	cl client.Client,
	obj *konnectv1alpha1.KonnectEventGateway,
	id string,
)

func WaitForManagerStart added in v2.1.1

func WaitForManagerStart(t *testing.T, logsObserver LogsObserver)

WaitForManagerStart waits for the manager to start. The indication of the manager starting is the "Starting manager" log entry that is emitted just before the manager starts. Note: We cannot rely here on the manager's readiness probe because it returns 200 OK as soon as it starts listening which happens before the manager actually starts.

func WatchFor added in v2.3.0

func WatchFor[
	T client.Object,
](
	t *testing.T,
	ctx context.Context,
	w watch[T],
	eventType apiwatch.EventType,
	predicate func(T) bool,
	failMsg string,
) T

WatchFor watches for an event of type eventType using the provided watch.Interface. It is a wrapper of helpers.WatchFor which uses the type safe `watch` and a fixed timeout.

func WithCacheSyncTimeout added in v2.1.1

func WithCacheSyncTimeout(d time.Duration) func(cfg *managercfg.Config)

func WithDefaultEnvTestsConfig added in v2.1.1

func WithDefaultEnvTestsConfig(envcfg *rest.Config) func(cfg *managercfg.Config)

WithDefaultEnvTestsConfig modifies a managercfg.Config for use in envtests.

func WithDiagnosticsServer added in v2.1.1

func WithDiagnosticsServer(port int) func(cfg *managercfg.Config)

func WithDiagnosticsWithoutServer added in v2.1.1

func WithDiagnosticsWithoutServer() func(cfg *managercfg.Config)

func WithFeatureGate added in v2.1.1

func WithFeatureGate(name string, enabled bool) func(cfg *managercfg.Config)

func WithGatewayAPI added in v2.1.1

func WithGatewayAPI(t *testing.T, s *k8sruntime.Scheme)

WithGatewayAPI registers the Gateway API types with the scheme.

func WithGatewayAPIControllers added in v2.1.1

func WithGatewayAPIControllers() func(cfg *managercfg.Config)

func WithGatewayFeatureEnabled added in v2.1.1

func WithGatewayFeatureEnabled(cfg *managercfg.Config)

func WithGatewayToReconcile added in v2.1.1

func WithGatewayToReconcile(gatewayNN string) func(cfg *managercfg.Config)

func WithHealthProbePort added in v2.1.1

func WithHealthProbePort(port int) func(cfg *managercfg.Config)

func WithIngressClass added in v2.1.1

func WithIngressClass(name string) func(cfg *managercfg.Config)

func WithInitCacheSyncDuration added in v2.1.1

func WithInitCacheSyncDuration(d time.Duration) func(cfg *managercfg.Config)

func WithKong added in v2.1.1

func WithKong(t *testing.T, s *k8sruntime.Scheme)

WithKong registers the Kong types with the scheme.

func WithKongAdminURLs added in v2.1.1

func WithKongAdminURLs(urls ...string) func(cfg *managercfg.Config)

func WithKongServiceFacadeFeatureEnabled added in v2.1.1

func WithKongServiceFacadeFeatureEnabled() func(cfg *managercfg.Config)

func WithKongUpstreamPolicyEnabled added in v2.1.1

func WithKongUpstreamPolicyEnabled() func(cfg *managercfg.Config)

func WithMetricsAddr added in v2.1.1

func WithMetricsAddr(addr string) func(cfg *managercfg.Config)

func WithProfiling added in v2.1.1

func WithProfiling() func(cfg *managercfg.Config)

func WithProxySyncInterval added in v2.1.1

func WithProxySyncInterval(period time.Duration) func(cfg *managercfg.Config)

func WithPublishService added in v2.1.1

func WithPublishService(namespace string) func(cfg *managercfg.Config)

func WithPublishStatusAddress added in v2.1.1

func WithPublishStatusAddress(addresses []string, udps []string) func(cfg *managercfg.Config)

func WithTelemetry added in v2.1.1

func WithTelemetry(splunkEndpoint string, telemetryPeriod time.Duration) managercfg.Opt

func WithUpdateStatus added in v2.1.1

func WithUpdateStatus() func(cfg *managercfg.Config)

func WithWatchNamespace added in v2.1.1

func WithWatchNamespace(ns string) func(*manager.Options)

Types

type IngressReconciler added in v2.1.1

type IngressReconciler interface {
	SetupWithManager(ctrl.Manager) error
	SetLogger(logr.Logger)
}

IngressReconciler represents a reconciler that requires a logger.

type LogsObserver

type LogsObserver interface {
	// All returns all the logs that have been observed so far.
	All() []observer.LoggedEntry
}

LogsObserver is an interface for observing logs.

func CreateTestLogger

func CreateTestLogger(ctx context.Context) (context.Context, logr.Logger, LogsObserver)

CreateTestLogger creates a logger for use in tests. It returns the logger - which is also added to the context - and the observer which can be used to dump logs if the test fails.

func NewManager

func NewManager(t *testing.T, ctx context.Context, cfg *rest.Config, s *runtime.Scheme, opts ...ManagerOption) (manager.Manager, LogsObserver)

NewManager returns a manager and a logs observer. The logs observer can be used to dump logs if the test fails. The returned manager can be used with StartReconcilers() to start a list of provided reconcilers with the manager.

func RunManager added in v2.1.1

func RunManager(
	ctx context.Context,
	t *testing.T,
	envcfg *rest.Config,
	adminAPIOpts []mocks.AdminAPIHandlerOpt,
	modifyCfgFns ...managercfg.Opt,
) LogsObserver

RunManager runs the manager in a goroutine. It's possible to modify the manager's configuration by passing in modifyCfgFns. The manager is stopped when the context is canceled.

type ManagerOption

type ManagerOption func(manager.Manager) error

ManagerOption is a function that can be used to configure the manager.

type MockTestingTAdapter

type MockTestingTAdapter struct {
	*assert.CollectT
	// contains filtered or unexported fields
}

MockTestingTAdapter allows to use assert.CollectT where a mock.TestingT is required. This is useful when in functions like AssertExpectations.

Ref: https://pkg.go.dev/github.com/stretchr/testify/mock#TestingT

func (MockTestingTAdapter) Logf

func (a MockTestingTAdapter) Logf(format string, args ...any)

Logf is a method that allows to log messages in the context of a test.

type OptionModifier added in v2.1.1

type OptionModifier func(Options) Options

func WithAdditionalCRDPaths added in v2.2.0

func WithAdditionalCRDPaths(paths []string) OptionModifier

func WithInstallGatewayCRDs added in v2.1.1

func WithInstallGatewayCRDs(install bool) OptionModifier

func WithInstallKongCRDs added in v2.1.1

func WithInstallKongCRDs(install bool) OptionModifier

type Options added in v2.1.1

type Options struct {
	InstallGatewayCRDs bool
	InstallKongCRDs    bool
	AdditionalCRDPaths []string
}

type Reconciler

type Reconciler interface {
	SetupWithManager(context.Context, ctrl.Manager) error
}

Reconciler represents a reconciler.

type SchemeOption added in v2.1.1

type SchemeOption func(t *testing.T, s *k8sruntime.Scheme)

type TelemetryServer added in v2.1.1

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

TelemetryServer represents a server that listens for telemetry data over a TLS connection.

func NewTelemetryServer added in v2.1.1

func NewTelemetryServer(t *testing.T) *TelemetryServer

NewTelemetryServer creates and configures a new TelemetryServer instance. It generates a TLS listener using a self-signed certificate.

func (*TelemetryServer) Endpoint added in v2.1.1

func (ts *TelemetryServer) Endpoint() string

Endpoint returns the address of the telemetry server.

func (*TelemetryServer) ReportChan added in v2.1.1

func (ts *TelemetryServer) ReportChan() <-chan []byte

ReportChan provides access to the telemetry report channel.

func (*TelemetryServer) Start added in v2.1.1

func (ts *TelemetryServer) Start(ctx context.Context, t *testing.T)

Start begins the telemetry server, accepting incoming connections and processing telemetry data. It does not block.

func (*TelemetryServer) Stop added in v2.1.1

func (ts *TelemetryServer) Stop(t *testing.T)

Stop shuts down the telemetry server, closing the listener and canceling the context.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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