Help us shape the future of Go! Take the 2026 Go Developer Survey

testutils

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Overview

Package testutils provides test utilities for crossplane-diff.

Index

Constants

View Source
const (
	ColorRed    = "\x1b[31m"
	ColorGreen  = "\x1b[32m"
	ColorYellow = "\x1b[33m"
	ColorReset  = "\x1b[0m"
)

Colors for terminal output.

Variables

This section is empty.

Functions

func AssertStructuredCompDiff added in v0.7.0

func AssertStructuredCompDiff(t *testing.T, jsonOutput string, e CompDiffExpectation)

AssertStructuredCompDiff compares actual JSON output against expected. Accepts CompDiffExpectation interface so callers don't need to call And()/AndXR()/AndComp().

func AssertStructuredDiff added in v0.7.0

func AssertStructuredDiff(t *testing.T, jsonOutput string, e DiffExpectation)

AssertStructuredDiff compares actual JSON output against expected. Accepts DiffExpectation interface so callers don't need to call And() to return to root.

func CRDsForXRD added in v0.11.0

CRDsForXRD returns the CRDs Crossplane generates from an XRD manifest: the composite resource's CRD and, when the XRD sets spec.claimNames, the claim's. Generation is upstream's (crossplane-runtime pkg/xcrd, via the crossplane CLI's ConvertToCRDs), so a test cluster gets the same CRDs a real one would.

xcrd consumes the XRD as Crossplane's controller reads it: at apiextensions.crossplane.io/v1, with the apiserver's defaults applied. A manifest has neither, and the defaults decide what is generated (the policy defaults the CRDs declare, and the scope of an XRD that omits it, which is Namespaced at v2 but LegacyCluster at v1). So the manifest is first defaulted exactly as the apiserver would: with the schema of its own version, then relabelled to v1 (the XRD CRD converts with strategy None, so only apiVersion changes) and defaulted with v1's. Both schemas come from xrdCRD, the CompositeResourceDefinition CRD.

The generated CRDs carry no owner reference: xcrd points one at the XRD, but the XRD has not been created yet when a test installs its CRDs, so it has no UID and an apiserver would reject the reference.

The input is not modified.

func CompareIgnoringAnsi

func CompareIgnoringAnsi(expected, actual string) bool

CompareIgnoringAnsi compares two strings after stripping ANSI special characters.

func CreateFakeDiscoveryClient

func CreateFakeDiscoveryClient(resources map[string][]metav1.APIResource) discovery.DiscoveryInterface

CreateFakeDiscoveryClient is a helper function to create a fake discovery client for testing. The fake discovery client automatically derives API groups from the provided resources, enabling both ServerResourcesForGroupVersion() and ServerGroups() to work correctly.

func DockerContainer added in v0.11.0

func DockerContainer(id string, state container.ContainerState, labels map[string]string, networks ...string) container.Summary

DockerContainer returns a container in state, carrying labels and attached to the named networks.

func DockerNetwork added in v0.11.0

func DockerNetwork(name string, labels map[string]string) network.Summary

DockerNetwork returns a network carrying labels. Its ID is its name.

func DockerSession added in v0.11.0

func DockerSession(id string) map[string]string

DockerSession returns the labels the upstream render engine puts on what it creates for session id.

func Green

func Green(input string) string

Green takes a multiline string, splits it by line, and adds green coloring to each line. It returns a single string with all lines joined back together.

func PinnedCrossplaneCRDsDir added in v0.11.0

func PinnedCrossplaneCRDsDir(tb testing.TB) string

PinnedCrossplaneCRDsDir returns the directory of Crossplane's own CRDs (Compositions, XRDs, Functions, …) at the version of github.com/crossplane/crossplane/v2 that go.mod pins, so they match the xcrd and the rest of the Crossplane code under test. `earthly +fetch-crossplane-crds-gomod` writes them to cluster/gomod/crds at the repository root. They are located from this source file rather than the working directory, and the test fails with the target to run if they are missing.

func Red

func Red(input string) string

Red takes a multiline string, splits it by line, and adds red coloring to each line. It returns a single string with all lines joined back together.

func SetupKubeTestLogger

func SetupKubeTestLogger(t *testing.T)

SetupKubeTestLogger sets the global logger for use of the Kube environment to the T.Log of this test.

func TestLogger

func TestLogger(t *testing.T, verbose bool) logging.Logger

TestLogger coerces the T.Log into the shape of a Logr logger.

func Yellow added in v0.5.0

func Yellow(input string) string

Yellow takes a multiline string, splits it by line, and adds yellow coloring to each line. It returns a single string with all lines joined back together.

Types

type AdvisoryCapturingLogger added in v0.11.0

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

AdvisoryCapturingLogger wraps a logging.Logger and records the messages passed to Info, so a test can assert that a call site raises a user-facing advisory rather than mere tracing.

Info is the codebase's advisory level: the CLI wraps the injected logger so every Info becomes a stderr WARNING line and a structured warnings[] entry. Emitters deliberately know nothing about that wrapper, so tests for them assert the contract they actually have — "this calls Info, not Debug" — instead of coupling to the wrapper. That also lets packages the wrapper's own package imports (the clients) assert their advisories without an import cycle.

func NewAdvisoryCapturingLogger added in v0.11.0

func NewAdvisoryCapturingLogger(t *testing.T) *AdvisoryCapturingLogger

NewAdvisoryCapturingLogger returns a logger that forwards to a standard test logger while recording Info messages for assertion.

func (*AdvisoryCapturingLogger) Advisories added in v0.11.0

func (l *AdvisoryCapturingLogger) Advisories() []string

Advisories returns the Info messages recorded so far, in call order.

func (*AdvisoryCapturingLogger) Debug added in v0.11.0

func (l *AdvisoryCapturingLogger) Debug(msg string, keysAndValues ...any)

Debug forwards to the wrapped logger without recording: tracing is not an advisory.

func (*AdvisoryCapturingLogger) Info added in v0.11.0

func (l *AdvisoryCapturingLogger) Info(msg string, keysAndValues ...any)

Info records msg as an advisory and forwards to the wrapped logger.

func (*AdvisoryCapturingLogger) WithValues added in v0.11.0

func (l *AdvisoryCapturingLogger) WithValues(keysAndValues ...any) logging.Logger

WithValues returns a derived logger that records into the same place, so an advisory raised through a derived logger is still captured.

type AffectedResourcesSummary added in v0.7.0

type AffectedResourcesSummary struct {
	Total              int `json:"total"`
	WithChanges        int `json:"withChanges"`
	Unchanged          int `json:"unchanged"`
	WithErrors         int `json:"withErrors"`
	FilteredByPolicy   int `json:"filteredByPolicy,omitempty"`
	FilteredBySelector int `json:"filteredBySelector,omitempty"`
	FilteredByDeletion int `json:"filteredByDeletion,omitempty"`
}

AffectedResourcesSummary mirrors renderer.AffectedResourcesSummary.

type CRDBuilder added in v0.2.0

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

CRDBuilder helps construct CRD resources for testing.

func NewCRD added in v0.2.0

func NewCRD(name, group, kind string) *CRDBuilder

NewCRD creates a new CRDBuilder.

func (*CRDBuilder) Build added in v0.2.0

Build returns the built CRD.

func (*CRDBuilder) WithClusterScope added in v0.2.0

func (b *CRDBuilder) WithClusterScope() *CRDBuilder

WithClusterScope sets the CRD to be cluster-scoped.

func (*CRDBuilder) WithDefaultVersion added in v0.3.0

func (b *CRDBuilder) WithDefaultVersion() *CRDBuilder

WithDefaultVersion adds a default "v1" version to the CRD.

func (*CRDBuilder) WithDefaultedStringFieldSchema added in v0.11.0

func (b *CRDBuilder) WithDefaultedStringFieldSchema(fieldName, defaultValue string) *CRDBuilder

WithDefaultedStringFieldSchema adds a schema whose spec has a single string field carrying a `default:` value, for exercising CRD defaulting.

func (*CRDBuilder) WithListKind added in v0.2.0

func (b *CRDBuilder) WithListKind(listKind string) *CRDBuilder

WithListKind sets the ListKind name for the CRD.

func (*CRDBuilder) WithNamespaceScope added in v0.2.0

func (b *CRDBuilder) WithNamespaceScope() *CRDBuilder

WithNamespaceScope sets the CRD to be namespace-scoped.

func (*CRDBuilder) WithPlural added in v0.2.0

func (b *CRDBuilder) WithPlural(plural string) *CRDBuilder

WithPlural sets the plural name for the CRD.

func (*CRDBuilder) WithSchema added in v0.2.0

func (b *CRDBuilder) WithSchema(schema *extv1.JSONSchemaProps) *CRDBuilder

WithSchema adds an OpenAPI v3 schema to the last added version.

func (*CRDBuilder) WithScope added in v0.2.0

func (b *CRDBuilder) WithScope(scope extv1.ResourceScope) *CRDBuilder

WithScope sets the scope (Namespaced or Cluster) for the CRD.

func (*CRDBuilder) WithSingular added in v0.2.0

func (b *CRDBuilder) WithSingular(singular string) *CRDBuilder

WithSingular sets the singular name for the CRD.

func (*CRDBuilder) WithStandardSchema added in v0.2.0

func (b *CRDBuilder) WithStandardSchema(specFieldName string) *CRDBuilder

WithStandardSchema adds a standard schema with common Kubernetes fields and a spec field.

func (*CRDBuilder) WithStringFieldSchema added in v0.2.0

func (b *CRDBuilder) WithStringFieldSchema(fieldName string) *CRDBuilder

WithStringFieldSchema adds a simple string field schema to the CRD.

func (*CRDBuilder) WithVersion added in v0.2.0

func (b *CRDBuilder) WithVersion(name string, served, storage bool) *CRDBuilder

WithVersion adds a version to the CRD.

type ChangeDetail added in v0.7.0

type ChangeDetail struct {
	Type       string         `json:"type"`
	APIVersion string         `json:"apiVersion"`
	Kind       string         `json:"kind"`
	Name       string         `json:"name"`
	Namespace  string         `json:"namespace,omitempty"`
	Diff       map[string]any `json:"diff"`
	DryRun     *DryRunInfo    `json:"dryRun,omitempty"`
}

ChangeDetail mirrors renderer.ChangeDetail.

type CompDiffExpectation added in v0.7.0

type CompDiffExpectation interface {
	// contains filtered or unexported methods
}

CompDiffExpectation is an interface that allows AssertStructuredCompDiff to accept any level of the builder hierarchy, eliminating the need for And()/AndXR()/AndComp().

type CompWarningExpectation added in v0.11.0

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

CompWarningExpectation describes one expected entry in a comp diff's warnings[].

func (*CompWarningExpectation) And added in v0.11.0

And returns to the parent builder.

func (*CompWarningExpectation) WithWarningContext added in v0.11.0

func (w *CompWarningExpectation) WithWarningContext(context map[string]string) *CompWarningExpectation

WithWarningContext pins the expected context key/value pairs on the warning under construction.

type CompositionBuilder

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

CompositionBuilder helps construct Composition objects for testing.

func NewComposition

func NewComposition(name string) *CompositionBuilder

NewComposition creates a new CompositionBuilder.

func (*CompositionBuilder) Build

Build returns the built Composition.

func (*CompositionBuilder) BuildAsUnstructured added in v0.2.0

func (b *CompositionBuilder) BuildAsUnstructured() *un.Unstructured

BuildAsUnstructured returns the built Composition as an unstructured object.

func (*CompositionBuilder) WithAnnotations added in v0.11.0

func (b *CompositionBuilder) WithAnnotations(annotations map[string]string) *CompositionBuilder

WithAnnotations sets metadata.annotations on the composition. Useful for modelling the tooling-applied annotations a cluster copy carries but a file copy does not (notably kubectl.kubernetes.io/last-applied-configuration).

func (*CompositionBuilder) WithCompositeTypeRef

func (b *CompositionBuilder) WithCompositeTypeRef(apiVersion, kind string) *CompositionBuilder

WithCompositeTypeRef sets the composite type reference.

func (*CompositionBuilder) WithLabels added in v0.9.0

func (b *CompositionBuilder) WithLabels(labels map[string]string) *CompositionBuilder

WithLabels sets metadata.labels on the composition. CompositionRevisions inherit these labels, so they drive compositionRevisionSelector matching in comp-diff tests.

func (*CompositionBuilder) WithPipelineMode

func (b *CompositionBuilder) WithPipelineMode() *CompositionBuilder

WithPipelineMode sets the composition mode to pipeline.

func (*CompositionBuilder) WithPipelineStep

func (b *CompositionBuilder) WithPipelineStep(step, functionName string, input map[string]any, opts ...PipelineStepOption) *CompositionBuilder

WithPipelineStep adds a pipeline step to the composition.

type CompositionDiffWire added in v0.10.0

type CompositionDiffWire struct {
	Name               string                   `json:"name"`
	Error              string                   `json:"error,omitempty"`  // v1 only
	Errors             []OutputError            `json:"errors,omitempty"` // v2 only
	CompositionChanges *ChangeDetail            `json:"compositionChanges,omitempty"`
	AffectedResources  AffectedResourcesSummary `json:"affectedResources"`
	ImpactAnalysis     []XRImpactWire           `json:"impactAnalysis"`
	// ImpactAnalysisSkipped distinguishes "not evaluated" from "no affected composites found".
	ImpactAnalysisSkipped bool `json:"impactAnalysisSkipped,omitempty"`
	// MaskedChangesOnly records that an absent compositionChanges does not mean unchanged.
	MaskedChangesOnly bool `json:"maskedChangesOnly,omitempty"`
	// RevisionImpact mirrors renderer.RevisionImpact.
	RevisionImpact RevisionImpactWire `json:"revisionImpact"`
}

CompositionDiffWire mirrors compositionDiffWire from the renderer.

type CompositionExpectation added in v0.7.0

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

CompositionExpectation defines expectations for a single composition in the diff.

func (*CompositionExpectation) And added in v0.7.0

And returns to parent to chain more composition expectations. Not needed at the end of a chain - AssertStructuredCompDiff accepts CompositionExpectation directly.

func (*CompositionExpectation) AndComposition added in v0.11.0

func (c *CompositionExpectation) AndComposition(name string) *CompositionExpectation

AndComposition starts an expectation for another composition. See DownstreamResourceExpectation.AndComposition.

func (*CompositionExpectation) WithAffectedResources added in v0.7.0

