testing

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertEqual

func AssertEqual(t *gt.T, want, actual any, description string, opts ...DiffOption)

AssertEqual asserts that two values are equal. Values are converted to YAML before comparison, differences are represented as colored diff.

func Colorize

func Colorize(diff string) string

Colorize returns a string with colorized diff.

func NormalizeErrorMessage added in v1.0.4

func NormalizeErrorMessage(s string) string

NormalizeErrorMessage canonicalizes the renderings that upstream libraries deliberately randomize in order to discourage comparing error strings:

  • github.com/go-json-experiment/json picks the modal verb "cannot" or "unable to" once per process (errorModalVerb in its errors.go), so "json: unable to" is rewritten to "json: cannot".
  • google.golang.org/protobuf prefixes its errors with "proto: " using either a regular space (U+0020) or a non-breaking space (U+00A0), chosen from a hash of the test binary (prefixError in its internal/errors), so the non-breaking variant is rewritten to the regular one.

Both substitutions are anchored on the library prefix, so arbitrary resource text is never touched. The function is idempotent.

It is applied to both sides of every comparison made by Case and GoldenFileCase. Use it directly in hand-written tests that compare such messages themselves.

func SetResourceBuilderBaseDir

func SetResourceBuilderBaseDir(dir string)

SetResourceBuilderBaseDir defines the base directory path used for resource building operations.

Types

type Args

type Args struct {
	Ctx context.Context //nolint:containedctx // ok for this test case
	Req *fnv1.RunFunctionRequest
}

Args function request arguments.

type Case

type Case struct {
	// Reason is a human-readable description of the test case.
	Reason string
	// Args are the arguments available in the request for the test case.
	Args Args
	// Want is the expected response for the test case.
	Want Want
	// HookFunction is an optional function that can be run before/after the test case is run.
	HookFunction func()
	// DiffOptions are the diff options for the test case.
	DiffOptions []DiffOption
	// Parallel run test casse n times parallel
	Parallel int
	// Results the expected results returned by the function. Empty of OK
	Results []FunctionResult
}

func (*Case) Run

func (c *Case) Run(tb gt.TB, f fnv1.FunctionRunnerServiceServer)

Run runs the function test case.

type DiffOption

type DiffOption func(opts *diff)

func Granular

func Granular() DiffOption

Granular if enabled, diff is evaluated on individual response parts as yaml, rather dnt on the whole structpb response object.

func WithDiffContextLines

func WithDiffContextLines(lines int) DiffOption

WithDiffContextLines sets the number of context lines to use when diffing YAML.

func WithNormalizer added in v1.0.4

func WithNormalizer(re *regexp.Regexp, repl string) DiffOption

WithNormalizer registers an additional replacement applied to both sides of every comparison: error messages, result messages, response diffs and golden files. Use it for values that change between runs, such as byte offsets, timestamps or UUIDs.

func WithYamlIndent

func WithYamlIndent(indent int) DiffOption

WithYamlIndent sets the YAML indentation level.

func WithoutDefaultNormalizers added in v1.0.4

func WithoutDefaultNormalizers() DiffOption

WithoutDefaultNormalizers disables the built-in normalizers described in NormalizeErrorMessage, making every comparison byte-exact again.

type ErrorMatcher added in v1.0.4

type ErrorMatcher interface {
	error
	// MatchError reports whether got satisfies the matcher. normalize canonicalizes the
	// renderings that upstream libraries deliberately randomize.
	MatchError(got error, normalize Normalize) bool
}

ErrorMatcher matches the error returned by the function under test. It implements error, so that it can be assigned to Case.Want.Err and GoldenFileCase.Err in place of a plain error.

func AllOf added in v1.0.4

func AllOf(matchers ...ErrorMatcher) ErrorMatcher

AllOf matches an error that satisfies all the given matchers. Combine a kind with its context, for example AllOf(ErrorAs[*json.SemanticError](), ErrorContains("cannot marshal")).

func ErrorAs added in v1.0.4

func ErrorAs[T error]() ErrorMatcher

ErrorAs matches an error that wraps an error of type T according to errors.As. Use it to assert the kind of a library error, for example ErrorAs[*json.SemanticError]().

func ErrorContains added in v1.0.4

func ErrorContains(substrs ...string) ErrorMatcher

ErrorContains matches an error whose message contains all the given substrings. This is the simplest way to pin the stable part of a wrapped error while ignoring library wording that changes between runs.

func ErrorEqual added in v1.0.4

func ErrorEqual(msg string) ErrorMatcher

ErrorEqual matches an error whose message equals msg once both sides are normalized. It is the explicit form of assigning a plain error to the Err field of a test case.

func ErrorIs added in v1.0.4

func ErrorIs(target error) ErrorMatcher

ErrorIs matches an error that is target according to errors.Is. This is the most robust check available, as it does not look at the message at all.

func ErrorMatching added in v1.0.4

func ErrorMatching(pattern string) ErrorMatcher

ErrorMatching matches an error whose message matches the given regular expression. It panics if pattern does not compile, just like regexp.MustCompile.

func ErrorMessage added in v1.0.4

func ErrorMessage(m StringMatcher) ErrorMatcher

