helpers

package
v2.2.2 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// DefaultGatewayName is the default name for the Gateways created during tests.
	DefaultGatewayName = "kong"
)

Variables

This section is empty.

Functions

func CountHTTPGetResponses added in v2.2.0

func CountHTTPGetResponses(
	t *testing.T,
	proxyURL *url.URL,
	cfg CountHTTPResponsesConfig,
	matchers ...ResponseMatcher,
) (matchedResponseCounter map[string]int)

func CreateIngressClass added in v2.2.0

func CreateIngressClass(ctx context.Context, ingressClassName string, client *kubernetes.Clientset) error

func DefaultHTTPClient added in v2.2.0

func DefaultHTTPClient(opts ...HTTPClientOption) *http.Client

DefaultHTTPClient returns a client that should be used by default in tests. All defaults that should be propagated to tests for use should be changed in here.

func DeployGateway added in v2.2.0

func DeployGateway(ctx context.Context, client *gatewayclient.Clientset, namespace, gatewayClassName string, opts ...func(*gatewayapi.Gateway)) (*gatewayapi.Gateway, error)

DeployGateway creates a default gateway, accepts a variadic set of options, and finally deploys it on the Kubernetes cluster by means of the gateway client given as arg.

func DeployGatewayClass added in v2.2.0

func DeployGatewayClass(ctx context.Context, client *gatewayclient.Clientset, gatewayClassName string, opts ...func(*gatewayapi.GatewayClass)) (*gatewayapi.GatewayClass, error)

DeployGatewayClass creates a default gatewayClass, accepts a variadic set of options, and finally deploys it on the Kubernetes cluster by means of the gateway client given as arg.

func DistributionOfMapValues added in v2.2.0

func DistributionOfMapValues(counter map[string]int) map[string]float64

DistributionOfMapValues returns a map of the values in the given counter map and the relative frequency of each value.

func DumpDiagnosticsIfFailed added in v2.2.0

func DumpDiagnosticsIfFailed(ctx context.Context, t *testing.T, cluster clusters.Cluster) string

DumpDiagnosticsIfFailed dumps the diagnostics and returns the outpur directory if the test failed.

func EventuallyExpectHTTP404WithNoRoute added in v2.2.0

func EventuallyExpectHTTP404WithNoRoute(
	t *testing.T,
	proxyURL *url.URL,
	host string,
	path string,
	httpsOpts *HTTPSOptions,
	waitDuration time.Duration,
	waitTick time.Duration,
	headers map[string]string,
)

EventuallyExpectHTTP404WithNoRoute is used to check whether a given http response is (specifically) a Kong 404.

func EventuallyGETPath added in v2.2.0

func EventuallyGETPath(
	t *testing.T,
	proxyURL *url.URL,
	host string,
	path string,
	httpsOpts *HTTPSOptions,
	statusCode int,
	bodyContent string,
	requestHeaders map[string]string,
	waitDuration time.Duration,
	waitTick time.Duration,
	responseMatchers ...ResponseMatcher,
)

EventuallyGETPath makes a GET request to the Kong proxy multiple times until either the request starts to respond with the given status code and contents present in the response body, or until timeout occurs according to ingressWait time limits. This uses a "require" for the desired conditions so if this request doesn't eventually succeed the calling test will fail and stop. Parameter proxyURL is the URL of Kong Gateway proxy (set nil when it's not different from parameter host). Parameter host, path and headers are used to make the GET request. Parameter httpsOpts is used to set a cert pool for validating the server certificate or skipping the verification entirely (leave nil to use system one). Response is expected to have the given statusCode and contain the passed bodyContent.

func ExitOnErr added in v2.2.0

func ExitOnErr(ctx context.Context, err error)

ExitOnErr is a wrapper around exitOnErrorWithCode that defaults to using the ExitCodeEnvSetupFailed exit code. This function is meant for convenience to wrap errors in setup that are hard to predict.

func ExitOnErrWithCode added in v2.2.0

func ExitOnErrWithCode(ctx context.Context, err error, exitCode int, fns ...CleanupFunc)

ExitOnErrWithCode is a helper function meant for us in the test.Main to simplify failing and exiting the tests under unrecoverable error conditions. It will also attempt to perform any cluster cleaning necessary before exiting.

func GenerateKongBuilder added in v2.2.0

func GenerateKongBuilder(_ context.Context) (*kong.Builder, []string, error)

GenerateKongBuilder returns a Kong KTF addon builder, a string slice of controller arguments needed to interact with the addon and an error.

func GenerateKongBuilderWithController added in v2.2.0

func GenerateKongBuilderWithController() (*kong.Builder, error)

GenerateKongBuilderWithController generates a Kong builder that installs both KIC and Kong gateway.

func GetFreePort

func GetFreePort(t *testing.T) int

GetFreePort asks the kernel for a free open port that is ready to use. On top of that, it also makes sure that the port hasn't been used in the current test run yet to reduce chances of a race condition in parallel tests.

