testing

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2025 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultScriptOutputPrefix = "##output##"

DefaultScriptOutputPrefix the prefix of script output Deprecated: move to testing/script DefaultScriptOutputPrefix

Variables

View Source
var IgnoreVolatileTime = cmpopts.IgnoreTypes(apis.VolatileTime{})

IgnoreVolatileTime is a cmp option to ignore VolatileTime

Functions

func AddReportEntriesAsYaml

func AddReportEntriesAsYaml(name string, objs ...interface{})

AddReportEntriesAsYaml adds multiple report entries formatted as YAML to the current SpecReport. The Report entry visibility is set to ReportEntryVisibilityFailureOrVerbose.

Example:

configMap := &corev1.ConfigMap{}
service := &corev1.Service{}
client.Get(ctx, key, configMap)
client.Get(ctx, serviceKey, service)
AddReportEntriesAsYaml("configuration", configMap, service)

Note: Any pointer will be only printed as the final value when testing is completed for current value provide the object as value:

AddReportEntriesAsYaml("previous-configuration", *configMap)

func AddReportEntryAsYaml

func AddReportEntryAsYaml(name string, obj interface{})

AddReportEntryAsYaml marshals the given object as YAML and adds it to the test report with the given name. The Report entry visibility is set to ReportEntryVisibilityFailureOrVerbose. Note: Any pointer will be only printed as the final value when testing is completed for current value provide the object as value.

Example:

configMap := &corev1.ConfigMap{}
client.Get(ctx, key, configMap)
AddReportEntryAsYaml("configuration", configMap)

Note: Any pointer will be only printed as the final value when testing is completed for current value provide the object as value:

AddReportEntryAsYaml("previous-configuration", *configMap)

Will automatically redact secret data for corev1.Secret objects.

func Case

func Case(caseName string) Labels

Case the unique case name label

func ConditionIsReady

func ConditionIsReady(condition *apis.Condition) error

ConditionIsReady returns an error if the condition status is not True useful for Eventually checks

func ConvertTypeMetaToGroupVersionResource

func ConvertTypeMetaToGroupVersionResource(typeMeta metav1.TypeMeta) schema.GroupVersionResource

ConvertTypeMetaToGroupVersionResource converts type meta to group version resource

func DefaultConvertRuntimeToClientobjectFunc

func DefaultConvertRuntimeToClientobjectFunc(runtimeObj runtime.Object) (obj client.Object, err error)

DefaultConvertRuntimeToClientobjectFunc convert runtime.Object to client.Object be similar to convertFromUnstructuredIfNecessary

func DeleteResources

func DeleteResources(file string, clt client.Client) (err error)

DeleteResources delete resources contained in the file

func DiffEqualTo

func DiffEqualTo(expected interface{}, diffCleanFuncs ...func(object interface{}) interface{}) gomega.OmegaMatcher

DiffEqualTo will use github.com/google/go-cmp/cmp.Diff to compare you can use diffCleanFuncs to change object in order to clean some fields that you don't want to compare Deprecated: use assertions.DiffEqual instead

func ExpectDiff deprecated

func ExpectDiff(actual interface{}, expected interface{}, diffCleanFuncs ...func(object interface{}) interface{}) gomega.Assertion

ExpectDiff will using github.com/google/go-cmp/cmp.Diff to compare two data as default, it will not compare fields that have some undetermined value like uid, timestamp when compare kubernetes object you can use diffCleanFuncs to change object in order to clean some fields that you don't want to compare eg: clean status when compare

ExpectDiff(actual, expected, KubeObjectDiffClean, func(object ctrlclient.Object) {
	object.(*corev1.Pod).Status = corev1.PodStatus{} // do not compare Status
	return object
}).Should(BeEmpty())

Deprecated: should use regular Expect with assertions.DiffEqual instead Example:

Expect(obj).To(DiffEqual(expected, cmpopts.IgnoreTypes(v1.TypeMeta{}, v1.PodStatus{})))

func GetCaseNames

func GetCaseNames(name string) []string

GetCaseNames Resolve the case identifier from the testcase name in the junit report For go test junit report, the case name may be started with `Test`, e.g: TestGetProject For ginkgo test junit report, the case name may contain the {case:%s} string, e.g: [It] when xxxx [{case:GetProject}]

func GetDefaultEnv

func GetDefaultEnv(key string, defaultValue string) string

GetDefaultEnv get the parameter from env, if not set it use the defaultValue instead

func GetDefaultLogger

func GetDefaultLogger() *uberzap.SugaredLogger

GetDefaultLogger returns the default logger for testing

func InitGinkgoWithLogger

func InitGinkgoWithLogger() *uberzap.SugaredLogger

InitGinkgoWithLogger initializes Ginkgo and returns a logger.

