testutil

package
v0.7.1 Latest Latest
Warning

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

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

Documentation

Overview

Package testutil builds fixture objects and fake clients for backend tests.

Index

Constants

View Source
const Controller = "kgateway.dev/kgateway"

Controller is the upstream kgateway controller name.

View Source
const RecvTimeout = 10 * time.Second

RecvTimeout bounds every channel receive in tests.

View Source
const ScaleNoReadyEvery = 20

ScaleNoReadyEvery makes every ScaleNoReadyEvery-th referenced Service of a worst-case shape lack a ready endpoint: 5 %.

View Source
const ScaleReferencedLabel = "scale/referenced"

ScaleReferencedLabel is "true" on the Services a Backend or route names.

View Source
const ScaleRejectEvery = 20

ScaleRejectEvery makes a seeded 1 in ScaleRejectEvery Gateways of a non-worst shape reject: 5 %.

View Source
const ScaleSkewedProxyTag = "v2.3.11"

ScaleSkewedProxyTag is the proxy image tag of a worst-case shape: a minor behind the controller, so every Gateway's proxies skew (KGWUI-022).

View Source
const SettingValueFrom = "<valueFrom>"

SettingValueFrom is a Settings value meaning the env var uses valueFrom, so the UI cannot read it.

Variables

View Source
var Now = time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC)

Now is the fixed clock used by fixtures and by tests that compare times.

View Source
var Old = metav1.NewTime(Now.Add(-time.Hour))

Old is a creation time well past every grace period.

View Source
var ScaleTeamLabel = map[string]string{"team": "web"}

ScaleTeamLabel is the label of every fourth scale namespace; each scale Gateway has one Selector listener that selects it.

Functions

func AddSpecListener

func AddSpecListener(gw *unstructured.Unstructured, name string)

AddSpecListener adds a listener to gw's spec without a status block, as when the controller has not processed it yet.

func Backend

func Backend(ns, name string, cs []metav1.Condition) *unstructured.Unstructured

Backend builds a kgateway Backend of type Static. With no conditions given it is Accepted.

func BackendTLSPolicy

func BackendTLSPolicy(ns, name string, ancestors ...PolicyAncestor) *unstructured.Unstructured

BackendTLSPolicy builds a Gateway API BackendTLSPolicy with status.ancestors.

func CRDMetadata

func CRDMetadata(name, bundleVersion, channel string) *metav1.PartialObjectMetadata

CRDMetadata builds the metadata a metadata client returns for a Gateway API CRD: name, bundle-version and channel annotations.

func Clients

func Clients(t *testing.T, objs ...runtime.Object) (dynamic.Interface, *kubefake.Clientset)

Clients returns fake dynamic and typed clients seeded with objs. Unstructured objects go to the dynamic client under the served GVR of their kind; everything else goes to the typed client. Fake discovery serves every upstream kind at its first version.

func ClientsFor

func ClientsFor(t *testing.T, served []kinds.Served, objs ...runtime.Object) (dynamic.Interface, *kubefake.Clientset)

ClientsFor is Clients with fake discovery and list kinds for served, for tests that serve a kind at a version other than its first.

func ClientsWith

func ClientsWith(t *testing.T, extra []kinds.Descriptor, objs ...runtime.Object) (dynamic.Interface, *kubefake.Clientset)

ClientsWith is Clients with extra kinds served at their first version, for downstream-extension tests.

func Cond

func Cond(typ string, status metav1.ConditionStatus, reason string) metav1.Condition

Cond builds a condition observed at generation 1.

func ControllerDeployment

func ControllerDeployment(ns, name, image string, desired, ready int32, env ...corev1.EnvVar) *appsv1.Deployment

ControllerDeployment builds a kgateway controller Deployment with the upstream labels. The Pod template carries the upstream v2.3/v2.4 Pod labels exactly: the selector labels plus app.kubernetes.io/component=controller.

func ControllerPod

func ControllerPod(d *appsv1.Deployment, name string, ready bool) *corev1.Pod

ControllerPod builds a Pod of d. ready controls its Ready condition and phase.

func DelegateLabel

func DelegateLabel(ns, label string) map[string]any

DelegateLabel is a backendRef that delegates to the HTTPRoutes in ns labelled with the delegation label value label.

func DelegateTo

func DelegateTo(ns, name string) map[string]any

DelegateTo is a backendRef that delegates to the HTTPRoute ns/name.

func DelegateWildcard

func DelegateWildcard(ns string) map[string]any