func (c *CompositionExpectation) WithAffectedResources(total, withChanges, unchanged, withErrors int) *CompositionExpectation

WithAffectedResources sets the expected affected resources counts.

func (*CompositionExpectation) WithCompositionErrorContaining added in v0.11.0

func (c *CompositionExpectation) WithCompositionErrorContaining(s string) *CompositionExpectation

WithCompositionErrorContaining asserts the composition failed with an error containing s: v1's error string, or a message in v2's errors[].

func (*CompositionExpectation) WithCompositionFieldChange added in v0.7.0

func (c *CompositionExpectation) WithCompositionFieldChange(path string, oldValue, newValue any) *CompositionExpectation

WithCompositionFieldChange asserts a specific field in the composition changed from old to new value.

func (*CompositionExpectation) WithCompositionModified added in v0.7.0

func (c *CompositionExpectation) WithCompositionModified() *CompositionExpectation

WithCompositionModified asserts that the composition itself is modified.

func (*CompositionExpectation) WithFilteredByDeletion added in v0.11.0

func (c *CompositionExpectation) WithFilteredByDeletion(count int) *CompositionExpectation

WithFilteredByDeletion asserts the number of XRs excluded from impact analysis because they are being deleted (AffectedResourcesSummary.FilteredByDeletion). A single-purpose setter rather than a positional counterpart to WithAffectedResources, so a caller cannot transpose filter counters.

func (*CompositionExpectation) WithImpactAnalysisSkipped added in v0.11.0

func (c *CompositionExpectation) WithImpactAnalysisSkipped() *CompositionExpectation

WithImpactAnalysisSkipped asserts that the composites were deliberately not evaluated, which is what distinguishes "we did not look" from "we looked and found no affected composites" — both of which leave impactAnalysis empty.

func (*CompositionExpectation) WithPredictedRevisionNamePattern added in v0.11.0

func (c *CompositionExpectation) WithPredictedRevisionNamePattern(pattern string) *CompositionExpectation

WithPredictedRevisionNamePattern asserts that revisionImpact.predictedRevisionName matches pattern (an unanchored regexp unless the pattern anchors itself). Use for the usual case, where the name's hash suffix is not worth pinning in an end-to-end test.

func (*CompositionExpectation) WithRevisionImpact added in v0.11.0

func (c *CompositionExpectation) WithRevisionImpact(changeScope string, createsRevision bool, repointedComposites int) *CompositionExpectation

WithRevisionImpact asserts what applying the composition does to CompositionRevisions, independent of whether anything renders differently. changeScope is "none", "metadata" or "spec".

func (*CompositionExpectation) WithXRImpact added in v0.7.0

func (c *CompositionExpectation) WithXRImpact(kind, name, namespace, status string) *XRImpactExpectation

WithXRImpact adds an expectation for an XR impact.

func (*CompositionExpectation) WithoutPredictedRevisionName added in v0.11.0

func (c *CompositionExpectation) WithoutPredictedRevisionName() *CompositionExpectation

WithoutPredictedRevisionName asserts that revisionImpact carries no predictedRevisionName — i.e. the revision's identity could not be predicted. Distinct from simply not asserting on the field.

type DiffExpectation added in v0.7.0

type DiffExpectation interface {
	// contains filtered or unexported methods
}

DiffExpectation is an interface that allows AssertStructuredDiff to accept either *ExpectedDiff or *ResourceExpectation, eliminating the need for And().

type DiffProcessor

type DiffProcessor interface {
	Initialize(ctx context.Context) error
	ProcessAll(stdout io.Writer, ctx context.Context, resources []*un.Unstructured) error
	ProcessResource(stdout io.Writer, ctx context.Context, res *un.Unstructured) error
}

DiffProcessor defines the interface for processing resources for diffing.

type DiffProcessorBuilder

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

DiffProcessorBuilder helps build mock DiffProcessor instances.

func NewMockDiffProcessor

func NewMockDiffProcessor() *DiffProcessorBuilder

NewMockDiffProcessor creates a new DiffProcessorBuilder.

func (*DiffProcessorBuilder) Build

Build creates and returns the configured mock DiffProcessor.

func (*DiffProcessorBuilder) WithFailedInitialize

func (b *DiffProcessorBuilder) WithFailedInitialize(errMsg string) *DiffProcessorBuilder

WithFailedInitialize sets a failing Initialize implementation.

func (*DiffProcessorBuilder) WithFailedPerformDiff

func (b *DiffProcessorBuilder) WithFailedPerformDiff(errMsg string) *DiffProcessorBuilder

WithFailedPerformDiff sets a failing PerformDiff implementation.

func (*DiffProcessorBuilder) WithInitialize

func (b *DiffProcessorBuilder) WithInitialize(fn func(context.Context) error) *DiffProcessorBuilder

WithInitialize adds an implementation for the Initialize method.

func (*DiffProcessorBuilder) WithPerformDiff

WithPerformDiff adds an implementation for the PerformDiff method.

func (*DiffProcessorBuilder) WithSuccessfulInitialize

func (b *DiffProcessorBuilder) WithSuccessfulInitialize() *DiffProcessorBuilder

WithSuccessfulInitialize sets a successful Initialize implementation.

func (*DiffProcessorBuilder) WithSuccessfulPerformDiff

func (b *DiffProcessorBuilder) WithSuccessfulPerformDiff() *DiffProcessorBuilder

WithSuccessfulPerformDiff sets a successful PerformDiff implementation with no diffs.

func (*DiffProcessorBuilder) WithSuccessfulPerformDiffWithChanges added in v0.6.0

func (b *DiffProcessorBuilder) WithSuccessfulPerformDiffWithChanges() *DiffProcessorBuilder

WithSuccessfulPerformDiffWithChanges sets a successful PerformDiff implementation with diffs.

type DownstreamChanges added in v0.7.0

type DownstreamChanges struct {
	Summary Summary        `json:"summary"`
	Changes []ChangeDetail `json:"changes"`
}

DownstreamChanges mirrors renderer.DownstreamChanges.

type DownstreamResourceExpectation added in v0.7.0

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

DownstreamResourceExpectation defines expectations for a downstream resource change.

func (*DownstreamResourceExpectation) AndComposition added in v0.11.0

AndComposition starts an expectation for another composition, from anywhere in the current composition's chain. It exists because the only climb a caller genuinely needs is the one back to the root to add a sibling — every other And()/AndXR()/AndComp() is avoidable, since the assert functions accept any builder level. Spelling the sibling case as one intention-named call keeps a multi-composition expectation readable instead of ending each composition with a run of climbs whose purpose is not obvious from reading them.

func (*DownstreamResourceExpectation) AndXR added in v0.7.0

AndXR returns to parent to chain more downstream resource expectations. Not needed at the end of a chain - AssertStructuredCompDiff accepts DownstreamResourceExpectation directly.

func (*DownstreamResourceExpectation) WithAnyName added in v0.7.0

WithAnyName allows any resource name (useful for generated names).

func (*DownstreamResourceExpectation) WithDryRunPerformed added in v0.11.0

WithDryRunPerformed asserts this downstream change carries NO dryRun object, i.e. its desired state did go through the apiserver. See the ResourceExpectation counterpart for why the happy path is worth asserting explicitly.

func (*DownstreamResourceExpectation) WithDryRunSkipped added in v0.11.0

func (d *DownstreamResourceExpectation) WithDryRunSkipped(reason, detailSubstring string) *DownstreamResourceExpectation

WithDryRunSkipped asserts this downstream change reports that its desired state was NOT verified against the apiserver, for the given reason (one of the dt.DryRunSkipReason values: "disabled", "forbidden", "webhookUnavailable").

Pass a detailSubstring to additionally require that the cluster's own explanation was propagated rather than swallowed; pass "" to skip that check.

func (*DownstreamResourceExpectation) WithField added in v0.7.0

WithField asserts a specific field exists with exact value (for added/removed resources).

func (*DownstreamResourceExpectation) WithFieldAdded added in v0.7.0

WithFieldAdded asserts a field was added (for modified resources). Equivalent to WithFieldChange(path, nil, value).

func (*DownstreamResourceExpectation) WithFieldChange added in v0.7.0

func (d *DownstreamResourceExpectation) WithFieldChange(path string, oldValue, newValue any) *DownstreamResourceExpectation

WithFieldChange asserts a field changed from old to new value (for modified resources).

func (*DownstreamResourceExpectation) WithFieldRemoved added in v0.7.0

func (d *DownstreamResourceExpectation) WithFieldRemoved(path string, value any) *DownstreamResourceExpectation

WithFieldRemoved asserts a field was removed (for modified resources). Equivalent to WithFieldChange(path, value, nil).

func (*DownstreamResourceExpectation) WithFieldValuePattern added in v0.7.0

func (d *DownstreamResourceExpectation) WithFieldValuePattern(path, pattern string) *DownstreamResourceExpectation

WithFieldValuePattern asserts a field value matches a regex pattern. Use this for fields with generated/dynamic values like resource names with random suffixes.

func (*DownstreamResourceExpectation) WithNamePattern added in v0.7.0

WithNamePattern matches resource name against a regex pattern.

type DryRunInfo added in v0.11.0

type DryRunInfo struct {
	Performed      bool   `json:"performed"`
	SkipReason     string `json:"skipReason,omitempty"`
	Detail         string `json:"detail,omitempty"`
	StorageVersion string `json:"storageVersion,omitempty"`
}

DryRunInfo mirrors dt.DryRunInfo. Absent (nil) means the resource's desired state was verified against the apiserver; see WithDryRunSkipped / WithDryRunPerformed.

type ErrorExpectation added in v0.8.0

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

ErrorExpectation describes one expected entry in the structured errors[] payload. Match is by ResourceID; ValidationFailures, when non-nil, asserts the per-resource typed validation breakdown.

func (*ErrorExpectation) AndError added in v0.8.0

func (e *ErrorExpectation) AndError() *ExpectedDiff

AndError returns to the parent ExpectedDiff to chain another WithError call, mirroring the AndXR / AndComp helpers elsewhere in this file.

func (*ErrorExpectation) WithMessageContaining added in v0.8.0

func (e *ErrorExpectation) WithMessageContaining(s string) *ErrorExpectation

WithMessageContaining adds a substring assertion on the error's Message field. Optional — useful when machine consumers care about the human-readable message too.

func (*ErrorExpectation) WithValidationFailure added in v0.8.0

func (e *ErrorExpectation) WithValidationFailure(apiVersion, kind, name, namespace string) *ValidationFailureExpectation

WithValidationFailure adds an expectation for one entry in the error's validationFailures[] slice, matched by APIVersion/Kind/Name. namespace is optional (empty string skips the namespace assertion); pass the actual namespace to lock down namespaced resources.

type ExpectedCompDiff added in v0.7.0

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

ExpectedCompDiff is a fluent builder for test expectations on composition diff output.

func ExpectCompDiff added in v0.7.0

func ExpectCompDiff() *ExpectedCompDiff

ExpectCompDiff creates a new ExpectedCompDiff builder.

func (*ExpectedCompDiff) WithComposition added in v0.7.0

func (e *ExpectedCompDiff) WithComposition(name string) *CompositionExpectation

WithComposition adds an expectation for a composition.

func (*ExpectedCompDiff) WithError added in v0.11.0

func (e *ExpectedCompDiff) WithError(resourceID string) *ExpectedCompDiff

WithError asserts the top-level errors[] contains an error with the given resourceID.

func (*ExpectedCompDiff) WithNoWarnings added in v0.11.0

func (e *ExpectedCompDiff) WithNoWarnings() *ExpectedCompDiff

WithNoWarnings asserts that structured output carries no advisories at all. Distinct from simply declaring no WithWarning expectations, which asserts nothing: this is how a test pins that a condition the tool warns about elsewhere is correctly silent here.

func (*ExpectedCompDiff) WithOutputVersion added in v0.11.0

func (e *ExpectedCompDiff) WithOutputVersion(version string) *ExpectedCompDiff

WithOutputVersion asserts the document's outputVersion ("v1" or "v2"), and that each composition and impactAnalysis[] entry carries exactly that version's fields.

func (*ExpectedCompDiff) WithWarning added in v0.11.0

func (e *ExpectedCompDiff) WithWarning(messageContains string) *CompWarningExpectation

WithWarning asserts that structured output carries a warning whose message contains the supplied substring. Chain WithWarningContext to pin the machine-readable context pairs.

type ExpectedDiff added in v0.7.0

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

ExpectedDiff is a fluent builder for test expectations on structured diff output.

func ExpectDiff added in v0.7.0

func ExpectDiff() *ExpectedDiff

ExpectDiff creates a new ExpectedDiff builder.

func (*ExpectedDiff) Build added in v0.10.0

func (e *ExpectedDiff) Build() *ExpectedDiff

Build terminates the chain and returns the root expectation. Optional — AssertStructuredDiff accepts an *ExpectedDiff directly — but it reads as an explicit "done building" marker.

func (*ExpectedDiff) WithAddedResource added in v0.7.0

func (e *ExpectedDiff) WithAddedResource(kind, name, namespace string) *ResourceExpectation

WithAddedResource adds an expectation for an added resource.

func (*ExpectedDiff) WithError added in v0.8.0

func (e *ExpectedDiff) WithError(resourceID string) *ErrorExpectation

WithError attaches an expectation for an entry in the structured errors[] payload, matched by resourceID. Use the returned ErrorExpectation to add validationFailures expectations.

func (*ExpectedDiff) WithModifiedResource added in v0.7.0

func (e *ExpectedDiff) WithModifiedResource(kind, name, namespace string) *ResourceExpectation

WithModifiedResource adds an expectation for a modified resource.

func (*ExpectedDiff) WithNoWarnings added in v0.11.0

func (e *ExpectedDiff) WithNoWarnings() *ExpectedDiff

WithNoWarnings asserts that structured output carries no advisories at all. Distinct from simply declaring no WithWarning expectations, which asserts nothing: this is how a test pins that a condition the tool used to warn about is correctly silent.

func (*ExpectedDiff) WithOutputVersion added in v0.11.0

func (e *ExpectedDiff) WithOutputVersion(version string) *ExpectedDiff

WithOutputVersion asserts the document's outputVersion ("v1" or "v2") and its shape: v1 carries the flat changes[], v2 does not. Under v2, assert changes per XR with WithXRs; the top-level resource expectations (WithAddedResource and friends) read the flat view and so are rejected.

func (*ExpectedDiff) WithRemovedResource added in v0.7.0