func InitializeGinkgoConfig

func InitializeGinkgoConfig()

InitializeGinkgoConfig initializes the Ginkgo configuration.

func KubeObjectDiffClean deprecated

func KubeObjectDiffClean(object interface{}) interface{}

KubeObjectDiffClean will clean these fields in order to clean when diff kubernetes objects

  • CreationTimestamp
  • ManagedFields
  • UID
  • ResourceVersion
  • Generation
  • SelfLink

Deprecated: use assertions.DiffEqual and assertions.IgnoreObjectMetaFields instead

func ListByGVK

ListByGVK creates a new UnstructuredList initialized with the given GroupVersionKind. Very useful for listing resources using only GroupVersionKind.

func LoadJSON

func LoadJSON(file string, obj interface{}) (err error)

LoadJSON loads json

func LoadKubeResources

func LoadKubeResources(file string, clt client.Client, converts ...ConvertRuntimeObjctToClientObjectFunc) (err error)

LoadKubeResources loading kubernetes resources

func LoadKubeResourcesAsUnstructured

func LoadKubeResourcesAsUnstructured(file string) (objs []unstructured.Unstructured, err error)

func LoadMultiYamlOrJson

func LoadMultiYamlOrJson[T any](file string, list *[]T) (err error)

LoadMultiYamlOrJson loads multi yamls

func LoadMultiYamlOrJsonFromBytes

func LoadMultiYamlOrJsonFromBytes[T any](data []byte, list *[]T) (err error)

LoadMultiYamlOrJsonFromBytes loads multi yamls For historical reasons, this method still supports JSON documents separated by --- However, --- is not a valid separator for JSON documents. To be compatible with the previous handling logic, we cannot directly use the k8s built-in multiple document unmarshalling method and need to read line by line to implement it.

func LoadObjectOrDie

func LoadObjectOrDie(g *WithT, file string, obj metav1.Object, patches ...func(metav1.Object)) metav1.Object

LoadObjectOrDie loads object from yaml and returns

func LoadObjectReferenceOrDie

func LoadObjectReferenceOrDie(g *WithT, file string, obj *corev1.ObjectReference, patches ...func(*corev1.ObjectReference)) *corev1.ObjectReference

LoadObjectReferenceOrDie loads object reference from yaml and returns

func LoadResourceFromFile

func LoadResourceFromFile(scheme *runtime.Scheme, path string) (obj runtime.Object, err error)

func LoadResourcesFromFile

func LoadResourcesFromFile(scheme *runtime.Scheme, path string) (objs []runtime.Object, err error)

func LoadYAML

func LoadYAML(file string, obj interface{}) (err error)

LoadYAML loads yaml

func MustLoadFileBytes

func MustLoadFileBytes(file string) []byte

MustLoadFileBytes loads a file as []bytes will panic if if failes ONLY FOR TEST USAGE

func MustLoadFileString

func MustLoadFileString(file string, content *string)

MustLoadFileString loads a file as string will panic if if failes ONLY FOR TEST USAGE

func MustLoadJSON

func MustLoadJSON(file string, obj interface{})

MustLoadJSON loads json or panics if the parse fails.

func MustLoadMultiYamlOrJson

func MustLoadMultiYamlOrJson[T any](file string, list *[]T)

MustLoadMultiYamlOrJson loads multi yamls or panics if the parse fails.

func MustLoadReturnObjectFromYAML

func MustLoadReturnObjectFromYAML(file string, obj interface{}) interface{}

MustLoadReturnObjectFromYAML loads and object from yaml file and returns as interface{} if any loading errors happen will panic TO BE USED IN TESTS, DO NOT USE IN PRODUCTION CODE

func MustLoadYaml

func MustLoadYaml(file string, obj interface{})

MustLoadYaml loads yaml or panics if the parse fails.

func NewGinkgoLogger

func NewGinkgoLogger() *uberzap.SugaredLogger

NewGinkgoLogger creates a new logger for Ginkgo tests.

func PrintDiffWantGot

func PrintDiffWantGot(diff string) string

PrintDiffWantGot takes a diff string generated by cmp.Diff and returns it in a consistent format for reuse across all of our tests. This func assumes that the order of arguments passed to cmp.Diff was (want, got) or, in other words, the expectedResult then the actualResult.

func ReflectName

func ReflectName(obj interface{}) string

ReflectName reflect the type name of the object

func RestoreDirectories

func RestoreDirectories(fs embed.FS, dirName string, targetDir string)

RestoreDirectories restore directories from embed.FS to targetDir Deprecated: move to testing/script RestoreDirectories

func RuntimeObjectFromUnstructured

func RuntimeObjectFromUnstructured(scheme *runtime.Scheme, u *unstructured.Unstructured) (runtime.Object, error)