DelegateWildcard is a backendRef that delegates to every HTTPRoute in ns.

func DirectResponse

func DirectResponse(ns, name string) *unstructured.Unstructured

DirectResponse builds a kgateway DirectResponse with no status.

func Drain

func Drain[T any](ch <-chan T)

Drain discards the values buffered in ch without blocking.

func EndpointSlice

func EndpointSlice(ns, name, svc string, ready ...bool) *discoveryv1.EndpointSlice

EndpointSlice builds a slice of service svc with one endpoint per ready entry, each Ready as given.

func Env

func Env(name, value string) corev1.EnvVar

Env is a shorthand for a literal env var.

func FakeClock

func FakeClock() *clocktesting.FakeClock

FakeClock returns a fake clock at Now.

func Gateway

func Gateway(ns, name, class string, cs []metav1.Condition, listeners ...Listener) *unstructured.Unstructured

Gateway builds a Gateway. With no conditions given it is Accepted and Programmed. Its listeners admit routes from every namespace.

func GatewayClass

func GatewayClass(name, controller string, accepted bool) *unstructured.Unstructured

GatewayClass builds a GatewayClass with an Accepted condition.

func GatewayExtension

func GatewayExtension(ns, name string) *unstructured.Unstructured

GatewayExtension builds a kgateway GatewayExtension with no status.

func GatewayParameters

func GatewayParameters(ns, name string, selfManaged bool) *unstructured.Unstructured

GatewayParameters builds a kgateway GatewayParameters. selfManaged sets spec.selfManaged; otherwise it carries only a spec.kube block.

func GatewayWithListeners

func GatewayWithListeners(ns, name, class string, spec []objects.Listener, status ...Listener) *unstructured.Unstructured

GatewayWithListeners builds an Accepted, Programmed Gateway whose spec listeners are spec, as given, and whose status listeners are status.

func GwRef

func GwRef(ns, name string) objects.ParentRef

GwRef is a parentRef to a Gateway.

func HTTPRoute

func HTTPRoute(ns, name string, parents []objects.ParentRef, status ...RouteParent) *unstructured.Unstructured

HTTPRoute builds an HTTPRoute with the given parentRefs and status.parents.

func HTTPRouteRef

func HTTPRouteRef(ns, name string) objects.ParentRef

HTTPRouteRef is a parentRef to an HTTPRoute.

func ListenerSet

func ListenerSet(ns, name string, parent objects.ParentRef, cs []metav1.Condition, listeners ...Listener) *unstructured.Unstructured

ListenerSet builds a ListenerSet attached to parent. With no conditions given it is Accepted and Programmed; with no listeners it has one accepted listener "extra". A listener with nil Conds has no status block.

func Namespace

func Namespace(name string, lbls map[string]string) *corev1.Namespace

Namespace builds a namespace with labels.

func ObjectsByGVR

ObjectsByGVR groups objs under the upstream served GVR of their kind, as in cache.Snapshot.Objects. It fails the test for an object of an unserved kind.

func PodList

func PodList(ps ...*corev1.Pod) []*corev1.Pod

PodList converts pods for use in a Snapshot.

func Policy

func Policy(apiVersion, kind, ns, name string, ancestors ...PolicyAncestor) *unstructured.Unstructured

Policy builds a policy of any kind with status.ancestors.

func ProxyDeployment

func ProxyDeployment(gwNS, gwName string, desired, ready int32) *appsv1.Deployment

ProxyDeployment builds the proxy Deployment kgateway creates for a Gateway.

func ProxyPod

func ProxyPod(gwNS, gwName string, i int, suffix string, restarts int32) *corev1.Pod

ProxyPod builds Pod number i of a Gateway's proxy Deployment, Ready, with restarts container restarts: kgateway's Pod labels, owned by the ReplicaSet "<gwName>-<suffix>" whose pod-template-hash is suffix.

func Recv

func Recv[T any](t *testing.T, ch <-chan T, what string) T

Recv returns the next value from ch, failing the test after RecvTimeout. Call it only from the test goroutine.

func ReferenceGrant

func ReferenceGrant(ns, name, fromNS string) *unstructured.Unstructured

ReferenceGrant builds a ReferenceGrant that lets HTTPRoutes of fromNS use Services in ns. It has no status.

func Rule

func Rule(matches ...map[string]any) map[string]any

Rule builds an HTTPRoute rule with the given matches; with none, matches is omitted.

func SafeGatewayLabelValue

