utils

package
v0.0.0-...-159d35f Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2024 License: Apache-2.0 Imports: 58 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var APIServerDefaultArgs = []string{
	"--advertise-address=127.0.0.1",
	"--etcd-servers={{ if .EtcdURL }}{{ .EtcdURL.String }}{{ end }}",
	"--cert-dir={{ .CertDir }}",
	"--insecure-port={{ if .URL }}{{ .URL.Port }}{{else}}0{{ end }}",
	"{{ if .URL }}--insecure-bind-address={{ .URL.Hostname }}{{ end }}",
	"--secure-port={{ if .SecurePort }}{{ .SecurePort }}{{ end }}",

	"--disable-admission-plugins=ServiceAccount",
	"--service-cluster-ip-range=10.0.0.0/24",
	"--allow-privileged=true",
}

APIServerDefaultArgs are copied from the internal controller-runtime pkg/internal/testing/integration/internal/apiserver.go sadly, we can't import them anymore since it is an internal package

Functions

func CleanObjectForMarshalling

func CleanObjectForMarshalling(o runtime.Object) (runtime.Object, error)

CleanObjectForMarshalling removes unnecessary object metadata that should not be included in serialization and diffs.

func ConvertUnstructured

func ConvertUnstructured(in client.Object) (client.Object, error)

ConvertUnstructured converts an unstructured object to the known struct. If the type is not known, then the unstructured object is returned unmodified.

func CreateOrUpdate

func CreateOrUpdate(ctx context.Context, cl client.Client, obj client.Object, retryOnError bool) (updated bool, err error)

CreateOrUpdate will create obj if it does not exist and update if it it does. retryonerror indicates whether we retry in case of conflict Returns true if the object was updated and false if it was created.

func FakeDiscoveryClient

func FakeDiscoveryClient() discovery.DiscoveryInterface

FakeDiscoveryClient returns a fake discovery client that is populated with some types for use in unit tests.

func GetAPIResource

GetAPIResource returns the APIResource object for a specific GroupVersionKind.

func GetArgs

func GetArgs(ctx context.Context, cmd harness.Command, namespace string, envMap map[string]string) (*exec.Cmd, error)

GetArgs parses a command line string into its arguments and appends a namespace if it is not already set.

func InClusterConfig

func InClusterConfig() (bool, error)

InClusterConfig returns true if in cluster, false if not

func InstallManifests

func InstallManifests(ctx context.Context, c client.Client, dClient discovery.DiscoveryInterface, manifestsDir string, kinds ...runtime.Object) ([]*apiextv1.CustomResourceDefinition, error)

InstallManifests recurses over ManifestsDir to install all resources defined in YAML manifests.

func IsJSONSyntaxError

func IsJSONSyntaxError(err error) bool

IsJSONSyntaxError returns true if the error is a JSON syntax error.

func IsSubset

func IsSubset(expected, actual interface{}, currentPath string, strategyFactory ArrayComparisonStrategyFactory) error

IsSubset checks to see if `expected` is a subset of `actual`. A "subset" is an object that is equivalent to the other object, but where map keys found in actual that are not defined in expected are ignored.

func Kubeconfig

func Kubeconfig(cfg *rest.Config, w io.Writer) error

Kubeconfig converts a rest.Config into a YAML kubeconfig and writes it to w

func LoadYAML

func LoadYAML(path string, r io.Reader) ([]client.Object, error)

LoadYAML loads all objects from a reader

func LoadYAMLFromFile

func LoadYAMLFromFile(path string) ([]client.Object, error)

LoadYAMLFromFile loads all objects from a YAML file.

func MarshalObject

func MarshalObject(o runtime.Object, w io.Writer) error

MarshalObject marshals a Kubernetes object to a YAML string.

func MarshalObjectJSON

func MarshalObjectJSON(o runtime.Object, w io.Writer) error

MarshalObjectJSON marshals a Kubernetes object to a JSON string.

func MatchesKind

func MatchesKind(obj runtime.Object, kinds ...runtime.Object) bool

