testing

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2020 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Copyright 2019 The Knative Authors.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const TestField = "test-field"

Variables

View Source
var (
	ValidListOptions = options.ListOptions{
		Namespace: "default",
	}
	InvalidListOptions           = options.ListOptions{}
	InvalidListOptionsFieldError = cli.ErrMissingOneOf(cli.NamespaceFlagName, cli.AllNamespacesFlagName)
)
View Source
var (
	ValidResourceOptions = options.ResourceOptions{
		Namespace: "default",
		Name:      "push-credentials",
	}
	InvalidResourceOptions           = options.ResourceOptions{}
	InvalidResourceOptionsFieldError = cli.FieldErrors{}.Also(
		cli.ErrMissingField(cli.NamespaceFlagName),
		cli.ErrMissingField(cli.NameArgumentName),
	)
)
View Source
var (
	ValidDeleteOptions = options.DeleteOptions{
		Namespace: "default",
		Names:     []string{"my-resource"},
	}
	InvalidDeleteOptions = options.DeleteOptions{
		Namespace: "default",
	}
	InvalidDeleteOptionsFieldError = cli.ErrMissingOneOf(cli.AllFlagName, cli.NamesArgumentName)
)

Functions

func InduceFailure

func InduceFailure(verb, resource string) clientgotesting.ReactionFunc

InduceFailure is used in conjunction with TableTest's WithReactors field. Tests that want to induce a failure in a row of a TableTest would add:

WithReactors: []clientgotesting.ReactionFunc{
   // Makes calls to create revisions return an error.
   InduceFailure("create", "revisions"),
},

func ValidateCreates added in v0.5.0

func ValidateCreates(ctx context.Context, action clientgotesting.Action) (handled bool, ret runtime.Object, err error)

func ValidateUpdates added in v0.5.0

func ValidateUpdates(ctx context.Context, action clientgotesting.Action) (handled bool, ret runtime.Object, err error)

Types

type ActionRecorder added in v0.5.0

type ActionRecorder interface {
	Actions() []clientgotesting.Action
}

ActionRecorder contains list of K8s request actions.

type ActionRecorderList added in v0.5.0

type ActionRecorderList []ActionRecorder

ActionRecorderList is a list of ActionRecorder objects.

func (ActionRecorderList) ActionsByVerb added in v0.5.0

func (l ActionRecorderList) ActionsByVerb() (Actions, error)

ActionsByVerb fills in Actions objects, sorting the actions by verb.

type Actions added in v0.5.0

Actions stores list of Actions recorded by the reactors.

type CommandTable

type CommandTable []CommandTableRecord

CommandTable provides a declarative model for testing interactions with Kubernetes clientsets via Cobra commands.

Fake clientsets are used to stub calls to the Kubernetes API server. GivenObjects populate a local cache for clientsets to respond to get and list operations (update and delete will error if the object does not exist and create operations will error if the resource does exist).

ExpectCreates and ExpectUpdates each contain objects that are compared directly to resources received by the clientsets. ExpectDeletes and ExpectDeleteCollections contain references to the resources impacted by the call since these calls do not receive an object.

Errors can be injected into API calls by reactor functions specified in WithReactors. A ReactionFunc is able to intercept each clientset operation to observe or mutate the request or response.

ShouldError must correctly reflect whether the command is expected to return an error, otherwise the testcase will fail. Custom assertions based on the content of the error object and the console output from the command are available with the Verify callback.

Advanced state may be configured before and after each record by the Prepare and CleanUp callbacks respectively.

func (CommandTable) Run

func (ct CommandTable) Run(t *testing.T, cmdFactory func(context.Context, *cli.Config) *cobra.Command)

Run each record for the table. Tables with a focused record will run only the focused records and then fail, to prevent accidental check-in.

type CommandTableRecord