func GetGatewayIsLinkedCallback added in v2.2.0

func GetGatewayIsLinkedCallback(
	ctx context.Context,
	t *testing.T,
	c *gatewayclient.Clientset,
	protocolType gatewayapi.ProtocolType,
	namespace,
	name string,
) func() bool

GetGatewayIsLinkedCallback returns a callback that checks if the specific Route (HTTP, TCP, TLS, or UDP) is correctly linked to a supported gateway.

func GetGatewayIsUnlinkedCallback added in v2.2.0

func GetGatewayIsUnlinkedCallback(
	ctx context.Context,
	t *testing.T,
	c *gatewayclient.Clientset,
	protocolType gatewayapi.ProtocolType,
	namespace,
	name string,
) func() bool

GetGatewayIsUnlinkedCallback returns a callback that checks if the specific Route (HTTP, TCP, TLS, or UDP) is correctly unlinked from a supported gateway.

func GetKongDBMode added in v2.2.0

func GetKongDBMode(ctx context.Context, proxyAdminURL *url.URL, kongTestPassword string) (dpconf.DBMode, error)

GetKongDBMode returns kong dbmode using the provided Admin API URL.

func GetKongLicenses added in v2.2.0

func GetKongLicenses(ctx context.Context, proxyAdminURL *url.URL, kongTestPassword string) ([]*kong.License, error)

GetKongLicenses fetches all licenses applied to Kong gateway.

func GetKongRootConfig added in v2.2.0

func GetKongRootConfig(ctx context.Context, proxyAdminURL *url.URL, kongTestPassword string) (map[string]any, error)

GetKongRootConfig gets version and root configurations of Kong from / endpoint of the provided Admin API URL.

func GetKongRouterFlavor added in v2.2.0

func GetKongRouterFlavor(ctx context.Context, proxyAdminURL *url.URL, kongTestPassword string) (dpconf.RouterFlavor, error)

GetKongRouterFlavor gets router flavor of Kong using the provided Admin API URL.

func GetKongVersion added in v2.2.0

func GetKongVersion(ctx context.Context, proxyAdminURL *url.URL, kongTestPassword string) (kong.Version, error)

GetKongVersion returns kong version using the provided Admin API URL.

func GetVerifyProgrammedConditionCallback added in v2.2.0

func GetVerifyProgrammedConditionCallback(t *testing.T,
	c *gatewayclient.Clientset,
	protocolType gatewayapi.ProtocolType,
	namespace, name string,
	expectedStatus metav1.ConditionStatus,
) func() bool

func HTTPRouteEventuallyContainsConditions

func HTTPRouteEventuallyContainsConditions(ctx context.Context, t *testing.T, client ctrlclient.Client, nn k8stypes.NamespacedName, conds ...metav1.Condition) func() bool

HTTPRouteEventuallyContainsConditions returns a predicate function that can be used with assert.Eventually or require.Eventually in order to check - via the provided client - that the HTTPRoute with the NamespacedName as provided in the arguments, does indeed contain the provided conditions in the status.

func HTTPRouteEventuallyNotContainsConditions

func HTTPRouteEventuallyNotContainsConditions(ctx context.Context, t *testing.T, client ctrlclient.Client, nn k8stypes.NamespacedName, conds ...metav1.Condition) func() bool

func LabelValueForTest added in v2.2.0

func LabelValueForTest(t *testing.T) string

LabelValueForTest returns a sanitized test name that can be used as kubernetes label value.

func MustHTTPRequest added in v2.2.0

func MustHTTPRequest(t *testing.T, method string, host, path string, headers map[string]string) *http.Request

MustHTTPRequest creates a request with provided parameters and it fails the test that it was called in when request creation fails.

func Namespace added in v2.2.0

Namespace provides the Namespace provisioned for each test case given their t.Name as the "testCase".

func NewKongAdminClient added in v2.2.0

func NewKongAdminClient(proxyAdminURL *url.URL, kongTestPassword string) (*kong.Client, error)

func RemoveCluster added in v2.2.0

func RemoveCluster(ctx context.Context, cluster clusters.Cluster) error

RemoveCluster removes the cluster if it was created by the test suite. Pass desired timeout through context.

func RetryableHTTPClient added in v2.2.0

func RetryableHTTPClient(base *http.Client) *http.Client

RetryableHTTPClient wraps a client with retry logic. That should be used when calling external services that might temporarily fail (e.g. Konnect APIs), and we don't want them to affect the test results.

func Setup added in v2.2.0

Setup is a test helper function which:

  • creates a cluster cleaner which will be used to clean up test resources automatically after the test finishes and creates a new namespace for the test to use.
  • creates a namespace for the provided test and adds it to the cleaner for automatic cleanup using the previously created cleaner.

TODO move this into a shared library https://github.com/Kong/kubernetes-testing-framework/issues/302

func TLSRouteEventuallyContainsConditions added in v2.2.0