ErrorMessage matches an error whose message satisfies m.

type FunctionResult

type FunctionResult struct {
	Severity fnv1.Severity
	// Message is the expected result message. It is compared after normalizing both sides,
	// see NormalizeErrorMessage. Empty to not verify the message.
	Message string
	// MessageMatcher verifies the result message instead of Message, for a message that is
	// only partly predictable. See Contains, Matching and Equal.
	MessageMatcher StringMatcher
}

FunctionResult is the result of a function execution.

type GoldenFileCase

type GoldenFileCase struct {
	// Reason is a human-readable description of the test case.
	Reason string
	// Composite the path ot the composite file to use for this test
	Composite string
	// Observed resources to mapped by their key used as observed resources in the function request
	Observed map[string]string
	// Required resources to mapped by their key used as required resources in the function request
	Required map[string]string
	// DesiredComposite is the path to a file representing a desired composite
	// resource already produced by a prior function in the pipeline, seeded
	// into the request as req.Desired.Composite.
	DesiredComposite string
	// Desired resources mapped by their key, seeded into the request as
	// req.Desired.Resources - used to simulate desired state produced by a
	// prior function in the composition pipeline.
	Desired map[string]string
	// Input the function input file for the request
	Input string
	// DesiredLocation location of the desired files used to verif the output or the function
	DesiredLocation string
	// WithReady whether to verify the ready result of the desired resources in the function response.
	WithReady bool
	// Err the expected error returned by the function. A plain error matches either by
	// errors.Is or by its normalized message, see NormalizeErrorMessage. Assign an
	// ErrorMatcher such as ErrorContains or ErrorIs to match an error whose message is not
	// fully predictable. If an error is expected, the desired resources are not verified.
	Err error
	// Results the expected results returned by the function. Empty of OK
	Results []FunctionResult

	// DiffOptions are the diff options for the test case.
	DiffOptions []DiffOption
	// contains filtered or unexported fields
}

func (*GoldenFileCase) Run

func (c *GoldenFileCase) Run(tb gt.TB, caseName string, f fnv1.FunctionRunnerServiceServer)

Run runs the function test case.

type Normalize added in v1.0.4

type Normalize func(s string) string

Normalize canonicalizes unstable renderings in a message before it is compared.

type Normalizer added in v1.0.4

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

Normalizer replaces a deliberately unstable fragment of a message. Use NewNormalizer to create one and WithNormalizer to register it on a test case.

func NewNormalizer added in v1.0.4

func NewNormalizer(re *regexp.Regexp, repl string) Normalizer

NewNormalizer returns a Normalizer that replaces every match of re with repl.

type ResourceBuilder

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

ResourceBuilder Reads an initial resource from a YAML file and optionally adds status/conditions to it.

func From

func From(file string) *ResourceBuilder

From Returns a new Resource Builder from a given file.

func NewResourceFromFile

func NewResourceFromFile(file string) *ResourceBuilder

NewResourceFromFile Returns a new Resource Builder.

func (*ResourceBuilder) ToStruct

func (b *ResourceBuilder) ToStruct() *structpb.Struct

ToStruct returns a structpb.Struct object out of the initially provided configurations Function panics on error. To be used in tests only!

func (*ResourceBuilder) WithStatus

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

WithStatus sets optional status values in the resource.

func (*ResourceBuilder) WithStatusConditions

func (b *ResourceBuilder) WithStatusConditions(conditions ...xpv2.Condition) *ResourceBuilder

WithStatusConditions adds conditions Example: WithStatusConditions(xpv2.Available(), xpv2.ReconcileSuccess()).

func (*ResourceBuilder) WithoutName

func (b *ResourceBuilder) WithoutName() *ResourceBuilder

WithoutName removes the metadata.name from the object, mainly used for desired resources as we do not expect any name.

func (*ResourceBuilder) WithoutStatus

func (b *ResourceBuilder) WithoutStatus() *ResourceBuilder

WithoutStatus removes the status from the object, mainly used for desired resources as we do not expect any status.

type RunFunctionRequestBuilder

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

RunFunctionRequestBuilder helps build RunFunctionRequest objects.

func NewRequestBuilder

func NewRequestBuilder() *RunFunctionRequestBuilder

NewRequestBuilder creates a new builder instance.

func (*RunFunctionRequestBuilder) Build

Build returns the constructed RunFunctionRequest.

func (*RunFunctionRequestBuilder) Wdc added in v1.0.3

Wdc adds a desired composite resource.

func (*RunFunctionRequestBuilder) Wdr added in v1.0.3

Wdr adds a desired resource with the given name.

func (*RunFunctionRequestBuilder) WithDesiredComposite added in v1.0.3

func (b *RunFunctionRequestBuilder) WithDesiredComposite(
	composite *ResourceBuilder,
) *RunFunctionRequestBuilder

WithDesiredComposite adds a desired composite resource.

func (*RunFunctionRequestBuilder) WithDesiredResource added in v1.0.3

func (b *RunFunctionRequestBuilder) WithDesiredResource(
	name string,
	resource *ResourceBuilder,
	ready ...fnv1.Ready,
) *RunFunctionRequestBuilder