type CommandTableRecord struct {

	// Name is used to identify the record in the test results. A sub-test is created for each
	// record with this name.
	Name string
	// Skip suppresses the execution of this test record.
	Skip bool
	// Focus executes this record skipping all unfocused records. The containing test will fail to
	// prevent accidental check-in.
	Focus bool

	// Config is passed into the command factory. Mosts tests should not need to set this field.
	// If not specified, a default Config is created with a FakeClient. The Config's client will
	// always be replaced with a FakeClient configured with the given objects and reactors to
	// intercept all calls to the fake clientsets for comparison with the expected operations.
	Config *cli.Config
	// Runtimes are an optional array of runtime names to enabled on the config. If not set, the
	// default runtime set is used.
	Runtimes *[]string

	// GivenObjects represents resources that would already exist within Kubernetes. These
	// resources are passed directly to the fake clientsets.
	GivenObjects []runtime.Object
	// WithReactors installs each ReactionFunc into each fake clientset. ReactionFuncs intercept
	// each call to the clientset providing the ability to mutate the resource or inject an error.
	WithReactors []ReactionFunc
	// ExecHelper is a test case that will intercept exec calls receiving their arguments and
	// environment. The helper is able to control stdio and the exit code of the process. Test
	// cases that need to orchestrate multiple exec calls within a single test should instead use
	// a mock.
	//
	// The value of ExecHelper must map to a test function in the same package taking the form
	// `fmt.Sprintf("TestHelperProcess_%s", ExecHelper)“. The test function should distinguish
	// between test exec invocations and vanilla test calls by the `GO_WANT_HELPER_PROCESS` env.
	//
	// “`
	// func TestHelperProcess_Example(t *testing.T) {
	//     if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
	//         return
	//     }
	//     // insert custom behavior
	//     os.Exit(0)
	// }
	// “`
	ExecHelper string

	// Args are passed directly to cobra before executing the command. This is the primary
	// interface to control the behavior of the cli.
	Args []string
	// Stdin injects stub data to be read via os.Stdin for the command. Tests using stdin are
	// forced to be sequential.
	Stdin []byte

	// ExpectCreates asserts each resource with the resources passed to the Create method of the
	// fake clientsets in order.
	ExpectCreates []runtime.Object
	// ExpectUpdates asserts each resource with the resources passed to the Update method of the
	// fake clientsets in order.
	ExpectUpdates []runtime.Object
	// ExpectDeletes assert references to the Delete method of the fake clientsets in order.
	// Unlike Create and Update, Delete does not receive a full resource, so a reference is used
	// instead. The Group will be blank for 'core' resources. The Resource is not a Kind, but
	// plural lowercase name of the resource.
	ExpectDeletes []DeleteRef
	// ExpectDeleteCollections asserts references to the DeleteCollection method of the fake
	// clientsets in order. DeleteCollections behaves similarly to Deletes. Unlike Delete,
	// DeleteCollection does not contain a resource Name, but may contain a LabelSelector.
	ExpectDeleteCollections []DeleteCollectionRef

	// ShouldError indicates if the table record command execution should return an error. The
	// test will fail if this value does not reflect the returned error.
	ShouldError bool
	// ExpectOutput performs a direct comparison of this content with the command's output showing
	// a diff of any changes. The comparison is ignored for empty strings and ignores a leading
	// new line.
	ExpectOutput string
	// Verify provides the command output and error for custom assertions.
	Verify func(t *testing.T, output string, err error)

	// Prepare is called before the command is executed. It is intended to prepare that broader
	// environment before the specific table record is executed. For example, chaning the working
	// directory or setting mock expectations.
	Prepare func(t *testing.T, ctx context.Context, config *cli.Config) (context.Context, error)
	// CleanUp is called after the table record is finished and all defined assertions complete.
	// It is indended to clean up any state created in the Prepare step or during the test
	// execution, or to make assertions for mocks.
	CleanUp func(t *testing.T, ctx context.Context, config *cli.Config) error
}

CommandTableRecord is a single test case within a CommandTable. All state and assertions are defined within the record.