func (e *ExpectedDiff) WithRemovedResource(kind, name, namespace string) *ResourceExpectation

WithRemovedResource adds an expectation for a removed resource.

func (*ExpectedDiff) WithSummary added in v0.7.0

func (e *ExpectedDiff) WithSummary(added, modified, removed int) *ExpectedDiff

WithSummary sets the expected summary counts.

func (*ExpectedDiff) WithWarning added in v0.11.0

func (e *ExpectedDiff) WithWarning(messageContains string) *WarningExpectation

WithWarning asserts that structured output carries a warning whose message contains the supplied substring. Chain WithWarningContext to pin the machine-readable context pairs.

func (*ExpectedDiff) WithXRs added in v0.10.0

func (e *ExpectedDiff) WithXRs(xrs ...xrSpec) *ExpectedDiff

WithXRs attaches per-input-XR expectations (built via XR(...)) to assert against the xrs[] grouped view, in order.

type FakeDocker added in v0.11.0

type FakeDocker struct {
	Containers []container.Summary
	Networks   []network.Summary

	// ListErr and NetworkListErr fail every container and network list.
	ListErr, NetworkListErr error
	// RemoveErr fails removing the container or network with that ID, which stays.
	RemoveErr map[string]error
	// Vanished holds the IDs of containers and networks that are listed but gone by the time they are
	// removed, as when a concurrent run removed them first.
	Vanished map[string]bool
}

FakeDocker is an in-memory Docker daemon: it holds containers and networks, and implements the subset of the Docker API client that dockerrun.Docker names. It behaves as the daemon does wherever the difference would change which resources are left: listing applies label filters (a resource matches only if it carries every one) and, without All, lists only running containers; a running container is only removed with Force; and a network is not removed while a container is attached to it. A test sets up the host, runs the code, and asserts what is left.

func (*FakeDocker) Close added in v0.11.0

func (f *FakeDocker) Close() error

Close does nothing: the fake holds no connection.

func (*FakeDocker) ContainerIDs added in v0.11.0

func (f *FakeDocker) ContainerIDs() []string

ContainerIDs returns the IDs of the containers on the host, sorted.

func (*FakeDocker) ContainerList added in v0.11.0

ContainerList lists the containers matching opts' filters; without opts.All, only running ones.

func (*FakeDocker) ContainerRemove added in v0.11.0

ContainerRemove removes the container with ID id.

func (*FakeDocker) NetworkList added in v0.11.0

NetworkList lists the networks matching opts' filters.

func (*FakeDocker) NetworkNames added in v0.11.0

func (f *FakeDocker) NetworkNames() []string

NetworkNames returns the names of the networks on the host, sorted.

func (*FakeDocker) NetworkRemove added in v0.11.0

NetworkRemove removes the network with ID or name id, unless a container is attached to it.

type FieldErrorExpectation added in v0.8.0

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

FieldErrorExpectation describes one expected entry in errors[].validationFailures[].errors[]. Match is by Type+Field (Field may be empty for non-localized errors); messageContains and value are optional refinements.

func (*FieldErrorExpectation) AndFieldError added in v0.8.0

AndFieldError returns to the parent ValidationFailureExpectation to chain another WithFieldError.

func (*FieldErrorExpectation) WithMessageContaining added in v0.8.0

func (f *FieldErrorExpectation) WithMessageContaining(s string) *FieldErrorExpectation

WithMessageContaining adds a substring assertion on this field error's Message. Optional.

func (*FieldErrorExpectation) WithValue added in v0.8.0

WithValue pins the bad value on this field error. Pass the value as it would arrive after JSON decoding (e.g. float64 for numbers, string for strings); for "any number is fine" omit this method.

type FieldValidationError added in v0.8.0

type FieldValidationError struct {
	Type    string `json:"type"`
	Field   string `json:"field,omitempty"`
	Message string `json:"message"`
	Value   any    `json:"value,omitempty"`
}

FieldValidationError mirrors dt.FieldValidationError.

type MockAccessChecker added in v0.11.0

type MockAccessChecker struct {
	CanFn func(ctx context.Context, gvk schema.GroupVersionKind, namespace string, verb types.Verb) (bool, string, error)
}

MockAccessChecker implements the kubernetes.AccessChecker interface.

func (*MockAccessChecker) Can added in v0.11.0

func (m *MockAccessChecker) Can(ctx context.Context, gvk schema.GroupVersionKind, namespace string, verb types.Verb) (bool, string, error)

Can implements kubernetes.AccessChecker.

The unset default is "allowed", not an error, and that is deliberate. The production code only consults the authorizer after a dry run has already come back Forbidden, and "allowed" is the answer that routes such a 403 to the cluster-rejection path. So a test that wires a Forbidden without saying anything about authorization gets the rejection behaviour rather than a confusing "Can not implemented" failure from a collaborator it never meant to exercise.

type MockAccessCheckerBuilder added in v0.11.0

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

MockAccessCheckerBuilder helps build kubernetes.AccessChecker mocks.

func NewMockAccessChecker added in v0.11.0

func NewMockAccessChecker() *MockAccessCheckerBuilder

NewMockAccessChecker creates a new MockAccessCheckerBuilder. With no further calls the mock allows everything — see MockAccessChecker.Can for why that is the right default.

func (*MockAccessCheckerBuilder) Build added in v0.11.0

Build returns the built mock.

func (*MockAccessCheckerBuilder) WithAllowed added in v0.11.0

WithAllowed makes every authorization check succeed.

func (*MockAccessCheckerBuilder) WithCan added in v0.11.0

WithCan sets the Can behavior.

func (*MockAccessCheckerBuilder) WithDenied added in v0.11.0

WithDenied makes every authorization check report that we are not permitted, with the given reason. This is what turns a Forbidden dry-run into a graceful per-resource degradation rather than a reported cluster rejection.

func (*MockAccessCheckerBuilder) WithDeniedVerb added in v0.11.0

func (b *MockAccessCheckerBuilder) WithDeniedVerb(deniedVerb dtypes.Verb, reason string) *MockAccessCheckerBuilder

WithDeniedVerb denies only the named verb and allows everything else. A user holding patch but not create is the exact configuration this feature exists to cope with, so it needs to be expressible.

func (*MockAccessCheckerBuilder) WithFailedCheck added in v0.11.0

func (b *MockAccessCheckerBuilder) WithFailedCheck(err error) *MockAccessCheckerBuilder

WithFailedCheck makes the authorization check itself fail, leaving a Forbidden dry-run unclassifiable.

type MockApplyClient

type MockApplyClient struct {
	InitializeFn   func(ctx context.Context) error
	ApplyFn        func(ctx context.Context, obj *un.Unstructured) (*un.Unstructured, error)
	DryRunApplyFn  func(ctx context.Context, obj *un.Unstructured, fieldOwner string) (*un.Unstructured, error)
	DryRunCreateFn func(ctx context.Context, obj *un.Unstructured) (*un.Unstructured, error)
}

MockApplyClient implements the kubernetes.ApplyClient interface.

func (*MockApplyClient) Apply

Apply implements kubernetes.ApplyClient.

func (*MockApplyClient) DryRunApply

func (m *MockApplyClient) DryRunApply(ctx context.Context, obj *un.Unstructured, fieldOwner string) (*un.Unstructured, error)

DryRunApply implements kubernetes.ApplyClient.

func (*MockApplyClient) DryRunCreate added in v0.11.0

func (m *MockApplyClient) DryRunCreate(ctx context.Context, obj *un.Unstructured) (*un.Unstructured, error)

DryRunCreate implements kubernetes.ApplyClient.

func (*MockApplyClient) Initialize

func (m *MockApplyClient) Initialize(ctx context.Context) error

Initialize implements kubernetes.ApplyClient.

type MockApplyClientBuilder

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

MockApplyClientBuilder helps build kubernetes.ApplyClient mocks.

func NewMockApplyClient

func NewMockApplyClient() *MockApplyClientBuilder

NewMockApplyClient creates a new MockApplyClientBuilder.

func (*MockApplyClientBuilder) Build

Build returns the built mock.

func (*MockApplyClientBuilder) WithApply

WithApply sets the Apply behavior.

func (*MockApplyClientBuilder) WithDryRunApply

WithDryRunApply sets the DryRunApply behavior.

func (*MockApplyClientBuilder) WithDryRunCreate added in v0.11.0

WithDryRunCreate sets the DryRunCreate behavior.

func (*MockApplyClientBuilder) WithFailedDryRun

func (b *MockApplyClientBuilder) WithFailedDryRun(errMsg string) *MockApplyClientBuilder

WithFailedDryRun sets DryRunApply to return an error.

func (*MockApplyClientBuilder) WithFailedDryRunCreate added in v0.11.0

func (b *MockApplyClientBuilder) WithFailedDryRunCreate(errMsg string) *MockApplyClientBuilder

WithFailedDryRunCreate sets DryRunCreate to return an error.

func (*MockApplyClientBuilder) WithInitialize

func (b *MockApplyClientBuilder) WithInitialize(fn func(context.Context) error) *MockApplyClientBuilder

WithInitialize sets the Initialize behavior.

func (*MockApplyClientBuilder) WithSuccessfulDryRun

func (b *MockApplyClientBuilder) WithSuccessfulDryRun() *MockApplyClientBuilder

WithSuccessfulDryRun sets DryRunApply to return the input resource.

func (*MockApplyClientBuilder) WithSuccessfulDryRunCreate added in v0.11.0

func (b *MockApplyClientBuilder) WithSuccessfulDryRunCreate() *MockApplyClientBuilder

WithSuccessfulDryRunCreate sets DryRunCreate to return the input resource.

type MockCompositionClient

type MockCompositionClient struct {
	InitializeFn              func(ctx context.Context) error
	FindMatchingCompositionFn func(ctx context.Context, res *un.Unstructured) (types.ResolvedComposition, error)
	ListCompositionsFn        func(ctx context.Context) ([]*xpextv1.Composition, error)
	GetCompositionFn          func(ctx context.Context, name string) (*xpextv1.Composition, error)
	FindCompositesFn          func(ctx context.Context, comp *un.Unstructured, opts types.FindCompositesOptions) ([]*un.Unstructured, error)
}

MockCompositionClient implements the crossplane.CompositionClient interface.

func (*MockCompositionClient) FindComposites added in v0.8.0

FindComposites implements crossplane.CompositionClient.

func (*MockCompositionClient) FindMatchingComposition

func (m *MockCompositionClient) FindMatchingComposition(ctx context.Context, res *un.Unstructured) (types.ResolvedComposition, error)

FindMatchingComposition implements crossplane.CompositionClient.

func (*MockCompositionClient) GetComposition

func (m *MockCompositionClient) GetComposition(ctx context.Context, name string) (*xpextv1.Composition, error)

GetComposition implements crossplane.CompositionClient.

func (*MockCompositionClient) Initialize

func (m *MockCompositionClient) Initialize(ctx context.Context) error

Initialize implements crossplane.CompositionClient.

func (*MockCompositionClient) ListCompositions

func (m *MockCompositionClient) ListCompositions(ctx context.Context) ([]*xpextv1.Composition, error)

ListCompositions implements crossplane.CompositionClient.

type MockCompositionClientBuilder

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

MockCompositionClientBuilder helps build crossplane.CompositionClient mocks.

func NewMockCompositionClient

func NewMockCompositionClient() *MockCompositionClientBuilder

NewMockCompositionClient creates a new MockCompositionClientBuilder.

func (*MockCompositionClientBuilder) Build

Build returns the built mock.

func (*MockCompositionClientBuilder) WithCompositesByRef added in v0.8.0

func (b *MockCompositionClientBuilder) WithCompositesByRef(matched ...*un.Unstructured) *MockCompositionClientBuilder

WithCompositesByRef sets FindComposites (refs mode) to return the given resources for any non-empty-Refs request. Default-discovery calls return an explicit error identifying this helper as refs-only — use WithFindComposites directly if you need to mock both modes. Mirror of WithResourcesForComposition for the refs-mode side.

func (*MockCompositionClientBuilder) WithComposition added in v0.3.0

WithComposition is an alias for WithSuccessfulCompositionMatch for convenience.

func (*MockCompositionClientBuilder) WithFailedInitialize

func (b *MockCompositionClientBuilder) WithFailedInitialize(errMsg string) *MockCompositionClientBuilder

WithFailedInitialize mocks a failed call to Initialize.

func (*MockCompositionClientBuilder) WithFindComposites added in v0.8.0

WithFindComposites sets the FindComposites behavior.

func (*MockCompositionClientBuilder) WithFindMatchingComposition

WithFindMatchingComposition sets the FindMatchingComposition behavior.

func (*MockCompositionClientBuilder) WithFindResourcesError added in v0.5.0

func (b *MockCompositionClientBuilder) WithFindResourcesError(errMsg string) *MockCompositionClientBuilder

WithFindResourcesError sets FindComposites (default-discovery mode) to return an error. Refs-mode calls return an explicit error identifying this helper as default-discovery only — use WithFindComposites directly if you need to mock both modes.

func (*MockCompositionClientBuilder) WithGetComposition

WithGetComposition sets the GetComposition behavior.

func (*MockCompositionClientBuilder) WithInitialize

WithInitialize sets the Initialize behavior.

func (*MockCompositionClientBuilder) WithListCompositions

WithListCompositions sets the ListCompositions behavior.

func (*MockCompositionClientBuilder) WithNoMatchingComposites added in v0.8.0

func (b *MockCompositionClientBuilder) WithNoMatchingComposites() *MockCompositionClientBuilder

WithNoMatchingComposites sets FindComposites to return an empty matched set regardless of mode (default-discovery or refs). Use for "nothing matches anywhere" tests where neither default nor refs lookup should produce results. Mirrors WithNoMatchingComposition for the FindMatchingComposition method.

func (*MockCompositionClientBuilder) WithNoMatchingComposition

func (b *MockCompositionClientBuilder) WithNoMatchingComposition() *MockCompositionClientBuilder

WithNoMatchingComposition sets FindMatchingComposition to return "not found".

func (*MockCompositionClientBuilder) WithResourcesForComposition added in v0.5.0

func (b *MockCompositionClientBuilder) WithResourcesForComposition(compositionName, namespace string, resources []*un.Unstructured) *MockCompositionClientBuilder

WithResourcesForComposition sets FindComposites (default-discovery mode) to return specific resources for a given composition name and namespace. Refs-mode calls return an explicit error identifying this helper as default-discovery only — use WithFindComposites directly if you need to mock both modes.