WithDesiredResource adds a desired resource with the given name.

func (*RunFunctionRequestBuilder) WithInput

WithInput sets the input resource.

func (*RunFunctionRequestBuilder) WithMetaTag

WithMetaTag adds a meta tag.

func (*RunFunctionRequestBuilder) WithObservedComposite

func (b *RunFunctionRequestBuilder) WithObservedComposite(
	composite *ResourceBuilder,
) *RunFunctionRequestBuilder

WithObservedComposite adds an observed composite resource.

func (*RunFunctionRequestBuilder) WithObservedResource

func (b *RunFunctionRequestBuilder) WithObservedResource(
	name string,
	resource *ResourceBuilder,
	ready ...fnv1.Ready,
) *RunFunctionRequestBuilder

WithObservedResource adds an observed resource with the given name.

func (*RunFunctionRequestBuilder) WithRequiredResources

func (b *RunFunctionRequestBuilder) WithRequiredResources(
	name string,
	resources ...*structpb.Struct,
) *RunFunctionRequestBuilder

WithRequiredResources adds required resources with the given name.

func (*RunFunctionRequestBuilder) Woc

Woc adds an observed composite resource.

func (*RunFunctionRequestBuilder) Wor

Wor adds an observed resource with the given name.

type RunFunctionResponseBuilder

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

RunFunctionResponseBuilder helps build RunFunctionResponse objects.

func NewResponseBuilder

func NewResponseBuilder() *RunFunctionResponseBuilder

NewResponseBuilder creates a new builder instance.

func (*RunFunctionResponseBuilder) Build

Build returns the constructed RunFunctionResponse.

func (*RunFunctionResponseBuilder) Wdr

Wdr adds a desired resource with the given name.

func (*RunFunctionResponseBuilder) WithCondition

func (b *RunFunctionResponseBuilder) WithCondition(
	type_ string,
	status fnv1.Status,
	reason string,
	target fnv1.Target,
) *RunFunctionResponseBuilder

WithCondition adds a condition to the response.

func (*RunFunctionResponseBuilder) WithDesiredComposite

func (b *RunFunctionResponseBuilder) WithDesiredComposite(
	composite *structpb.Struct,
) *RunFunctionResponseBuilder

WithDesiredComposite sets the desired composite resource.

func (*RunFunctionResponseBuilder) WithDesiredResource

func (b *RunFunctionResponseBuilder) WithDesiredResource(
	name string,
	res *ResourceBuilder,
	ready ...fnv1.Ready,
) *RunFunctionResponseBuilder

WithDesiredResource adds a desired resource with the given name.

func (*RunFunctionResponseBuilder) WithMetaTag

WithMetaTag adds a meta tag.

func (*RunFunctionResponseBuilder) WithNormalResult

func (b *RunFunctionResponseBuilder) WithNormalResult(message string) *RunFunctionResponseBuilder

WithNormalResult adds a normal severity result.

func (*RunFunctionResponseBuilder) WithRequiredResources

func (b *RunFunctionResponseBuilder) WithRequiredResources(
	name string,
	selector *fnv1.ResourceSelector,
) *RunFunctionResponseBuilder

WithRequiredResources adds extra resources with the given name.

func (*RunFunctionResponseBuilder) WithResult

func (b *RunFunctionResponseBuilder) WithResult(
	severity fnv1.Severity,
	message string,
	target fnv1.Target,
) *RunFunctionResponseBuilder

WithResult adds a result to the response.

func (*RunFunctionResponseBuilder) WithTTL

WithTTL sets the TTL in the response meta.

type StringMatcher added in v1.0.4

type StringMatcher interface {
	// MatchString reports whether got satisfies the matcher. Implementations apply normalize
	// to got, and to their own expectation wherever it is compared literally.
	MatchString(got string, normalize Normalize) bool
	// String describes the expectation. It is used in assertion failure output.
	String() string
}

StringMatcher matches a string value, such as an error message or the message of a function result. Use Equal, Contains, Matching or MatchingRegexp to create one.

func Contains added in v1.0.4

func Contains(substrs ...string) StringMatcher

Contains matches a message that contains all the given substrings. Prefer it over an exact match when part of the message comes from a library that randomizes its wording.

func Equal added in v1.0.4

func Equal(want string) StringMatcher

Equal matches a message that equals want once both sides are normalized.

func Matching added in v1.0.4

func Matching(pattern string) StringMatcher

Matching matches a message matching the given regular expression. It panics if pattern does not compile, just like regexp.MustCompile.

func MatchingRegexp added in v1.0.4

func MatchingRegexp(re *regexp.Regexp) StringMatcher

MatchingRegexp matches a message matching the given regular expression.

type Want

type Want struct {
	Rsp *fnv1.RunFunctionResponse
	// Err is the expected error. A plain error matches either by errors.Is or by its
	// normalized message, see NormalizeErrorMessage. Assign an ErrorMatcher such as
	// ErrorContains or ErrorIs to match an error whose message is not fully predictable.
	// If an error is expected, the response is not verified.
	Err error
}

Want function response and error.

Jump to

Keyboard shortcuts

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