MatchesKind returns true if the Kubernetes kind of obj matches any of kinds.

func Namespaced

func Namespaced(dClient discovery.DiscoveryInterface, obj runtime.Object, namespace string) (string, string, error)

Namespaced sets the namespace on an object to namespace, if it is a namespace scoped resource. If the resource is cluster scoped, then it is ignored and the namespace is not set. If it is a namespaced resource and a namespace is already set, then the namespace is unchanged.

func NewClusterRoleBinding

func NewClusterRoleBinding(apiVersion, kind, name, namespace string, serviceAccount string, roleName string) runtime.Object

NewClusterRoleBinding Create a clusterrolebinding for the serviceAccount passed

func NewPod

func NewPod(name, namespace string) *unstructured.Unstructured

NewPod creates a new pod object.

func NewResource

func NewResource(apiVersion, kind, name, namespace string) *unstructured.Unstructured

NewResource generates a Kubernetes object using the provided apiVersion, kind, name, and namespace. The name and namespace are omitted if empty.

func NewV1Pod

func NewV1Pod(name, namespace, serviceAccountName string) *corev1.Pod

NewV1Pod returns a new corev1.Pod object. Each of name, namespace and serviceAccountName are set if non-empty.

func ObjectKey

func ObjectKey(obj runtime.Object) client.ObjectKey

ObjectKey returns an instantiated ObjectKey for the provided object.

func PatchObject

func PatchObject(actual, expected runtime.Object) error

PatchObject updates expected with the Resource Version from actual. In the future, PatchObject may perform a strategic merge of actual into expected.

func PrettyDiff

func PrettyDiff(expected runtime.Object, actual runtime.Object) (string, error)

PrettyDiff creates a unified diff highlighting the differences between two Kubernetes resources

func ReadMockControllerConfig

func ReadMockControllerConfig(filename string) (config []string, err error)

ReadMockControllerConfig reads the mock control plane config file

func ResourceID

func ResourceID(obj runtime.Object) string

ResourceID returns a human readable identifier indicating the object kind, name, and namespace.

func Retry

func Retry(ctx context.Context, fn func(context.Context) error, errValidationFuncs ...func(error) bool) error

Retry retries a method until the context expires or the method returns an unvalidated error.

func RunAssertCommands

func RunAssertCommands(ctx context.Context, logger Logger, namespace string, commands []harness.TestAssertCommand, workdir string, timeout int, kubeconfigOverride string) ([]*exec.Cmd, error)

RunAssertCommands runs a set of commands specified as TestAssertCommand

func RunCommand

func RunCommand(ctx context.Context, namespace string, cmd harness.Command, cwd string, stdout io.Writer, stderr io.Writer, logger Logger, timeout int, kubeconfigOverride string) (*exec.Cmd, error)

RunCommand runs a command with args. args gets split on spaces (respecting quoted strings). if the command is run in the background a reference to the process is returned for later cleanup

func RunCommands

func RunCommands(ctx context.Context, logger Logger, namespace string, commands []harness.Command, workdir string, timeout int, kubeconfigOverride string) ([]*exec.Cmd, error)

RunCommands runs a set of commands, returning any errors. If any (non-background) command fails, the following commands are skipped commands running in the background are returned

func RunTests

func RunTests(testName string, testToRun string, parallelism int, testFunc func(*testing.T))

RunTests runs a Go test method without requiring the Go compiler. This does not currently support test caching. If testToRun is set to a non-empty string, it is passed as a `-run` argument to the go test harness. If paralellism is set, it limits the number of concurrently running tests.

func Scheme

func Scheme() *runtime.Scheme

Scheme returns an initialized Kubernetes Scheme.

func SetAnnotation

func SetAnnotation(obj *unstructured.Unstructured, key, value string) *unstructured.Unstructured

SetAnnotation sets the given key and value in the object's annotations, returning a copy.

func ValidateErrors

func ValidateErrors(err error, errValidationFuncs ...func(error) bool) error