func TLSRouteEventuallyContainsConditions(ctx context.Context, t *testing.T, client ctrlclient.Client, nn k8stypes.NamespacedName, conds ...metav1.Condition) func() bool

TLSRouteEventuallyContainsConditions returns a predicate function that can be used with assert.Eventually or require.Eventually to check that the TLSRoute identified by the provided NamespacedName contains the provided conditions in any of its parent statuses.

func TeardownCluster added in v2.2.0

func TeardownCluster(ctx context.Context, t *testing.T, cluster clusters.Cluster)

TeardownCluster dumps the diagnostics from the test cluster if the test failed and performs a cluster removal.

func ValidateMinimalSupportedKongVersion added in v2.2.0

func ValidateMinimalSupportedKongVersion(ctx context.Context, proxyAdminURL *url.URL, kongTestPassword string) (kong.Version, error)

ValidateMinimalSupportedKongVersion returns version of Kong Gateway running at the provided Admin API URL. In case the version is below the minimal supported version versions.KICv3VersionCutoff (3.4.1), it returns an error.

func WaitForDeploymentRollout added in v2.2.0

func WaitForDeploymentRollout(ctx context.Context, t *testing.T, cluster clusters.Cluster, namespace, name string)

WaitForDeploymentRollout waits for the deployment to roll out in the cluster. It fails the test if the deployment doesn't roll out in time.

func WithTypeMeta

func WithTypeMeta[T runtime.Object](t *testing.T, obj T) T

WithTypeMeta adds type meta to the given object based on its Go type.

Types

type CleanupFunc added in v2.2.0

type CleanupFunc func(context.Context) error

type ControllerManagerOpt added in v2.2.0

type ControllerManagerOpt func([]string) []string

func ControllerManagerOptAdditionalWatchNamespace added in v2.2.0

func ControllerManagerOptAdditionalWatchNamespace(ns string) ControllerManagerOpt

ControllerManagerOptAdditionalWatchNamespace adds the provided namespace to controller manager's watch namespaces if it's not there yet.

func ControllerManagerOptFlagUseLastValidConfigForFallback added in v2.2.0

func ControllerManagerOptFlagUseLastValidConfigForFallback() ControllerManagerOpt

ControllerManagerOptFlagUseLastValidConfigForFallback sets --use-last-valid-config-for-fallback controller manager flag.

type CountHTTPResponsesConfig added in v2.2.0

type CountHTTPResponsesConfig struct {
	Method      string
	Host        string
	Path        string
	Headers     map[string]string
	Duration    time.Duration
	RequestTick time.Duration
}

type HTTPClientOption added in v2.2.0

type HTTPClientOption func(*httpClientCfg)

HTTPClientOption is a functional option for configuring the HTTP client.

func WithInsecureSkipVerify added in v2.2.0

func WithInsecureSkipVerify() HTTPClientOption

func WithResolveHostTo added in v2.2.0

func WithResolveHostTo(host string) HTTPClientOption

WithResolveHostTo sets the host to resolve to (equivalent of `curl --resolve`).

func WithRootCAs added in v2.2.0

func WithRootCAs(rootCAs *x509.CertPool) HTTPClientOption

WithRootCAs sets the root CAs for the client.

type HTTPSOptions added in v2.2.0

type HTTPSOptions struct {
	InsecureSkipVerify bool
	CertPool           *x509.CertPool
}

type ResponseMatcher added in v2.2.0

type ResponseMatcher func(resp *http.Response, respBody string) (key string, ok bool)

ResponseMatcher is a function that returns match-name and whether the response matches the provided criteria.

func MatchRespByStatusAndContent added in v2.2.0

func MatchRespByStatusAndContent(
	responseName string,
	expectedStatusCode int,
	expectedBodyContents string,
) ResponseMatcher

MatchRespByStatusAndContent returns a responseMatcher that matches the given status code and body contents.

type TCPProxy added in v2.1.1

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

TCPProxy is a simple server that forwards TCP connections to a given destination. It can be used to simulate network failures by stopping accepting new connections and interrupting existing ones.

func NewTCPProxy added in v2.1.1

func NewTCPProxy(destination string) (*TCPProxy, error)

func (*TCPProxy) Address added in v2.2.0

func (p *TCPProxy) Address() string

Address returns the address of the proxy.

func (*TCPProxy) Run added in v2.2.0

func (p *TCPProxy) Run(ctx context.Context) error

Run starts connections accepting loop and blocks until the context is canceled.

func (*TCPProxy) StartHandlingConnections added in v2.2.0

func (p *TCPProxy) StartHandlingConnections()

StartHandlingConnections starts handling new connections.

func (*TCPProxy) StopHandlingConnections added in v2.2.0

func (p *TCPProxy) StopHandlingConnections()

StopHandlingConnections stops handling connections by interrupting all existing connections and immediately closing new connections.

type TooOldKongGatewayError added in v2.2.0

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

func (TooOldKongGatewayError) Error added in v2.2.0

func (e TooOldKongGatewayError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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