func SafeGatewayLabelValue(name string) string

SafeGatewayLabelValue is the gateway-name label value kgateway writes: the name, or for one over 63 characters its first 50 (trailing "-" trimmed), "-" and the first 12 hex digits of its SHA-256.

func ScaleCRDs

func ScaleCRDs(t ScaleShape) []*metav1.PartialObjectMetadata

ScaleCRDs returns the metadata of GatewayAPICRDs Gateway API CRDs.

func ScaleClients

func ScaleClients(tb testing.TB, objs ...runtime.Object) (*dynamicfake.FakeDynamicClient, *kubefake.Clientset)

ScaleClients is Clients under testing.TB, for scale benchmarks and budgets.

func ScaleEndpointSlices

func ScaleEndpointSlices(t ScaleShape, seed int64) []*discoveryv1.EndpointSlice

ScaleEndpointSlices returns one slice per Service plus second slices of referenced ones, each with the Service's port. Under Worst every ScaleNoReadyEvery-th referenced Service has no ready endpoint.

func ScaleEvents

func ScaleEvents(t ScaleShape, seed int64) []*corev1.Event

ScaleEvents returns WarningEvents Warning Events, spread round-robin over the proxy Pods, with seeded reasons and times in the hour before Now.

func ScaleGateway

func ScaleGateway(i int) string

ScaleGateway is the name of scale Gateway i.

func ScaleLabelled

func ScaleLabelled(i int) bool

ScaleLabelled reports whether scale namespace i carries ScaleTeamLabel.

func ScaleLongGatewayObjects

func ScaleLongGatewayObjects(t ScaleShape) []*unstructured.Unstructured

ScaleLongGatewayObjects returns the Gateways whose proxy Pods ScaleProxyPods adds under Worst; it is empty otherwise.

func ScaleLongGateways

func ScaleLongGateways() []string

ScaleLongGateways are the names, over 63 characters, of the extra Gateways of a worst-case shape. The first two share their first 50 characters, so their label values differ only by hash; the third is unrelated.

func ScaleMetadata

func ScaleMetadata(tb testing.TB, crds ...*metav1.PartialObjectMetadata) metadata.Interface

ScaleMetadata is a fake metadata client serving crds.

func ScaleMetrics

func ScaleMetrics(t ScaleShape, seed int64) []byte

ScaleMetrics returns a /metrics capture shaped like the ctrlmetrics rejects captures. Under Worst every Gateway rejects; otherwise a seeded 1 in ScaleRejectEvery does.

func ScaleNamespace

func ScaleNamespace(i int) string

ScaleNamespace is the name of scale namespace i.

func ScaleNamespaces

func ScaleNamespaces(n int) []*corev1.Namespace

ScaleNamespaces builds the n namespaces ns-000 … of a scale world, every fourth one labelled with ScaleTeamLabel.

func ScaleProxyDeployments

func ScaleProxyDeployments(t ScaleShape) []*appsv1.Deployment

ScaleProxyDeployments returns each Gateway's proxy Deployment, long-named ones included, selecting its ScaleProxyPods. Under Worst each is past its progress deadline with every replica ready (KGWUI-021).

func ScaleProxyPods

func ScaleProxyPods(t ScaleShape, seed int64) []*corev1.Pod

ScaleProxyPods returns ProxyPodsPerGateway Ready proxy Pods for each Gateway, long-named ones included, each with its own Pod IP. Under Worst each restarted once a minute before Now and runs ScaleSkewedProxyTag.

func ScaleServiceName

func ScaleServiceName(t ScaleShape, i int) string

ScaleServiceName names Service i: "ref-" for the referenced ones, else "svc-".

func ScaleServices

func ScaleServices(t ScaleShape, _ int64) []*corev1.Service

ScaleServices returns Services Services over the namespaces, the first ReferencedServices labelled ScaleReferencedLabel.

func ServedUpstream

func ServedUpstream() []kinds.Served

ServedUpstream resolves every upstream descriptor to its first version.

func Service

func Service(ns, name string, lbls map[string]string) *corev1.Service

Service builds a ClusterIP Service with one port.

func SetClassParameters

func SetClassParameters(class *unstructured.Unstructured, group, kind, ns, name string)

SetClassParameters sets class's spec.parametersRef.

func SetGatewayParameters

func SetGatewayParameters(gw *unstructured.Unstructured, group, kind, name string)

SetGatewayParameters sets gw's spec.infrastructure.parametersRef.

func TrafficPolicy