ValidateErrors accepts an error as its first argument and passes it to each function in the errValidationFuncs slice, if any of the methods returns true, the method returns nil, otherwise it returns the original error.

func WaitForDelete

func WaitForDelete(c *RetryClient, objs []runtime.Object) error

WaitForDelete waits for the provide runtime objects to be deleted from cluster

func WaitForSA

func WaitForSA(config *rest.Config, name, namespace string) error

WaitForSA waits for a service account to be present

func WithAnnotations

func WithAnnotations(obj runtime.Object, annotations map[string]string) runtime.Object

WithAnnotations sets the annotations on an object.

func WithKeyValue

func WithKeyValue(obj *unstructured.Unstructured, key string, value map[string]interface{}) (*unstructured.Unstructured, error)

WithKeyValue sets key in the provided object to value.

func WithLabels

func WithLabels(t *testing.T, obj *unstructured.Unstructured, labels map[string]string) *unstructured.Unstructured

WithLabels sets the labels on an object.

func WithNamespace

func WithNamespace(obj *unstructured.Unstructured, namespace string) *unstructured.Unstructured

WithNamespace naively applies the namespace to the object. Used mainly in tests, otherwise use Namespaced.

func WithSpec

func WithSpec(t *testing.T, obj *unstructured.Unstructured, spec map[string]interface{}) *unstructured.Unstructured

WithSpec applies the provided spec to the Kubernetes object.

func WithStatus

func WithStatus(t *testing.T, obj *unstructured.Unstructured, status map[string]interface{}) *unstructured.Unstructured

WithStatus applies the provided status to the Kubernetes object.

Types

type ArrayComparisonStrategy

type ArrayComparisonStrategy = func(expectedData, actualData interface{}) error

func StrategyAnywhere

func StrategyAnywhere(path string, strategyFactory ArrayComparisonStrategyFactory) ArrayComparisonStrategy

func StrategyExact

func StrategyExact(path string, strategyFactory ArrayComparisonStrategyFactory) ArrayComparisonStrategy

type ArrayComparisonStrategyFactory

type ArrayComparisonStrategyFactory = func(path string) ArrayComparisonStrategy

func DefaultStrategyFactory

func DefaultStrategyFactory() ArrayComparisonStrategyFactory

type Client

type Client interface {
	client.Client
	// Watch watches a specific object and returns all events for it.
	Watch(ctx context.Context, obj runtime.Object) (watch.Interface, error)
}

Client is the controller-runtime Client interface with an added Watch method.

type DockerClient

type DockerClient interface {
	NegotiateAPIVersion(context.Context)
	VolumeCreate(context.Context, volumetypes.VolumeCreateBody) (dockertypes.Volume, error)
	ImageSave(context.Context, []string) (io.ReadCloser, error)
}

DockerClient is a wrapper interface for the Docker library to support unit testing.

type Logger

type Logger interface {
	Log(args ...interface{})
	Logf(format string, args ...interface{})
	WithPrefix(string) Logger
	Write(p []byte) (n int, err error)
	Flush()
}

Logger is an interface used by the KUTTL test operator to provide logging of tests.

type RetryClient

type RetryClient struct {
	Client client.Client
	// contains filtered or unexported fields
}

RetryClient implements the Client interface, with retries built in.

func NewRetryClient

func NewRetryClient(cfg *rest.Config, opts client.Options) (*RetryClient, error)

NewRetryClient initializes a new Kubernetes client that automatically retries on network-related errors.

func (*RetryClient) Create

func (r *RetryClient) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error

Create saves the object obj in the Kubernetes cluster.

func (*RetryClient) Delete