func (*MockCompositionClientBuilder) WithSuccessfulCompositionFetch added in v0.2.0

func (b *MockCompositionClientBuilder) WithSuccessfulCompositionFetch(comp *xpextv1.Composition) *MockCompositionClientBuilder

WithSuccessfulCompositionFetch sets up a successful composition fetch.

func (*MockCompositionClientBuilder) WithSuccessfulCompositionFetches added in v0.2.0

func (b *MockCompositionClientBuilder) WithSuccessfulCompositionFetches(comps []*xpextv1.Composition) *MockCompositionClientBuilder

WithSuccessfulCompositionFetches sets up successful composition fetches for multiple compositions.

func (*MockCompositionClientBuilder) WithSuccessfulCompositionMatch

func (b *MockCompositionClientBuilder) WithSuccessfulCompositionMatch(comp *xpextv1.Composition) *MockCompositionClientBuilder

WithSuccessfulCompositionMatch sets FindMatchingComposition to return a specific composition, with no revision resolved.

func (*MockCompositionClientBuilder) WithSuccessfulInitialize

func (b *MockCompositionClientBuilder) WithSuccessfulInitialize() *MockCompositionClientBuilder

WithSuccessfulInitialize mocks a successful call to Initialize.

type MockCompositionProvider added in v0.5.0

type MockCompositionProvider struct {
	GetCompositionFn func() (*xpextv1.Composition, error)
}

MockCompositionProvider provides a mock implementation for CompositionProvider.

func (*MockCompositionProvider) GetComposition added in v0.5.0

func (m *MockCompositionProvider) GetComposition() (*xpextv1.Composition, error)

GetComposition implements GetComposition from the CompositionProvider interface.

type MockCredentialClient added in v0.6.0

type MockCredentialClient struct {
	FetchCompositionCredentialsFn func(ctx context.Context, comp *xpextv1.Composition) (types.CredentialFetchResult, error)
}

MockCredentialClient implements the crossplane.CredentialClient interface.

func (*MockCredentialClient) FetchCompositionCredentials added in v0.6.0

func (m *MockCredentialClient) FetchCompositionCredentials(ctx context.Context, comp *xpextv1.Composition) (types.CredentialFetchResult, error)

FetchCompositionCredentials implements crossplane.CredentialClient.

type MockDefaulter added in v0.11.0

type MockDefaulter struct {
	DefaultFn func(ctx context.Context, obj *un.Unstructured) (*un.Unstructured, string, error)
}

MockDefaulter Mock defaulter. With no DefaultFn it applies no defaults, returning a copy of its input unchanged.

func (*MockDefaulter) Default added in v0.11.0

func (m *MockDefaulter) Default(ctx context.Context, obj *un.Unstructured) (*un.Unstructured, string, error)

Default returns a copy of obj with predicted CRD defaults applied, and the storage version of its CRD when that is not obj's own (none, without a DefaultFn).

type MockDefinitionClient

type MockDefinitionClient struct {
	InitializeFn         func(ctx context.Context) error
	GetXRDsFn            func(ctx context.Context) ([]*un.Unstructured, error)
	GetXRDForClaimFn     func(ctx context.Context, gvk schema.GroupVersionKind) (*un.Unstructured, error)
	GetXRDForXRFn        func(ctx context.Context, gvk schema.GroupVersionKind) (*un.Unstructured, error)
	IsClaimResourceFn    func(ctx context.Context, resource *un.Unstructured) bool
	GetCompositeSchemaFn func(ctx context.Context, gvk schema.GroupVersionKind) (cmp.Schema, error)
}

MockDefinitionClient implements the crossplane.DefinitionClient interface.

func (*MockDefinitionClient) GetCompositeSchema added in v0.8.0

func (m *MockDefinitionClient) GetCompositeSchema(ctx context.Context, gvk schema.GroupVersionKind) (cmp.Schema, error)

GetCompositeSchema implements crossplane.DefinitionClient.

func (*MockDefinitionClient) GetXRDForClaim

GetXRDForClaim implements crossplane.DefinitionClient.

func (*MockDefinitionClient) GetXRDForXR

GetXRDForXR implements crossplane.DefinitionClient.

func (*MockDefinitionClient) GetXRDs

func (m *MockDefinitionClient) GetXRDs(ctx context.Context) ([]*un.Unstructured, error)

GetXRDs implements crossplane.DefinitionClient.

func (*MockDefinitionClient) Initialize

func (m *MockDefinitionClient) Initialize(ctx context.Context) error

Initialize implements crossplane.DefinitionClient.

func (*MockDefinitionClient) IsClaimResource added in v0.2.0

func (m *MockDefinitionClient) IsClaimResource(ctx context.Context, resource *un.Unstructured) bool

IsClaimResource implements crossplane.DefinitionClient.

type MockDefinitionClientBuilder

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

MockDefinitionClientBuilder helps build crossplane.DefinitionClient mocks.

func NewMockDefinitionClient

func NewMockDefinitionClient() *MockDefinitionClientBuilder

NewMockDefinitionClient creates a new MockDefinitionClientBuilder.

func (*MockDefinitionClientBuilder) Build

Build returns the built mock. If WithXRDForGVK was used to add XRD mappings, this will configure GetXRDForXR to use those mappings.

func (*MockDefinitionClientBuilder) WithEmptyXRDsFetch

WithEmptyXRDsFetch sets GetXRDs to return an empty set of XRDs.

func (*MockDefinitionClientBuilder) WithFailedInitialize

func (b *MockDefinitionClientBuilder) WithFailedInitialize(errMsg string) *MockDefinitionClientBuilder

WithFailedInitialize mocks a failed call to Initialize.

func (*MockDefinitionClientBuilder) WithFailedXRDsFetch

func (b *MockDefinitionClientBuilder) WithFailedXRDsFetch(errMsg string) *MockDefinitionClientBuilder

WithFailedXRDsFetch sets GetXRDs to return an error.

func (*MockDefinitionClientBuilder) WithGetXRDForClaim

WithGetXRDForClaim sets the GetXRDForClaim behavior.

func (*MockDefinitionClientBuilder) WithGetXRDForXR

WithGetXRDForXR sets the GetXRDForXR behavior.

func (*MockDefinitionClientBuilder) WithGetXRDs

WithGetXRDs sets the GetXRDs behavior.

func (*MockDefinitionClientBuilder) WithInitialize

WithInitialize sets the Initialize behavior.

func (*MockDefinitionClientBuilder) WithIsClaimResource added in v0.2.0

WithIsClaimResource sets the IsClaimResource behavior.

func (*MockDefinitionClientBuilder) WithSuccessfulInitialize

func (b *MockDefinitionClientBuilder) WithSuccessfulInitialize() *MockDefinitionClientBuilder

WithSuccessfulInitialize mocks a successful call to Initialize.

func (*MockDefinitionClientBuilder) WithSuccessfulXRDsFetch

func (b *MockDefinitionClientBuilder) WithSuccessfulXRDsFetch(xrds []*un.Unstructured) *MockDefinitionClientBuilder

WithSuccessfulXRDsFetch sets GetXRDs to return specific XRDs.

func (*MockDefinitionClientBuilder) WithV1XRDForXR

WithV1XRDForXR sets the GetXRDForXR behavior to return a v1 XRD.

func (*MockDefinitionClientBuilder) WithV2XRDForXR

WithV2XRDForXR sets the GetXRDForXR behavior to return a v1 XRD.

func (*MockDefinitionClientBuilder) WithXRD added in v0.3.0

WithXRD sets the GetXRDForXR behavior to return the specified XRD for any GVK matching its group/kind.

func (*MockDefinitionClientBuilder) WithXRDForClaim

func (b *MockDefinitionClientBuilder) WithXRDForClaim(unstructured *un.Unstructured) *MockDefinitionClientBuilder

WithXRDForClaim sets the GetXRDForXR behavior to return the specified XR.

func (*MockDefinitionClientBuilder) WithXRDForGVK added in v0.3.0

WithXRDForGVK adds an XRD to be returned for a specific GVK. This method can be called multiple times to add different XRDs for different GVKs. When Build() is called, GetXRDForXR will use the accumulated XRD mappings.

func (*MockDefinitionClientBuilder) WithXRDForXR

WithXRDForXR sets the GetXRDForXR behavior to return the specified XR.

func (*MockDefinitionClientBuilder) WithXRDForXRError added in v0.3.0

WithXRDForXRError sets GetXRDForXR to return the specified error.

func (*MockDefinitionClientBuilder) WithXRDForXRNotFound added in v0.3.0

func (b *MockDefinitionClientBuilder) WithXRDForXRNotFound() *MockDefinitionClientBuilder

WithXRDForXRNotFound sets GetXRDForXR to return not found error for any GVK.

func (*MockDefinitionClientBuilder) WithXRDForXRNotFoundForGVK added in v0.3.0

func (b *MockDefinitionClientBuilder) WithXRDForXRNotFoundForGVK(notFoundGVK schema.GroupVersionKind) *MockDefinitionClientBuilder

WithXRDForXRNotFoundForGVK sets GetXRDForXR to return not found for a specific GVK.

type MockDiffCalculator

type MockDiffCalculator struct {
	CalculateDiffFn                 func(context.Context, *un.Unstructured, *un.Unstructured) (*dt.ResourceDiff, error)
	CalculateDiffsFn                func(context.Context, *cmp.Unstructured, render.CompositionOutputs) (map[string]*dt.ResourceDiff, error)
	CalculateNonRemovalDiffsFn      func(context.Context, *cmp.Unstructured, render.CompositionOutputs) (map[string]*dt.ResourceDiff, types.RenderedResources, error)
	CalculateRemovedResourceDiffsFn func(context.Context, *un.Unstructured, types.RenderedResources) (map[string]*dt.ResourceDiff, error)
}

MockDiffCalculator is a mock implementation of DiffCalculator for testing.

func (*MockDiffCalculator) CalculateDiff

func (m *MockDiffCalculator) CalculateDiff(ctx context.Context, composite *un.Unstructured, desired *un.Unstructured) (*dt.ResourceDiff, error)

CalculateDiff implements DiffCalculator.

func (*MockDiffCalculator) CalculateDiffs

func (m *MockDiffCalculator) CalculateDiffs(ctx context.Context, xr *cmp.Unstructured, desired render.CompositionOutputs) (map[string]*dt.ResourceDiff, error)

CalculateDiffs implements DiffCalculator.

func (*MockDiffCalculator) CalculateNonRemovalDiffs added in v0.5.0

CalculateNonRemovalDiffs implements DiffCalculator.

func (*MockDiffCalculator) CalculateRemovedResourceDiffs

func (m *MockDiffCalculator) CalculateRemovedResourceDiffs(ctx context.Context, xr *un.Unstructured, rendered types.RenderedResources) (map[string]*dt.ResourceDiff, error)

CalculateRemovedResourceDiffs implements DiffCalculator.

type MockDiffProcessor

type MockDiffProcessor struct {
	// Function fields for mocking behavior
	InitializeFn         func(ctx context.Context) error
	PerformDiffFn        func(ctx context.Context, resources []*un.Unstructured, compositionProvider types.CompositionProvider) (bool, error)
	DiffSingleResourceFn func(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, error)
	CleanupFn            func(ctx context.Context) error
}

MockDiffProcessor implements the DiffProcessor interface for testing.

func (*MockDiffProcessor) Cleanup added in v0.7.0

func (m *MockDiffProcessor) Cleanup(ctx context.Context) error

Cleanup implements the DiffProcessor.Cleanup method.

func (*MockDiffProcessor) DiffSingleResource added in v0.5.0

func (m *MockDiffProcessor) DiffSingleResource(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, error)

DiffSingleResource implements the DiffProcessor.DiffSingleResource method.

func (*MockDiffProcessor) Initialize

func (m *MockDiffProcessor) Initialize(ctx context.Context) error

Initialize implements the DiffProcessor interface.

func (*MockDiffProcessor) PerformDiff

func (m *MockDiffProcessor) PerformDiff(ctx context.Context, resources []*un.Unstructured, compositionProvider types.CompositionProvider) (bool, error)

PerformDiff implements the DiffProcessor.PerformDiff method.

type MockDiffRenderer

type MockDiffRenderer struct {
	RenderDiffsFn func([]dt.XRDiffGroup, []dt.OutputError, []dt.OutputWarning) error
}

MockDiffRenderer provides a mock implementation for DiffRenderer.

func (*MockDiffRenderer) RenderDiffs

func (m *MockDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.OutputError, warnings []dt.OutputWarning) error

RenderDiffs implements RenderDiffs from the DiffRenderer interface.

type MockDynamicClient

type MockDynamicClient struct {
	ResourceFn func(gvr schema.GroupVersionResource) dynamic.NamespaceableResourceInterface
}

MockDynamicClient mocks the dynamic.Interface.

func (*MockDynamicClient) Resource

Resource implements the dynamic.Interface method.

type MockEnvironmentClient

type MockEnvironmentClient struct {
	InitializeFn            func(ctx context.Context) error
	GetEnvironmentConfigsFn func(ctx context.Context) ([]*un.Unstructured, error)
	GetEnvironmentConfigFn  func(ctx context.Context, name string) (*un.Unstructured, error)
}

MockEnvironmentClient implements the crossplane.EnvironmentClient interface.

func (*MockEnvironmentClient) GetEnvironmentConfig

func (m *MockEnvironmentClient) GetEnvironmentConfig(ctx context.Context, name string) (*un.Unstructured, error)

GetEnvironmentConfig implements crossplane.EnvironmentClient.

func (*MockEnvironmentClient) GetEnvironmentConfigs

func (m *MockEnvironmentClient) GetEnvironmentConfigs(ctx context.Context) ([]*un.Unstructured, error)

GetEnvironmentConfigs implements crossplane.EnvironmentClient.

func (*MockEnvironmentClient) Initialize

func (m *MockEnvironmentClient) Initialize(ctx context.Context) error

Initialize implements crossplane.EnvironmentClient.

type MockEnvironmentClientBuilder

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

MockEnvironmentClientBuilder helps build crossplane.EnvironmentClient mocks.

func NewMockEnvironmentClient

func NewMockEnvironmentClient() *MockEnvironmentClientBuilder

NewMockEnvironmentClient creates a new MockEnvironmentClientBuilder.

func (*MockEnvironmentClientBuilder) Build

Build returns the built mock.

func (*MockEnvironmentClientBuilder) WithFailedInitialize