RuntimeObjectFromUnstructured converts an unstructured to a runtime object

func SetName

func SetName(name string) func(metav1.Object)

func SliceToInterfaceSlice

func SliceToInterfaceSlice[T any](s []T) []interface{}

SliceToInterfaceSlice convert a slice to a slice of interface

func SliceToRuntimeOjbect

func SliceToRuntimeOjbect[T any](s []T) []runtime.Object

SliceToRuntimeOjbect convert slice to runtime.Object

func ToObjectList

func ToObjectList[T client.Object](list []T) []client.Object

ToObjectList converts resource list to a list of client.Object

func UnstructedToTyped

func UnstructedToTyped(from unstructured.Unstructured, to interface{}) error

UnstructedToTyped converts an unstructured object into a object Warning: This SHOULD never be used in production code, only in test code

func WarningOnError

func WarningOnError(logger *zap.SugaredLogger, err error, message string)

WarningOnError set a warning on error

Types

type ConditionBuilder

type ConditionBuilder struct {
	apis.Condition
}

ConditionBuilder builds a conditions in a builder pattern

func BuildCondition

func BuildCondition() *ConditionBuilder

BuildCondition starts a condition builder object useful for unit tests that require validating multiple conditions

func (*ConditionBuilder) Done

func (c *ConditionBuilder) Done() *apis.Condition

SetReasonMessage returns a condition

func (*ConditionBuilder) SetReasonMessage

func (c *ConditionBuilder) SetReasonMessage(reason, message string, formtKeyValues ...interface{}) *ConditionBuilder

SetReasonMessage sets the message for the condition

func (*ConditionBuilder) SetStatus

SetStatus sets the status for the condition

func (*ConditionBuilder) SetType

SetType sets the type for the condition

type ConvertRuntimeObjctToClientObjectFunc

type ConvertRuntimeObjctToClientObjectFunc func(runtime.Object) (client.Object, error)

type ScriptResult

type ScriptResult struct {
	OutputDataPrefix string
	// contains filtered or unexported fields
}

ScriptResult the result of script execution Deprecated: move to testing/script ScriptResult

func ExecBashScript

func ExecBashScript(script string, params ...string) *ScriptResult

ExecBashScript exec bash script with params Deprecated: move to testing/script ExecBashScript

func ExecScript

func ExecScript(name string, arg ...string) *ScriptResult

ExecScript exec script with params Deprecated: move to testing/script ExecScript

func (*ScriptResult) Error

func (p *ScriptResult) Error() error

Error get the error of a script execution

func (*ScriptResult) ExitCode

func (p *ScriptResult) ExitCode() int

ExitCode get the exit code of a script execution

func (*ScriptResult) ExitMessage

func (p *ScriptResult) ExitMessage() string

ExitMessage get the exit message of a script execution

func (*ScriptResult) OutputData

func (p *ScriptResult) OutputData(dataPrefix string) string

OutputData get the output of a script execution, it can be a structured data, e.g: json string

func (*ScriptResult) Stderr

func (p *ScriptResult) Stderr() string

Stderr get the error output of a script execution

func (*ScriptResult) Stdout

func (p *ScriptResult) Stdout() string

Stdout get the output of a script execution

Directories

Path Synopsis
Package assertions contains all the assertions that can be used in tests for general testing.
Package assertions contains all the assertions that can be used in tests for general testing.
Package mock contains useful functionality for testing
Package mock contains useful functionality for testing
github.com/AlaudaDevops/pkg
Package sharedmain is a generated GoMock package.
Package sharedmain is a generated GoMock package.
github.com/AlaudaDevops/pkg/apis/meta/v1alpha1
Package apis is a generated GoMock package.
Package apis is a generated GoMock package.
github.com/AlaudaDevops/pkg/multicluster
Package multicluster is a generated GoMock package.
Package multicluster is a generated GoMock package.
github.com/AlaudaDevops/pkg/warnings/condition
Package warnings is a generated GoMock package.
Package warnings is a generated GoMock package.
github.com/minio/minio-go
Package pkg is a generated GoMock package.
Package pkg is a generated GoMock package.
k8s.io/cli-runtime/pkg/genericclioptions
Package genericclioptions is a generated GoMock package.
Package genericclioptions is a generated GoMock package.
k8s.io/client-go/kubernetes
Package kubernetes is a generated GoMock package.
Package kubernetes is a generated GoMock package.
knative.dev/pkg/apis
Package apis is a generated GoMock package.
Package apis is a generated GoMock package.
sigs.k8s.io/controller-runtime/pkg/client
Package client is a generated GoMock package.
Package client is a generated GoMock package.
sigs.k8s.io/controller-runtime/pkg/manager
Package manager is a generated GoMock package.
Package manager is a generated GoMock package.

Jump to

Keyboard shortcuts

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