func (r *RetryClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error

Delete deletes the given obj from Kubernetes cluster.

func (*RetryClient) DeleteAllOf

func (r *RetryClient) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error

DeleteAllOf deletes the given obj from Kubernetes cluster.

func (*RetryClient) Get

func (r *RetryClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error

Get retrieves an obj for the given object key from the Kubernetes Cluster. obj must be a struct pointer so that obj can be updated with the response returned by the Server.

func (*RetryClient) List

func (r *RetryClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error

List retrieves list of objects for a given namespace and list options. On a successful call, Items field in the list will be populated with the result returned from the server.

func (*RetryClient) Patch

func (r *RetryClient) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error

Patch patches the given obj in the Kubernetes cluster. obj must be a struct pointer so that obj can be updated with the content returned by the Server.

func (*RetryClient) RESTMapper

func (r *RetryClient) RESTMapper() meta.RESTMapper

RESTMapper returns the rest mapper this client is using.

func (*RetryClient) Scheme

func (r *RetryClient) Scheme() *runtime.Scheme

Scheme returns the scheme this client is using.

func (*RetryClient) Status

func (r *RetryClient) Status() client.StatusWriter

Status returns a client which can update status subresource for kubernetes objects.

func (*RetryClient) Update

func (r *RetryClient) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error

Update updates the given obj in the Kubernetes cluster. obj must be a struct pointer so that obj can be updated with the content returned by the Server.

func (*RetryClient) Watch

func (r *RetryClient) Watch(ctx context.Context, obj runtime.Object) (watch.Interface, error)

Watch watches a specific object and returns all events for it.

type RetryStatusWriter

type RetryStatusWriter struct {
	StatusWriter client.StatusWriter
}

RetryStatusWriter implements the StatusWriter interface, with retries built in.

func (*RetryStatusWriter) Patch

func (r *RetryStatusWriter) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error

Patch patches the given obj in the Kubernetes cluster. obj must be a struct pointer so that obj can be updated with the content returned by the Server.

func (*RetryStatusWriter) Update

func (r *RetryStatusWriter) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error

Update updates the given obj in the Kubernetes cluster. obj must be a struct pointer so that obj can be updated with the content returned by the Server.

type SubsetError

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

SubsetError is an error type used by IsSubset for tracking the path in the struct.

func (*SubsetError) AppendPath

func (e *SubsetError) AppendPath(key string)

AppendPath appends key to the existing struct path. For example, in struct member `a.Key1.Key2`, the path would be ["Key1", "Key2"]

func (*SubsetError) Error

func (e *SubsetError) Error() string

Error implements the error interface.

type TestEnvironment

type TestEnvironment struct {
	Environment     *envtest.Environment
	Config          *rest.Config
	Client          Client
	DiscoveryClient discovery.DiscoveryInterface
}

TestEnvironment is a struct containing the envtest environment, Kubernetes config and clients.

func StartTestEnvironment

func StartTestEnvironment(kubeAPIServerFlags []string, attachControlPlaneOutput bool) (env TestEnvironment, err error)

StartTestEnvironment is a wrapper for controller-runtime's envtest that creates a Kubernetes API server and etcd suitable for use in tests.

type TestLogger

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

TestLogger implements the Logger interface to be compatible with the go test operator's output buffering (without this, the use of Parallel tests combined with subtests causes test output to be mixed).

func NewTestLogger

func NewTestLogger(test *testing.T, prefix string) *TestLogger

NewTestLogger creates a new test logger.

func (*TestLogger) Flush

func (t *TestLogger) Flush()

func (*TestLogger) Log

func (t *TestLogger) Log(args ...interface{})

Log logs the provided arguments with the logger's prefix. See testing.Log for more details.

func (*TestLogger) Logf

func (t *TestLogger) Logf(format string, args ...interface{})

Logf logs the provided arguments with the logger's prefix. See testing.Logf for more details.

func (*TestLogger) WithPrefix

func (t *TestLogger) WithPrefix(prefix string) Logger

WithPrefix returns a new TestLogger with the provided prefix appended to the current prefix.

func (*TestLogger) Write

func (t *TestLogger) Write(p []byte) (n int, err error)

Write implements the io.Writer interface. Logs each line written to it, buffers incomplete lines until the next Write() call.

Jump to

Keyboard shortcuts

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