func (b *MockEnvironmentClientBuilder) WithFailedInitialize(errMsg string) *MockEnvironmentClientBuilder

WithFailedInitialize mocks a failed call to Initialize.

func (*MockEnvironmentClientBuilder) WithGetEnvironmentConfig

WithGetEnvironmentConfig sets the GetEnvironmentConfig behavior.

func (*MockEnvironmentClientBuilder) WithGetEnvironmentConfigs

func (b *MockEnvironmentClientBuilder) WithGetEnvironmentConfigs(fn func(context.Context) ([]*un.Unstructured, error)) *MockEnvironmentClientBuilder

WithGetEnvironmentConfigs sets the GetEnvironmentConfigs behavior.

func (*MockEnvironmentClientBuilder) WithInitialize

WithInitialize sets the Initialize behavior.

func (*MockEnvironmentClientBuilder) WithNoEnvironmentConfigs added in v0.5.0

func (b *MockEnvironmentClientBuilder) WithNoEnvironmentConfigs() *MockEnvironmentClientBuilder

WithNoEnvironmentConfigs sets GetEnvironmentConfigs to return an empty list.

func (*MockEnvironmentClientBuilder) WithSuccessfulEnvironmentConfigsFetch

func (b *MockEnvironmentClientBuilder) WithSuccessfulEnvironmentConfigsFetch(configs []*un.Unstructured) *MockEnvironmentClientBuilder

WithSuccessfulEnvironmentConfigsFetch sets GetEnvironmentConfigs to return specific configs.

func (*MockEnvironmentClientBuilder) WithSuccessfulInitialize

func (b *MockEnvironmentClientBuilder) WithSuccessfulInitialize() *MockEnvironmentClientBuilder

WithSuccessfulInitialize mocks a successful call to Initialize.

type MockFunctionClient

type MockFunctionClient struct {
	InitializeFn               func(ctx context.Context) error
	GetFunctionsFromPipelineFn func(comp *xpextv1.Composition) ([]pkgv1.Function, error)
	ListFunctionsFn            func(ctx context.Context) ([]pkgv1.Function, error)
}

MockFunctionClient implements the crossplane.FunctionClient interface.

func (*MockFunctionClient) GetFunctionsFromPipeline

func (m *MockFunctionClient) GetFunctionsFromPipeline(comp *xpextv1.Composition) ([]pkgv1.Function, error)

GetFunctionsFromPipeline implements crossplane.FunctionClient.

func (*MockFunctionClient) Initialize

func (m *MockFunctionClient) Initialize(ctx context.Context) error

Initialize implements crossplane.FunctionClient.

func (*MockFunctionClient) ListFunctions

func (m *MockFunctionClient) ListFunctions(ctx context.Context) ([]pkgv1.Function, error)

ListFunctions implements crossplane.FunctionClient.

type MockFunctionClientBuilder

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

MockFunctionClientBuilder helps build crossplane.FunctionClient mocks.

func NewMockFunctionClient

func NewMockFunctionClient() *MockFunctionClientBuilder

NewMockFunctionClient creates a new MockFunctionClientBuilder.

func (*MockFunctionClientBuilder) Build

Build returns the built mock.

func (*MockFunctionClientBuilder) WithFailedFunctionsFetch

func (b *MockFunctionClientBuilder) WithFailedFunctionsFetch(errMsg string) *MockFunctionClientBuilder

WithFailedFunctionsFetch sets GetFunctionsFromPipeline to return an error.

func (*MockFunctionClientBuilder) WithFailedInitialize

func (b *MockFunctionClientBuilder) WithFailedInitialize(errMsg string) *MockFunctionClientBuilder

WithFailedInitialize mocks a failed call to Initialize.

func (*MockFunctionClientBuilder) WithFunctionsFetchCallback added in v0.5.0

func (b *MockFunctionClientBuilder) WithFunctionsFetchCallback(callback func() ([]pkgv1.Function, error)) *MockFunctionClientBuilder

WithFunctionsFetchCallback sets a callback that's called when GetFunctionsFromPipeline is invoked. This is useful for testing caching behavior by tracking how many times functions are fetched.

func (*MockFunctionClientBuilder) WithGetFunctionsFromPipeline

func (b *MockFunctionClientBuilder) WithGetFunctionsFromPipeline(fn func(*xpextv1.Composition) ([]pkgv1.Function, error)) *MockFunctionClientBuilder

WithGetFunctionsFromPipeline sets the GetFunctionsFromPipeline behavior.

func (*MockFunctionClientBuilder) WithInitialize

WithInitialize sets the Initialize behavior.

func (*MockFunctionClientBuilder) WithListFunctions

WithListFunctions sets the ListFunctions behavior.

func (*MockFunctionClientBuilder) WithNoFunctions added in v0.5.0

WithNoFunctions sets GetFunctionsFromPipeline to return an empty function list.

func (*MockFunctionClientBuilder) WithSuccessfulFunctionsFetch

func (b *MockFunctionClientBuilder) WithSuccessfulFunctionsFetch(functions []pkgv1.Function) *MockFunctionClientBuilder

WithSuccessfulFunctionsFetch sets GetFunctionsFromPipeline to return specific functions.

func (*MockFunctionClientBuilder) WithSuccessfulInitialize

func (b *MockFunctionClientBuilder) WithSuccessfulInitialize() *MockFunctionClientBuilder

WithSuccessfulInitialize mocks a successful call to Initialize.

type MockFunctionProvider added in v0.7.0

type MockFunctionProvider struct {
	GetFunctionsForCompositionFn func(comp *xpextv1.Composition) ([]pkgv1.Function, error)
	CleanupFn                    func(ctx context.Context) error
}

MockFunctionProvider provides a mock implementation for FunctionProvider.

func (*MockFunctionProvider) Cleanup added in v0.7.0

func (m *MockFunctionProvider) Cleanup(ctx context.Context) error

Cleanup implements FunctionProvider.

func (*MockFunctionProvider) GetFunctionsForComposition added in v0.7.0

func (m *MockFunctionProvider) GetFunctionsForComposition(comp *xpextv1.Composition) ([]pkgv1.Function, error)

GetFunctionsForComposition implements FunctionProvider.

type MockInputValidator added in v0.11.0

type MockInputValidator struct {
	ToRenderFn       func() []types.ValidatedInput
	RecordRenderFn   func(i int, rendered map[string]bool, err error)
	VerdictsFn       func(groups []dt.XRDiffGroup) []error
	RenderOverlapsFn func(groups []dt.XRDiffGroup) []error
}

MockInputValidator Mock input validator, for driving PerformDiff's wiring directly.

func (*MockInputValidator) RecordRender added in v0.11.0

func (m *MockInputValidator) RecordRender(i int, rendered map[string]bool, err error)

RecordRender records one render.

func (*MockInputValidator) RenderOverlaps added in v0.11.0

func (m *MockInputValidator) RenderOverlaps(groups []dt.XRDiffGroup) []error

RenderOverlaps returns the render-overlap errors; by default, none.

func (*MockInputValidator) ToRender added in v0.11.0

func (m *MockInputValidator) ToRender() []types.ValidatedInput

ToRender returns the inputs to render.

func (*MockInputValidator) Verdicts added in v0.11.0

func (m *MockInputValidator) Verdicts(groups []dt.XRDiffGroup) []error

Verdicts returns each group's final error; by default, none.

type MockNamespaceableResourceInterface

type MockNamespaceableResourceInterface struct {
	NamespaceFn func(namespace string) dynamic.ResourceInterface
	GetFn       func(ctx context.Context, name string, options metav1.GetOptions, subresources ...string) (*un.Unstructured, error)
	ListFn      func(ctx context.Context, opts metav1.ListOptions) (*un.UnstructuredList, error)
	CreateFn    func(ctx context.Context, obj *un.Unstructured, options metav1.CreateOptions, subresources ...string) (*un.Unstructured, error)
	UpdateFn    func(ctx context.Context, obj *un.Unstructured, options metav1.UpdateOptions, subresources ...string) (*un.Unstructured, error)
	DeleteFn    func(ctx context.Context, name string, options metav1.DeleteOptions, subresources ...string) error
	PatchFn     func(ctx context.Context, name string, pt k8stypes.PatchType, data []byte, options metav1.PatchOptions, subresources ...string) (*un.Unstructured, error)
}

MockNamespaceableResourceInterface implements dynamic.NamespaceableResourceInterface.

func (*MockNamespaceableResourceInterface) Apply

Apply implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) ApplyStatus

ApplyStatus implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) Create

Create implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) Delete

func (m *MockNamespaceableResourceInterface) Delete(ctx context.Context, name string, options metav1.DeleteOptions, subresources ...string) error

Delete implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) DeleteCollection

DeleteCollection implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) Get

func (m *MockNamespaceableResourceInterface) Get(ctx context.Context, name string, options metav1.GetOptions, subresources ...string) (*un.Unstructured, error)

Get implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) List

List implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) Namespace

Namespace implements dynamic.NamespaceableResourceInterface.

func (*MockNamespaceableResourceInterface) Patch

func (m *MockNamespaceableResourceInterface) Patch(ctx context.Context, name string, pt k8stypes.PatchType, data []byte, options metav1.PatchOptions, subresources ...string) (*un.Unstructured, error)

Patch implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) Update

Update implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) UpdateStatus

UpdateStatus implements dynamic.ResourceInterface.

func (*MockNamespaceableResourceInterface) Watch

Watch implements dynamic.ResourceInterface.

type MockResourceClient

type MockResourceClient struct {
	InitializeFn              func(ctx context.Context) error
	GetResourceFn             func(ctx context.Context, gvk schema.GroupVersionKind, namespace, name string) (*un.Unstructured, error)
	ListResourcesFn           func(ctx context.Context, gvk schema.GroupVersionKind, namespace string) ([]*un.Unstructured, error)
	GetResourcesByLabelFn     func(ctx context.Context, gvk schema.GroupVersionKind, namespace string, sel metav1.LabelSelector) ([]*un.Unstructured, error)
	GetAllResourcesByLabelsFn func(ctx context.Context, gvks []schema.GroupVersionKind, selectors []metav1.LabelSelector) ([]*un.Unstructured, error)
	GetGVKsForGroupKindFn     func(ctx context.Context, group, kind string) ([]schema.GroupVersionKind, error)
	IsNamespacedResourceFn    func(ctx context.Context, gvk schema.GroupVersionKind) (bool, error)
}

MockResourceClient implements the kubernetes.ResourceClient interface.

func (*MockResourceClient) GetAllResourcesByLabels

func (m *MockResourceClient) GetAllResourcesByLabels(ctx context.Context, gvks []schema.GroupVersionKind, selectors []metav1.LabelSelector) ([]*un.Unstructured, error)

GetAllResourcesByLabels implements kubernetes.ResourceClient.

func (*MockResourceClient) GetGVKsForGroupKind

func (m *MockResourceClient) GetGVKsForGroupKind(ctx context.Context, group, kind string) ([]schema.GroupVersionKind, error)

GetGVKsForGroupKind implements kubernetes.ResourceClient.

func (*MockResourceClient) GetResource

func (m *MockResourceClient) GetResource(ctx context.Context, gvk schema.GroupVersionKind, namespace, name string) (*un.Unstructured, error)

GetResource implements kubernetes.ResourceClient.

func (*MockResourceClient) GetResourcesByLabel

func (m *MockResourceClient) GetResourcesByLabel(ctx context.Context, gvk schema.GroupVersionKind, namespace string, sel metav1.LabelSelector) ([]*un.Unstructured, error)

GetResourcesByLabel implements kubernetes.ResourceClient.

func (*MockResourceClient) Initialize

func (m *MockResourceClient) Initialize(ctx context.Context) error

Initialize implements kubernetes.ResourceClient.

func (*MockResourceClient) IsNamespacedResource

func (m *MockResourceClient) IsNamespacedResource(ctx context.Context, gvk schema.GroupVersionKind) (bool, error)

IsNamespacedResource implements kubernetes.ResourceClient.

func (*MockResourceClient) ListResources

func (m *MockResourceClient) ListResources(ctx context.Context, gvk schema.GroupVersionKind, namespace string) ([]*un.Unstructured, error)

ListResources implements kubernetes.ResourceClient.

type MockResourceClientBuilder

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

MockResourceClientBuilder helps build kubernetes.ResourceClient mocks.

func NewMockResourceClient

func NewMockResourceClient() *MockResourceClientBuilder

NewMockResourceClient creates a new MockResourceClientBuilder.

func (*MockResourceClientBuilder) Build

Build returns the built mock.

func (*MockResourceClientBuilder) WithClusterScopedResource

func (b *MockResourceClientBuilder) WithClusterScopedResource(gvks ...schema.GroupVersionKind) *MockResourceClientBuilder

WithClusterScopedResource sets specific GVKs to be cluster-scoped.

Composes with WithNamespacedResource — see that method for details.

func (*MockResourceClientBuilder) WithEmptyListResources

func (b *MockResourceClientBuilder) WithEmptyListResources() *MockResourceClientBuilder

WithEmptyListResources mimics an empty but successful response.

func (*MockResourceClientBuilder) WithFoundGVKs

WithFoundGVKs sets the GetGVKsForGroupKind behavior.

func (*MockResourceClientBuilder) WithGetAllResourcesByLabels

WithGetAllResourcesByLabels sets the GetAllResourcesByLabels behavior.

func (*MockResourceClientBuilder) WithGetResource

WithGetResource sets the GetResource behavior.

func (*MockResourceClientBuilder) WithGetResourceError added in v0.8.0

func (b *MockResourceClientBuilder) WithGetResourceError(err error) *MockResourceClientBuilder

WithGetResourceError sets GetResource to always return the given error (for non-NotFound transport-failure scenarios; use WithResourceNotFound for clean 404 cases).

func (*MockResourceClientBuilder) WithGetResourcesByLabel

WithGetResourcesByLabel sets the GetResourcesByLabel behavior.

func (*MockResourceClientBuilder) WithInitialize

WithInitialize sets the Initialize behavior.

func (*MockResourceClientBuilder) WithIsNamespacedResource

WithIsNamespacedResource sets the IsNamespacedResource behavior.

func (*MockResourceClientBuilder) WithListResources

WithListResources sets the ListResources behavior.

func (*MockResourceClientBuilder) WithListResourcesFailure

func (b *MockResourceClientBuilder) WithListResourcesFailure(errorStr string) *MockResourceClientBuilder

WithListResourcesFailure mimics a failed response.

func (*MockResourceClientBuilder) WithNamespacedResource