func (CommandTableRecord) Run

func (ctr CommandTableRecord) Run(t *testing.T, cmdFactory func(context.Context, *cli.Config) *cobra.Command)

Run a single table record for the command. It is not common to run a record outside of a table.

type DeleteCollectionRef

type DeleteCollectionRef struct {
	Group         string
	Resource      string
	Namespace     string
	LabelSelector string
}

type DeleteRef

type DeleteRef struct {
	Group     string
	Resource  string
	Namespace string
	Name      string
}

func NewDeleteRef

func NewDeleteRef(action clientgotesting.DeleteAction) DeleteRef

type FakeClient

type FakeClient struct {
	Namespace                  string
	FakeKubeRestConfig         *rest.Config
	FakeKubeClientset          *kubernetes.Clientset
	FakeRiffClientset          *projectriffclientset.Clientset
	FakeAPIExtensionsClientset *apiextensionsv1beta1clientset.Clientset
	ActionRecorderList         ActionRecorderList
}

func NewClient

func NewClient(objects ...runtime.Object) *FakeClient

func (*FakeClient) APIExtension

func (*FakeClient) Auth

func (*FakeClient) Build

func (*FakeClient) Core

func (*FakeClient) CoreRuntime

func (*FakeClient) DefaultNamespace

func (c *FakeClient) DefaultNamespace() string

func (*FakeClient) KnativeRuntime

func (*FakeClient) KubeRestConfig

func (c *FakeClient) KubeRestConfig() *rest.Config

func (*FakeClient) PrependReactor

func (c *FakeClient) PrependReactor(verb, resource string, reaction ReactionFunc)

func (*FakeClient) StreamingRuntime

type Listers

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

func NewListers

func NewListers(objs []runtime.Object) Listers

func (*Listers) GetAPIExtensionsObjects

func (l *Listers) GetAPIExtensionsObjects() []runtime.Object

func (*Listers) GetKubeObjects

func (l *Listers) GetKubeObjects() []runtime.Object

func (*Listers) GetProjectriffObjects

func (l *Listers) GetProjectriffObjects() []runtime.Object

type ObjectSorter added in v0.5.0

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

func NewObjectSorter added in v0.5.0

func NewObjectSorter(scheme *runtime.Scheme) ObjectSorter

func (*ObjectSorter) AddObjects added in v0.5.0

func (o *ObjectSorter) AddObjects(objs ...runtime.Object)

func (*ObjectSorter) IndexerForObjectType added in v0.5.0

func (o *ObjectSorter) IndexerForObjectType(obj runtime.Object) cache.Indexer

func (*ObjectSorter) ObjectsForScheme added in v0.5.0

func (o *ObjectSorter) ObjectsForScheme(scheme *runtime.Scheme) []runtime.Object

func (*ObjectSorter) ObjectsForSchemeFunc added in v0.5.0

func (o *ObjectSorter) ObjectsForSchemeFunc(funcs ...func(scheme *runtime.Scheme) error) []runtime.Object

type OptionsTable

type OptionsTable []OptionsTableRecord

func (OptionsTable) Run

func (ot OptionsTable) Run(t *testing.T)

type OptionsTableRecord

type OptionsTableRecord struct {
	// Name is used to identify the record in the test results. A sub-test is created for each
	// record with this name.
	Name string
	// Skip suppresses the execution of this test record.
	Skip bool
	// Focus executes this record skipping all unfocused records. The containing test will fail to
	// prevent accidental check-in.
	Focus bool

	// Options to validate
	Options cli.Validatable

	// ExpectFieldErrors are the errors that should be returned from the validator.
	ExpectFieldErrors cli.FieldErrors

	// ShouldValidate is true if the options are valid
	ShouldValidate bool
}

func (OptionsTableRecord) Run

func (otr OptionsTableRecord) Run(t *testing.T)

type ReactionFunc

type ReactionFunc = clientgotesting.ReactionFunc

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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