func TrafficPolicy(ns, name string, ancestors ...PolicyAncestor) *unstructured.Unstructured

TrafficPolicy builds a kgateway TrafficPolicy with status.ancestors.

func WarningEvent

func WarningEvent(pod *corev1.Pod, name, reason string, at time.Time) *corev1.Event

WarningEvent builds a Warning Event about a Pod, first and last seen at at.

func WithHostnames

func WithHostnames(u *unstructured.Unstructured, h ...string) *unstructured.Unstructured

WithHostnames sets u's spec.hostnames and returns u.

func WithRules

func WithRules(u *unstructured.Unstructured, rules ...map[string]any) *unstructured.Unstructured

WithRules sets u's spec.rules and returns u.

Types

type FakeKube

type FakeKube = kubefake.Clientset

FakeKube is the fake typed client, named so scale code needs no client-go import.

type Listener

type Listener struct {
	Name     string
	Attached int32
	Conds    []metav1.Condition
}

Listener is a listener status entry for Gateway fixtures.

type PolicyAncestor

type PolicyAncestor struct {
	Ref        objects.ParentRef
	Controller string
	Conds      []metav1.Condition
}

PolicyAncestor is a status.ancestors entry for policy fixtures.

type RouteParent

type RouteParent struct {
	Ref        objects.ParentRef
	Controller string
	Conds      []metav1.Condition
}

RouteParent is a status.parents entry for route fixtures.

func AcceptedBy

func AcceptedBy(p objects.ParentRef, controller string) RouteParent

AcceptedBy is the status.parents entry of a healthy route attached to p by controller.

type RuleCase

type RuleCase struct {
	// Provenance names the kgateway output (`translator/gateway/testutils/outputs/<file>@<tag>`)
	// or the rules section the expectation comes from.
	Provenance string
	// RuleOnly keeps the case out of the API matrix.
	RuleOnly          bool
	ControllerVersion string
	// Settings are controller env vars; an absent key is an absent env var.
	Settings map[string]string
	// NamespacesOK defaults to true when the file omits it.
	NamespacesOK bool
	// Namespaces maps each existing Namespace to its labels.
	Namespaces map[string]map[string]string
	// Bounds overrides computed.Bounds fields by name.
	Bounds  map[string]int
	Objects []*unstructured.Unstructured
	Expect  map[string]any
}

RuleCase is one computed-rules fixture (rules §11): a world of objects and the views expected from it, written from Provenance and never generated.

func LoadRuleCase

func LoadRuleCase(t *testing.T, path string) RuleCase

LoadRuleCase reads one YAML rule case. Unknown top-level keys fail the test; an object without metadata.generation gets generation 1.

type ScaleShape

type ScaleShape struct {
	Gateways, Namespaces                int
	Services, ReferencedServices        int
	EndpointSlices, ProxyPodsPerGateway int
	WarningEvents, GatewayAPICRDs       int
	// Worst adds ScaleLongGateways and makes every Gateway reject, 5 % of
	// referenced Services lack a ready endpoint and every proxy Pod restart.
	Worst bool
}

ScaleShape is the size of a scale tier's typed Phase 3 objects; package scale fills it from its Tier.

Directories

Path Synopsis
Package benchgate decides how a bench budget fails (D-044).
Package benchgate decides how a bench budget fails (D-044).
Package computedtest has test doubles for the computed views.
Package computedtest has test doubles for the computed views.
Package healthtest has test helpers for the health check contract.
Package healthtest has test helpers for the health check contract.
Package metricstest builds controller metrics values for tests, as the kgateway pack's collector publishes them.
Package metricstest builds controller metrics values for tests, as the kgateway pack's collector publishes them.
Package scale builds deterministic worlds of the scale tiers of design §9.6 for benchmarks and scale tests.
Package scale builds deterministic worlds of the scale tiers of design §9.6 for benchmarks and scale tests.
measure
Package measure builds the measurement world of the 3.2 and 3.3 budgets (design §16.3): scale.LivePhase3 with its optional watches, controller metrics with rejects per Gateway, observed probe failures, a stub proxy stats source and the controller log reader over a stub stream at LogRate, both published through the real collector store.
Package measure builds the measurement world of the 3.2 and 3.3 budgets (design §16.3): scale.LivePhase3 with its optional watches, controller metrics with rejects per Gateway, observed probe failures, a stub proxy stats source and the controller log reader over a stub stream at LogRate, both published through the real collector store.

Jump to

Keyboard shortcuts

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