func (b *MockResourceClientBuilder) WithNamespacedResource(gvks ...schema.GroupVersionKind) *MockResourceClientBuilder

WithNamespacedResource sets specific GVKs to be namespaced.

Composes with WithClusterScopedResource: each call adds to the set of known scopes rather than replacing it, so a single mock can describe a mix of namespaced and cluster-scoped kinds. GVKs that no call has described still return an error, keeping tests explicit about what they rely on.

func (*MockResourceClientBuilder) WithResourceNotFound

func (b *MockResourceClientBuilder) WithResourceNotFound() *MockResourceClientBuilder

WithResourceNotFound sets GetResource to always return "not found".

func (*MockResourceClientBuilder) WithResourcesExist

func (b *MockResourceClientBuilder) WithResourcesExist(resources ...*un.Unstructured) *MockResourceClientBuilder

WithResourcesExist sets up GetResource to return resources from a map. Resources are keyed using MakeDiffKey (apiVersion/kind/namespace/name) to correctly handle same-named resources in different namespaces.

func (*MockResourceClientBuilder) WithResourcesFoundByLabel

func (b *MockResourceClientBuilder) WithResourcesFoundByLabel(resources []*un.Unstructured, label, value string, expectNamespace ...string) *MockResourceClientBuilder

WithResourcesFoundByLabel sets GetResourcesByLabel to return resources for a specific label value. This method is stateful - multiple calls accumulate mappings for different label values. The label parameter specifies which label key to match on (e.g., "crossplane.io/composition-name").

An optional expectNamespace pins the lookup namespace: when supplied, the resources are returned only if GetResourcesByLabel is called with that exact namespace. Pass metav1.NamespaceAll to require a cluster-wide (all-namespaces) lookup, as for matchLabels ExtraResources (crossplane-contrib/crossplane-diff#376) — a regression that scopes the lookup to a specific namespace then yields zero results. When omitted, the namespace is not considered and only the label value is matched.

func (*MockResourceClientBuilder) WithSuccessfulInitialize

func (b *MockResourceClientBuilder) WithSuccessfulInitialize() *MockResourceClientBuilder

WithSuccessfulInitialize sets a successful Initialize implementation.

func (*MockResourceClientBuilder) WithoutFoundGVKs

WithoutFoundGVKs sets the GetGVKsForGroupKind behavior.

type MockResourceInterface

type MockResourceInterface struct {
	GetFn    func(ctx context.Context, name string, options metav1.GetOptions, subresources ...string) (*un.Unstructured, error)
	ListFn   func(ctx context.Context, opts metav1.ListOptions) (*un.UnstructuredList, error)
	CreateFn func(ctx context.Context, obj *un.Unstructured, options metav1.CreateOptions, subresources ...string) (*un.Unstructured, error)
	UpdateFn func(ctx context.Context, obj *un.Unstructured, options metav1.UpdateOptions, subresources ...string) (*un.Unstructured, error)
	DeleteFn func(ctx context.Context, name string, options metav1.DeleteOptions, subresources ...string) error
	PatchFn  func(ctx context.Context, name string, pt k8stypes.PatchType, data []byte, options metav1.PatchOptions, subresources ...string) (*un.Unstructured, error)
}

MockResourceInterface mocks dynamic.ResourceInterface for namespaced resources.

func (*MockResourceInterface) Apply

Apply implements dynamic.ResourceInterface.

func (*MockResourceInterface) ApplyStatus

ApplyStatus implements dynamic.ResourceInterface.

func (*MockResourceInterface) Create

func (m *MockResourceInterface) Create(ctx context.Context, obj *un.Unstructured, options metav1.CreateOptions, subresources ...string) (*un.Unstructured, error)

Create implements dynamic.ResourceInterface.

func (*MockResourceInterface) Delete

func (m *MockResourceInterface) Delete(ctx context.Context, name string, options metav1.DeleteOptions, subresources ...string) error

Delete implements dynamic.ResourceInterface.

func (*MockResourceInterface) DeleteCollection

DeleteCollection implements dynamic.ResourceInterface.

func (*MockResourceInterface) Get

func (m *MockResourceInterface) Get(ctx context.Context, name string, options metav1.GetOptions, subresources ...string) (*un.Unstructured, error)

Get implements dynamic.ResourceInterface.

func (*MockResourceInterface) List

List implements dynamic.ResourceInterface.

func (*MockResourceInterface) Patch

func (m *MockResourceInterface) Patch(ctx context.Context, name string, pt k8stypes.PatchType, data []byte, options metav1.PatchOptions, subresources ...string) (*un.Unstructured, error)

Patch implements dynamic.ResourceInterface.

func (*MockResourceInterface) Update

func (m *MockResourceInterface) Update(ctx context.Context, obj *un.Unstructured, options metav1.UpdateOptions, subresources ...string) (*un.Unstructured, error)

Update implements dynamic.ResourceInterface.

func (*MockResourceInterface) UpdateStatus

UpdateStatus implements dynamic.ResourceInterface.

func (*MockResourceInterface) Watch

Watch implements dynamic.ResourceInterface.

type MockResourceTreeClient

type MockResourceTreeClient struct {
	InitializeFn      func(ctx context.Context) error
	GetResourceTreeFn func(ctx context.Context, root *un.Unstructured) (*resource.Resource, error)
}

MockResourceTreeClient implements the crossplane.ResourceTreeClient interface.

func (*MockResourceTreeClient) GetResourceTree

func (m *MockResourceTreeClient) GetResourceTree(ctx context.Context, root *un.Unstructured) (*resource.Resource, error)

GetResourceTree implements crossplane.ResourceTreeClient.

func (*MockResourceTreeClient) Initialize

func (m *MockResourceTreeClient) Initialize(ctx context.Context) error

Initialize implements crossplane.ResourceTreeClient.

type MockResourceTreeClientBuilder

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

MockResourceTreeClientBuilder helps build crossplane.ResourceTreeClient mocks.

func NewMockResourceTreeClient

func NewMockResourceTreeClient() *MockResourceTreeClientBuilder

NewMockResourceTreeClient creates a new MockResourceTreeClientBuilder.

func (*MockResourceTreeClientBuilder) Build

Build returns the built mock.

func (*MockResourceTreeClientBuilder) WithEmptyResourceTree

WithEmptyResourceTree sets GetResourceTree to return just the root with no children.

func (*MockResourceTreeClientBuilder) WithFailedInitialize

func (b *MockResourceTreeClientBuilder) WithFailedInitialize(errMsg string) *MockResourceTreeClientBuilder

WithFailedInitialize mocks a failed call to Initialize.

func (*MockResourceTreeClientBuilder) WithFailedResourceTreeFetch

func (b *MockResourceTreeClientBuilder) WithFailedResourceTreeFetch(errMsg string) *MockResourceTreeClientBuilder

WithFailedResourceTreeFetch sets GetResourceTree to return an error.

func (*MockResourceTreeClientBuilder) WithGetResourceTree

WithGetResourceTree sets the GetResourceTree behavior.

func (*MockResourceTreeClientBuilder) WithInitialize

WithInitialize sets the Initialize behavior.

func (*MockResourceTreeClientBuilder) WithResourceTreeFromXRAndComposed

func (b *MockResourceTreeClientBuilder) WithResourceTreeFromXRAndComposed(xr *un.Unstructured, composed []*un.Unstructured) *MockResourceTreeClientBuilder

WithResourceTreeFromXRAndComposed creates a basic resource tree from an XR and composed resources.

func (*MockResourceTreeClientBuilder) WithSuccessfulInitialize

func (b *MockResourceTreeClientBuilder) WithSuccessfulInitialize() *MockResourceTreeClientBuilder

WithSuccessfulInitialize mocks a successful call to Initialize.

func (*MockResourceTreeClientBuilder) WithSuccessfulResourceTreeFetch

func (b *MockResourceTreeClientBuilder) WithSuccessfulResourceTreeFetch(resourceTree *resource.Resource) *MockResourceTreeClientBuilder

WithSuccessfulResourceTreeFetch sets GetResourceTree to return a specific tree.

type MockSchemaClient

type MockSchemaClient struct {
	InitializeFn       func(ctx context.Context) error
	GetCRDFn           func(ctx context.Context, gvk schema.GroupVersionKind) (*extv1.CustomResourceDefinition, error)
	GetCRDByNameFn     func(name string) (*extv1.CustomResourceDefinition, error)
	IsCRDRequiredFn    func(ctx context.Context, gvk schema.GroupVersionKind) bool
	ValidateResourceFn func(ctx context.Context, resource *un.Unstructured) error
	LoadCRDsFromXRDsFn func(ctx context.Context, xrds []*un.Unstructured) error
	GetAllCRDsFn       func() []*extv1.CustomResourceDefinition
}

MockSchemaClient implements the kubernetes.SchemaClient interface.

func (*MockSchemaClient) GetAllCRDs added in v0.2.0

func (m *MockSchemaClient) GetAllCRDs() []*extv1.CustomResourceDefinition

GetAllCRDs implements kubernetes.SchemaClient.

func (*MockSchemaClient) GetCRD

GetCRD implements kubernetes.SchemaClient.

func (*MockSchemaClient) GetCRDByName added in v0.2.0

func (m *MockSchemaClient) GetCRDByName(name string) (*extv1.CustomResourceDefinition, error)

GetCRDByName implements kubernetes.SchemaClient.

func (*MockSchemaClient) Initialize

func (m *MockSchemaClient) Initialize(ctx context.Context) error

Initialize implements kubernetes.SchemaClient.

func (*MockSchemaClient) IsCRDRequired

func (m *MockSchemaClient) IsCRDRequired(ctx context.Context, gvk schema.GroupVersionKind) bool

IsCRDRequired implements kubernetes.SchemaClient.

func (*MockSchemaClient) LoadCRDsFromXRDs added in v0.2.0

func (m *MockSchemaClient) LoadCRDsFromXRDs(ctx context.Context, xrds []*un.Unstructured) error

LoadCRDsFromXRDs implements kubernetes.SchemaClient.

func (*MockSchemaClient) ValidateResource

func (m *MockSchemaClient) ValidateResource(ctx context.Context, resource *un.Unstructured) error

ValidateResource implements kubernetes.SchemaClient.

type MockSchemaClientBuilder

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

MockSchemaClientBuilder helps build kubernetes.SchemaClient mocks.

func NewMockSchemaClient

func NewMockSchemaClient() *MockSchemaClientBuilder

NewMockSchemaClient creates a new MockSchemaClientBuilder.

func (*MockSchemaClientBuilder) Build

Build returns the built mock.

func (*MockSchemaClientBuilder) WithAllResourcesRequiringCRDs

func (b *MockSchemaClientBuilder) WithAllResourcesRequiringCRDs() *MockSchemaClientBuilder

WithAllResourcesRequiringCRDs sets all resources to require CRDs.

func (*MockSchemaClientBuilder) WithCRDNotFound

func (b *MockSchemaClientBuilder) WithCRDNotFound() *MockSchemaClientBuilder

WithCRDNotFound sets GetCRD to return a not found error.

func (*MockSchemaClientBuilder) WithCachingBehavior added in v0.2.0

func (b *MockSchemaClientBuilder) WithCachingBehavior() *MockSchemaClientBuilder

WithCachingBehavior creates a mock that simulates caching CRDs when GetCRD or LoadCRDsFromXRDs is called.

func (*MockSchemaClientBuilder) WithFoundCRD added in v0.2.0

WithFoundCRD sets GetCRD to return a specific CRD when the group and kind match.

func (*MockSchemaClientBuilder) WithFoundCRDs added in v0.2.0

WithFoundCRDs sets GetCRD to return specific CRDs when the group and kind match, with a fallback error.

func (*MockSchemaClientBuilder) WithGetAllCRDs added in v0.2.0

WithGetAllCRDs sets the GetAllCRDs behavior.

func (*MockSchemaClientBuilder) WithGetCRD

WithGetCRD sets the GetCRD behavior.

func (*MockSchemaClientBuilder) WithGetCRDByName added in v0.2.0

WithGetCRDByName sets the GetCRDByName behavior.

func (*MockSchemaClientBuilder) WithInitialize

WithInitialize sets the Initialize behavior.

func (*MockSchemaClientBuilder) WithIsCRDRequired

WithIsCRDRequired sets the IsCRDRequired behavior.

func (*MockSchemaClientBuilder) WithNoResourcesRequiringCRDs

func (b *MockSchemaClientBuilder) WithNoResourcesRequiringCRDs() *MockSchemaClientBuilder

WithNoResourcesRequiringCRDs sets all resources to not require CRDs.

func (*MockSchemaClientBuilder) WithResourcesRequiringCRDs

func (b *MockSchemaClientBuilder) WithResourcesRequiringCRDs(crdsRequiredGVKs ...schema.GroupVersionKind) *MockSchemaClientBuilder

WithResourcesRequiringCRDs sets only the specified GVKs to require CRDs.

func (*MockSchemaClientBuilder) WithSuccessfulCRDByNameFetch added in v0.2.0

func (b *MockSchemaClientBuilder) WithSuccessfulCRDByNameFetch(name string, crd *extv1.CustomResourceDefinition) *MockSchemaClientBuilder

WithSuccessfulCRDByNameFetch sets GetCRDByName to return a specific CRD for a given name.

func (*MockSchemaClientBuilder) WithSuccessfulCRDFetch

WithSuccessfulCRDFetch sets GetCRD to return a specific CRD.

func (*MockSchemaClientBuilder) WithValidateResource

WithValidateResource sets the ValidateResource behavior.

type MockSchemaValidator

type MockSchemaValidator struct {
	ValidateResourcesFn        func(ctx context.Context, xr *un.Unstructured, composed []cpd.Unstructured) error
	ValidateScopeConstraintsFn func(ctx context.Context, resource *un.Unstructured, expectedNamespace string, isClaimRoot bool) error
}

MockSchemaValidator Mock schema validator.

func (*MockSchemaValidator) EnsureComposedResourceCRDs

func (m *MockSchemaValidator) EnsureComposedResourceCRDs(_ context.Context, _ []*un.Unstructured) error

EnsureComposedResourceCRDs Implement other required methods of the SchemaValidator interface.

func (*MockSchemaValidator) ValidateResources

func (m *MockSchemaValidator) ValidateResources(ctx context.Context, xr *un.Unstructured, composed []cpd.Unstructured) error

ValidateResources validates a set of resources against schemas from the cluster.

func (*MockSchemaValidator) ValidateScopeConstraints

func (m *MockSchemaValidator) ValidateScopeConstraints(ctx context.Context, resource *un.Unstructured, expectedNamespace string, isClaimRoot bool) error

ValidateScopeConstraints validates that a resource has the appropriate namespace for its scope.

type MockTypeConverter

type MockTypeConverter struct {
	GVKToGVRFn              func(ctx context.Context, gvk schema.GroupVersionKind) (schema.GroupVersionResource, error)
	GetResourceNameForGVKFn func(ctx context.Context, gvk schema.GroupVersionKind) (string, error)
}

MockTypeConverter implements the kubernetes.TypeConverter interface.

func (*MockTypeConverter) GVKToGVR

GVKToGVR implements kubernetes.TypeConverter.

func (*MockTypeConverter) GetResourceNameForGVK

func (m *MockTypeConverter) GetResourceNameForGVK(ctx context.Context, gvk schema.GroupVersionKind) (string, error)

GetResourceNameForGVK implements kubernetes.TypeConverter.

type MockTypeConverterBuilder

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

MockTypeConverterBuilder helps build kubernetes.TypeConverter mocks.

func NewMockTypeConverter

func NewMockTypeConverter() *MockTypeConverterBuilder

NewMockTypeConverter creates a new MockTypeConverterBuilder.

func (*MockTypeConverterBuilder) Build

Build returns the built mock.

func (*MockTypeConverterBuilder) WithDefaultGVKToGVR

func (b *MockTypeConverterBuilder) WithDefaultGVKToGVR() *MockTypeConverterBuilder

WithDefaultGVKToGVR sets a default implementation for GVKToGVR.

func (*MockTypeConverterBuilder) WithDefaultGetResourceNameForGVK

func (b *MockTypeConverterBuilder) WithDefaultGetResourceNameForGVK() *MockTypeConverterBuilder

WithDefaultGetResourceNameForGVK sets a default implementation for GetResourceNameForGVK.

func (*MockTypeConverterBuilder) WithGVKToGVR

WithGVKToGVR sets the GVKToGVR behavior.

func (*MockTypeConverterBuilder) WithGetResourceNameForGVK

WithGetResourceNameForGVK sets the GetResourceNameForGVK behavior.

func (*MockTypeConverterBuilder) WithResourceNameForGVK added in v0.2.0

func (b *MockTypeConverterBuilder) WithResourceNameForGVK(gvk schema.GroupVersionKind, resourceName string) *MockTypeConverterBuilder

WithResourceNameForGVK sets GetResourceNameForGVK to return a specific resource name for a given GVK.

func (*MockTypeConverterBuilder) WithResourceNameForGVKs added in v0.2.0

func (b *MockTypeConverterBuilder) WithResourceNameForGVKs(gvkMappings map[schema.GroupVersionKind]string) *MockTypeConverterBuilder

WithResourceNameForGVKs sets GetResourceNameForGVK to return specific resource names for given GVKs, with a fallback error.

type OutputError added in v0.7.0

type OutputError struct {
	ResourceID         string                      `json:"resourceID,omitempty"`
	Message            string                      `json:"message"`
	ValidationFailures []ResourceValidationFailure `json:"validationFailures,omitempty"`
}

OutputError mirrors dt.OutputError.

type OutputWarning added in v0.11.0

type OutputWarning struct {
	Message string            `json:"message"`
	Context map[string]string `json:"context,omitempty"`
}

OutputWarning mirrors renderer/types.OutputWarning: a non-fatal advisory carried in structured output alongside (but distinct from) errors.

type PipelineStepOption added in v0.6.0

type PipelineStepOption func(*xpextv1.PipelineStep)

PipelineStepOption is a functional option for configuring a pipeline step.

func WithCredentials added in v0.6.0

func WithCredentials(name, namespace, secretName string) PipelineStepOption

WithCredentials adds credentials to a pipeline step.

type ResourceBuilder

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

ResourceBuilder helps construct unstructured resources for testing.

func NewResource

func NewResource(apiVersion, kind, name string) *ResourceBuilder

NewResource creates a new ResourceBuilder.

func (*ResourceBuilder) Build

func (b *ResourceBuilder) Build() *un.Unstructured

Build returns the built unstructured resource.

func (*ResourceBuilder) BuildTyped added in v0.6.0

func (b *ResourceBuilder) BuildTyped(into runtime.Object)

BuildTyped converts the built unstructured resource into a typed Kubernetes object. The 'into' parameter should be a pointer to the target type (e.g., &corev1.Secret{}).

func (*ResourceBuilder) BuildUComposed

func (b *ResourceBuilder) BuildUComposed() *cpd.Unstructured

BuildUComposed returns the built unstructured resource as a *cpd.Unstructured.

func (*ResourceBuilder) BuildUComposite

func (b *ResourceBuilder) BuildUComposite() *cmp.Unstructured

BuildUComposite returns the built unstructured resource as a *cmp.Unstructured.

func (*ResourceBuilder) ControlledBy added in v0.11.0

func (b *ResourceBuilder) ControlledBy(owner *un.Unstructured) *ResourceBuilder

ControlledBy adds a controller owner reference to owner, by its apiVersion, kind, name and UID: what Crossplane sets on every resource a composite composes.

func (*ResourceBuilder) InNamespace

func (b *ResourceBuilder) InNamespace(namespace string) *ResourceBuilder

InNamespace sets the namespace for the resource.

func (*ResourceBuilder) WithAnnotations

func (b *ResourceBuilder) WithAnnotations(annotations map[string]string) *ResourceBuilder

WithAnnotations adds annotations to the resource.

func (*ResourceBuilder) WithCompositeOwner

func (b *ResourceBuilder) WithCompositeOwner(owner string) *ResourceBuilder

WithCompositeOwner sets up the resource as a cpd resource with the given composite owner.

func (*ResourceBuilder) WithCompositionResourceName

func (b *ResourceBuilder) WithCompositionResourceName(name string) *ResourceBuilder

WithCompositionResourceName sets the composition resource name annotation.

func (*ResourceBuilder) WithCompositionRevisionSelector added in v0.9.0

func (b *ResourceBuilder) WithCompositionRevisionSelector(apiGroup string, matchLabels map[string]string, matchExpressions []map[string]any) *ResourceBuilder

WithCompositionRevisionSelector sets spec[.crossplane].compositionRevisionSelector on the resource. Pass CrossplaneAPIExtGroupV2 ("apiextensions.crossplane.io/v2") to use the v2 path (spec.crossplane.compositionRevisionSelector) or CrossplaneAPIExtGroupV1 for the legacy v1 path (spec.compositionRevisionSelector). matchLabels and matchExpressions are omitted when nil, so a selector with only expressions (or only labels) can be built. matchExpressions entries use the standard LabelSelectorRequirement shape: {"key": string, "operator": string, "values": []any}.

func (*ResourceBuilder) WithCondition added in v0.11.0

func (b *ResourceBuilder) WithCondition(condType, status, reason string) *ResourceBuilder

WithCondition appends a status condition of the given type and status (e.g. "Ready", "False") to status.conditions, with the given reason.

func (*ResourceBuilder) WithControllerReference added in v0.9.0

func (b *ResourceBuilder) WithControllerReference(kind, name, apiVersion, uid string) *ResourceBuilder

WithControllerReference adds a controller owner reference (Controller=true, BlockOwnerDeletion=true) to the resource. This mirrors how Crossplane sets the controlling XR on a composed resource, so tests that exercise controller-ref-based logic (e.g. observed-resource scoping in FetchObservedResources) can build realistic fixtures.

func (*ResourceBuilder) WithData added in v0.6.0

func (b *ResourceBuilder) WithData(data map[string][]byte) *ResourceBuilder

WithData sets the data field for Secret resources. The byte slices are base64-encoded as they would be in Kubernetes.

func (*ResourceBuilder) WithDeletionTimestamp added in v0.11.0

func (b *ResourceBuilder) WithDeletionTimestamp(timestamp any) *ResourceBuilder

WithDeletionTimestamp sets metadata.deletionTimestamp to the supplied raw value, marking the resource as being deleted. The value is set verbatim, and typed any rather than string, so tests can pass an explicit nil — which is how round-tripped Kubernetes YAML spells "unset" for timestamp fields, and therefore a case worth asserting is not mistaken for a deleting resource.

func (*ResourceBuilder) WithFieldManagers added in v0.5.0

func (b *ResourceBuilder) WithFieldManagers(managers ...string) *ResourceBuilder

WithFieldManagers sets the managed fields on the resource using the provided manager names.

func (*ResourceBuilder) WithGenerateName

func (b *ResourceBuilder) WithGenerateName(generateName string) *ResourceBuilder

WithGenerateName sets the namespace for the resource.

func (*ResourceBuilder) WithLabels

func (b *ResourceBuilder) WithLabels(labels map[string]string) *ResourceBuilder

WithLabels adds labels to the resource.

func (*ResourceBuilder) WithNamespace added in v0.2.0

func (b *ResourceBuilder) WithNamespace(namespace string) *ResourceBuilder

WithNamespace sets the namespace for the resource.

func (*ResourceBuilder) WithNestedField added in v0.3.0

func (b *ResourceBuilder) WithNestedField(value any, fields ...string) *ResourceBuilder

WithNestedField sets a field at an arbitrary nested path in the resource. The path is a sequence of field names to traverse (e.g., "spec", "crossplane", "compositionUpdatePolicy").

func (*ResourceBuilder) WithOwnerReference

func (b *ResourceBuilder) WithOwnerReference(kind, name, apiVersion, uid string) *ResourceBuilder

WithOwnerReference appends an owner ref to a resource.

func (*ResourceBuilder) WithServerMetadata added in v0.8.1

func (b *ResourceBuilder) WithServerMetadata() *ResourceBuilder

WithServerMetadata stamps the server-populated identity and versioning metadata fields (resourceVersion, uid, generation, creationTimestamp) that Kubernetes adds to a persisted object. Values are deterministic placeholders so tests remain stable. Use this to construct a resource that looks like it was fetched from the cluster (e.g. to verify diff cleanup strips these).

func (*ResourceBuilder) WithSpec

func (b *ResourceBuilder) WithSpec(spec map[string]any) *ResourceBuilder

WithSpec sets the spec field of the resource.

func (*ResourceBuilder) WithSpecField

func (b *ResourceBuilder) WithSpecField(name string, value any) *ResourceBuilder

WithSpecField sets a specific field in the spec.

func (*ResourceBuilder) WithStatus

func (b *ResourceBuilder) WithStatus(status map[string]any) *ResourceBuilder

WithStatus sets the status field of the resource.

func (*ResourceBuilder) WithStatusField

func (b *ResourceBuilder) WithStatusField(name string, value any) *ResourceBuilder

WithStatusField sets a specific field in the status.

func (*ResourceBuilder) WithUID added in v0.9.0

func (b *ResourceBuilder) WithUID(uid string) *ResourceBuilder

WithUID sets the resource's metadata.uid.

type ResourceExpectation added in v0.7.0

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

ResourceExpectation defines expectations for a single resource change.

func (*ResourceExpectation) And added in v0.7.0

And returns to the root ExpectedDiff to chain more expectations. Not needed at the end of a chain - AssertStructuredDiff accepts a ResourceExpectation directly.

func (*ResourceExpectation) Change added in v0.10.0

func (r *ResourceExpectation) Change(changeType, kind, name, namespace string) *ResourceExpectation

Change opens a sibling change on the same enclosing XR entry (only valid on a change opened via XRExpectation.Change). Lets an XR's changes chain without a scope-closing call: xr.Change(...).FieldChange(...).Change(...). Panics if called on a flat top-level change (which has no enclosing XR).

func (*ResourceExpectation) WithAnyName added in v0.7.0

func (r *ResourceExpectation) WithAnyName() *ResourceExpectation

WithAnyName allows any resource name (useful for generated names).

func (*ResourceExpectation) WithDryRunPerformed added in v0.11.0

func (r *ResourceExpectation) WithDryRunPerformed() *ResourceExpectation

WithDryRunPerformed asserts this change carries NO dryRun object, i.e. its desired state did go through the apiserver. Worth asserting explicitly on the happy path: without it, a regression that silently stopped dry-running additions would only be caught by whichever field assertions happened to depend on server-side defaulting.

func (*ResourceExpectation) WithDryRunSkipped added in v0.11.0

func (r *ResourceExpectation) WithDryRunSkipped(reason, detailSubstring string) *ResourceExpectation

WithDryRunSkipped asserts this change reports that its desired state was NOT verified against the apiserver, for the given reason (one of the dt.DryRunSkipReason values: "disabled", "forbidden", "webhookUnavailable").

Pass a detailSubstring to additionally require that the cluster's own explanation was propagated rather than swallowed; pass "" to skip that check.

func (*ResourceExpectation) WithDryRunStorageVersion added in v0.11.0

func (r *ResourceExpectation) WithDryRunStorageVersion(version string) *ResourceExpectation

WithDryRunStorageVersion asserts this change, reported as not verified (see WithDryRunSkipped), records version as the version its CRD stores it at: one other than the version it was requested at, whose defaults and conversion its locally predicted diff does not model.

func (*ResourceExpectation) WithField added in v0.7.0

func (r *ResourceExpectation) WithField(path string, value any) *ResourceExpectation

WithField asserts a specific field exists with exact value (for added/removed resources).

func (*ResourceExpectation) WithFieldAbsent added in v0.11.0

func (r *ResourceExpectation) WithFieldAbsent(path string) *ResourceExpectation

WithFieldAbsent asserts the path carries no value at all (for added/removed resources).

Named rather than spelled WithField(path, nil) at call sites, because "this field must not be here" is a different claim from "this field equals nothing" and reads as a typo otherwise.

func (*ResourceExpectation) WithFieldAdded added in v0.7.0

func (r *ResourceExpectation) WithFieldAdded(path string, value any) *ResourceExpectation

WithFieldAdded asserts a field was added (for modified resources). Equivalent to WithFieldChange(path, nil, value).

func (*ResourceExpectation) WithFieldChange added in v0.7.0

func (r *ResourceExpectation) WithFieldChange(path string, oldValue, newValue any) *ResourceExpectation

WithFieldChange asserts a field changed from old to new value (for modified resources).

func (*ResourceExpectation) WithFieldRemoved added in v0.7.0

func (r *ResourceExpectation) WithFieldRemoved(path string, value any) *ResourceExpectation

WithFieldRemoved asserts a field was removed (for modified resources). Equivalent to WithFieldChange(path, value, nil).

func (*ResourceExpectation) WithFieldValuePattern added in v0.7.0

func (r *ResourceExpectation) WithFieldValuePattern(path, pattern string) *ResourceExpectation

WithFieldValuePattern asserts a field value matches a regex pattern. Use this for fields with generated/dynamic values like resource names with random suffixes.

func (*ResourceExpectation) WithNamePattern added in v0.7.0

func (r *ResourceExpectation) WithNamePattern(pattern string) *ResourceExpectation

WithNamePattern matches resource name against a regex pattern instead of exact name.

func (*ResourceExpectation) WithSpec added in v0.7.0

func (r *ResourceExpectation) WithSpec(spec map[string]any) *ResourceExpectation

WithSpec asserts the entire spec matches (for strict equality).

type ResourceValidationFailure added in v0.8.0

type ResourceValidationFailure struct {
	APIVersion string                 `json:"apiVersion"`
	Kind       string                 `json:"kind"`
	Name       string                 `json:"name,omitempty"`
	Namespace  string                 `json:"namespace,omitempty"`
	Status     string                 `json:"status"`
	Errors     []FieldValidationError `json:"errors,omitempty"`
}

ResourceValidationFailure mirrors dt.ResourceValidationFailure.

type RevisionImpactWire added in v0.11.0

type RevisionImpactWire struct {
	ChangeScope           string `json:"changeScope"`
	CreatesRevision       bool   `json:"createsRevision"`
	RepointedComposites   int    `json:"repointedComposites"`
	PredictedRevisionName string `json:"predictedRevisionName,omitempty"`
}

RevisionImpactWire mirrors renderer.RevisionImpact.

type StructuredCompDiffOutput added in v0.7.0

type StructuredCompDiffOutput struct {
	OutputVersion string                `json:"outputVersion"`
	Compositions  []CompositionDiffWire `json:"compositions"`
	Errors        []OutputError         `json:"errors,omitempty"`
	Warnings      []OutputWarning       `json:"warnings,omitempty"`
}

StructuredCompDiffOutput mirrors the JSON schema for composition diffs.

func ParseStructuredCompOutput added in v0.7.0

func ParseStructuredCompOutput(jsonOutput string) (StructuredCompDiffOutput, error)

ParseStructuredCompOutput parses JSON output into StructuredCompDiffOutput.

type StructuredDiffOutput added in v0.7.0

type StructuredDiffOutput struct {
	OutputVersion string          `json:"outputVersion"`
	Summary       Summary         `json:"summary"`
	Changes       []ChangeDetail  `json:"changes"`
	Errors        []OutputError   `json:"errors,omitempty"`
	Warnings      []OutputWarning `json:"warnings,omitempty"`
	Xrs           []XRDiffWire    `json:"xrs"`
}

StructuredDiffOutput mirrors the renderer's xr document to avoid import cycles: v1's renderer.StructuredDiffOutput, and v2's structuredDiffOutputV2, which is the same document without changes (Changes is then nil). These types are used only for test assertions.

func ParseStructuredOutput added in v0.7.0

func ParseStructuredOutput(jsonOutput string) (StructuredDiffOutput, error)

ParseStructuredOutput parses JSON output into StructuredDiffOutput.

type Summary added in v0.7.0

type Summary struct {
	Added    int `json:"added"`
	Modified int `json:"modified"`
	Removed  int `json:"removed"`
}

Summary mirrors renderer.Summary.

type TreeNodeBuilder added in v0.11.0

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

TreeNodeBuilder builds a resource-tree node, the shape a ResourceTreeClient returns.

func NewTreeNode added in v0.11.0

func NewTreeNode(obj *un.Unstructured) *TreeNodeBuilder

NewTreeNode starts a tree node holding a deep copy of obj, so the caller's object is never shared with, or mutated through, the tree.

func (*TreeNodeBuilder) Build added in v0.11.0

func (b *TreeNodeBuilder) Build() *resource.Resource

Build returns the built node.

func (*TreeNodeBuilder) WithChildren added in v0.11.0

func (b *TreeNodeBuilder) WithChildren(children ...*TreeNodeBuilder) *TreeNodeBuilder

WithChildren appends the given nodes as children of this one.

func (*TreeNodeBuilder) WithError added in v0.11.0

func (b *TreeNodeBuilder) WithError(err error) *TreeNodeBuilder

WithError records err on the node, as upstream's tree client does for a node it could not fetch.

type ValidationFailureExpectation added in v0.8.0

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

ValidationFailureExpectation describes one expected entry in errors[].validationFailures[]. Match is by APIVersion/Kind/Name; Errors asserts on the per-field validation entries within.

func (*ValidationFailureExpectation) AndValidationFailure added in v0.8.0

func (v *ValidationFailureExpectation) AndValidationFailure() *ErrorExpectation

AndValidationFailure returns to the parent ErrorExpectation to chain another WithValidationFailure.

func (*ValidationFailureExpectation) WithFieldError added in v0.8.0

func (v *ValidationFailureExpectation) WithFieldError(errType, field string) *FieldErrorExpectation

WithFieldError adds an expectation for one entry in the failure's errors[] slice, matched by errType ("schema", "cel", "unknownField", "defaulting") and field (empty matches non-localized errors like defaulting).

func (*ValidationFailureExpectation) WithStatus added in v0.8.0

WithStatus pins the validation status on this resource entry ("invalid", "missingSchema"). Optional; empty status skips the assertion.

type WarningExpectation added in v0.11.0

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

WarningExpectation describes one expected entry in an xr diff's warnings[].

func (*WarningExpectation) And added in v0.11.0

func (w *WarningExpectation) And() *ExpectedDiff

And returns to the parent builder.

func (*WarningExpectation) WithWarningContext added in v0.11.0

func (w *WarningExpectation) WithWarningContext(context map[string]string) *WarningExpectation

WithWarningContext pins the expected context key/value pairs on the warning under construction.

type XRDBuilder added in v0.2.0

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

XRDBuilder helps construct XRD resources for testing.

func NewXRD added in v0.2.0

func NewXRD(name, group, kind string) *XRDBuilder

NewXRD creates a new XRDBuilder.

func (*XRDBuilder) Build added in v0.2.0

Build returns the built XRD.

func (*XRDBuilder) BuildAsUnstructured added in v0.2.0

func (b *XRDBuilder) BuildAsUnstructured() *un.Unstructured

BuildAsUnstructured returns the built XRD as an unstructured object.

func (*XRDBuilder) WithClaimNames added in v0.2.0

func (b *XRDBuilder) WithClaimNames(kind, plural string) *XRDBuilder

WithClaimNames sets the claim names for the XRD.

func (*XRDBuilder) WithDefaultVersion added in v0.3.0

func (b *XRDBuilder) WithDefaultVersion() *XRDBuilder

WithDefaultVersion adds a default "v1" version to the XRD.

func (*XRDBuilder) WithPlural added in v0.2.0

func (b *XRDBuilder) WithPlural(plural string) *XRDBuilder

WithPlural sets the plural name for the XRD.

func (*XRDBuilder) WithRawSchema added in v0.2.0

func (b *XRDBuilder) WithRawSchema(rawJSON []byte) *XRDBuilder

WithRawSchema adds a raw JSON schema to the last added version.

func (*XRDBuilder) WithSchema added in v0.2.0

func (b *XRDBuilder) WithSchema(schema *extv1.JSONSchemaProps) *XRDBuilder

WithSchema adds an OpenAPI v3 schema to the last added version.

func (*XRDBuilder) WithSingular added in v0.2.0

func (b *XRDBuilder) WithSingular(singular string) *XRDBuilder

WithSingular sets the singular name for the XRD.

func (*XRDBuilder) WithVersion added in v0.2.0

func (b *XRDBuilder) WithVersion(name string, served, referenceable bool) *XRDBuilder

WithVersion adds a version to the XRD.

type XRDiffWire added in v0.10.0

type XRDiffWire = XREntryWire

XRDiffWire mirrors the renderer's v1 xrs[] entry (xrDiffWire). Its fields are a subset of the v2 entry's, the rest of which xr never sets, so one mirror serves both versions.

type XREntryWire added in v0.11.0

type XREntryWire struct {
	XR           corev1.ObjectReference `json:"xr"`
	Status       string                 `json:"status"`
	FilterReason string                 `json:"filterReason,omitempty"`
	FilterDetail string                 `json:"filterDetail,omitempty"`
	Summary      Summary                `json:"summary"`
	Changes      []ChangeDetail         `json:"changes"`
	Errors       []OutputError          `json:"errors,omitempty"`
}

XREntryWire mirrors the renderer's v2 per-XR entry (xrEntryWire), which both xr's xrs[] and comp's v2 impactAnalysis[] hold. XR is a corev1.ObjectReference nested under "xr", matching the renderer — asserting into the same platform type here also exercises that the "xr" object round-trips into an ObjectReference.

type XRExpectation added in v0.10.0

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

XRExpectation defines expectations for a single entry in the xrs[] grouped view: the input XR's identity, its status, its per-XR summary, and its per-XR changes. Build one with XR(...), configure it with the methods below, then pass it (with any siblings) to ExpectedDiff.WithXRs.

func XR added in v0.10.0

func XR(kind, name, namespace string) *XRExpectation

XR begins a standalone expectation for one xrs[] entry, keyed by the input XR's kind/name/namespace. Pass the result(s) to ExpectedDiff.WithXRs.

func (*XRExpectation) AnyName added in v0.10.0

func (x *XRExpectation) AnyName() *XRExpectation

AnyName matches the XR by kind/namespace only, accepting any name (useful for generated XR names).

func (*XRExpectation) Change added in v0.10.0

func (x *XRExpectation) Change(changeType, kind, name, namespace string) *ResourceExpectation

Change opens a change expectation scoped to this XR entry's changes[]. changeType is "added", "modified", or "removed". Returns a ResourceExpectation whose field methods (WithField/WithFieldChange/…) and chained Change(...) let a change and its siblings be expressed inline.

func (*XRExpectation) Err added in v0.10.0

func (x *XRExpectation) Err(resourceID string) *XRExpectation

Err asserts the entry carries an error with the given resourceID.

func (*XRExpectation) NamePattern added in v0.10.0

func (x *XRExpectation) NamePattern(pattern string) *XRExpectation

NamePattern matches the XR name against a regex instead of an exact name.

func (*XRExpectation) Status added in v0.10.0

func (x *XRExpectation) Status(status string) *XRExpectation

Status asserts the entry's status (changed/unchanged/error).

func (*XRExpectation) Summary added in v0.10.0

func (x *XRExpectation) Summary(added, modified, removed int) *XRExpectation

Summary asserts the entry's per-XR summary counts.

type XRImpactExpectation added in v0.7.0

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

XRImpactExpectation defines expectations for a single XR impact.

func (*XRImpactExpectation) AndComp added in v0.7.0

AndComp returns to parent to chain more XR impact expectations. Not needed at the end of a chain - AssertStructuredCompDiff accepts XRImpactExpectation directly.

func (*XRImpactExpectation) AndComposition added in v0.11.0

func (x *XRImpactExpectation) AndComposition(name string) *CompositionExpectation

AndComposition starts an expectation for another composition. See DownstreamResourceExpectation.AndComposition.

func (*XRImpactExpectation) WithAnyName added in v0.7.0

func (x *XRImpactExpectation) WithAnyName() *XRImpactExpectation

WithAnyName allows any XR name (useful for generated names).

func (*XRImpactExpectation) WithDownstreamResource added in v0.7.0

func (x *XRImpactExpectation) WithDownstreamResource(changeType, kind, name, namespace string) *DownstreamResourceExpectation

WithDownstreamResource adds an expectation for a downstream resource change. Use this to assert on specific field-level changes in downstream resources.

func (*XRImpactExpectation) WithDownstreamSummary added in v0.7.0

func (x *XRImpactExpectation) WithDownstreamSummary(added, modified, removed int) *XRImpactExpectation

WithDownstreamSummary sets the expected downstream changes summary.

func (*XRImpactExpectation) WithErrorContaining added in v0.11.0

func (x *XRImpactExpectation) WithErrorContaining(s string) *XRImpactExpectation

WithErrorContaining pins a substring of an "error" XR impact's Error, so a test can assert why the composite failed rather than only that it did. Only asserted when set.

func (*XRImpactExpectation) WithErrorResourceID added in v0.11.0

func (x *XRImpactExpectation) WithErrorResourceID(resourceID string) *XRImpactExpectation

WithErrorResourceID asserts the entry's errors[] (v2 only) holds an error with the given resourceID.

func (*XRImpactExpectation) WithFilterReason added in v0.9.0

func (x *XRImpactExpectation) WithFilterReason(reason string) *XRImpactExpectation

WithFilterReason pins the expected FilterReason on a filtered XR impact (e.g. "manual_policy", "revision_selector_mismatch", or "deleting"). Only asserted when set.

type XRImpactWire added in v0.10.0

type XRImpactWire struct {
	// v1 only.
	APIVersion        string             `json:"apiVersion,omitempty"`
	Kind              string             `json:"kind,omitempty"`
	Name              string             `json:"name,omitempty"`
	Namespace         string             `json:"namespace,omitempty"`
	UID               string             `json:"uid,omitempty"`
	Error             string             `json:"error,omitempty"`
	DownstreamChanges *DownstreamChanges `json:"downstreamChanges,omitempty"`

	// Both versions.
	Status       string `json:"status"`
	FilterReason string `json:"filterReason,omitempty"`
	FilterDetail string `json:"filterDetail,omitempty"`

	// v2 only. Pointers and nil slices so their absence from a v1 entry is detectable.
	XR      *corev1.ObjectReference `json:"xr,omitempty"`
	Summary *Summary                `json:"summary,omitempty"`
	Changes []ChangeDetail          `json:"changes,omitempty"`
	Errors  []OutputError           `json:"errors,omitempty"`
}

XRImpactWire mirrors an impactAnalysis[] entry of either version: v1's xrImpactWire (identity inlined, error string, downstreamChanges wrapper) or v2's xrEntryWire (the fields of XREntryWire). The two share only status, filterReason and filterDetail, so a v2 entry leaves the v1-only fields zero and vice versa; assertXRImpactShape checks that. Read it through ref, downstream and errorText, which work for both.

Directories

Path Synopsis
Package envtestreaper kills envtest servers that earlier test runs left behind.
Package envtestreaper kills envtest servers that earlier test runs left behind.

Jump to

Keyboard shortcuts

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