testing

package
v0.13.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const TestField = "test-field"

Variables

View Source
var InduceFailure = rtesting.InduceFailure
View Source
var NewFakeClient = rtesting.NewFakeClient

Functions

func DefaultHeader added in v0.9.0

func DefaultHeader() http.Header

func InteractInputLine added in v0.10.0

func InteractInputLine(format string, args ...any) string

InteractInputLine generate a string based on the format and args with a EnterKey (\r) suffix

func NewFakeCliClient

func NewFakeCliClient(c crclient.Client) cli.Client

func NewFakeCliClientWithTransport added in v0.12.0

func NewFakeCliClientWithTransport(c crclient.Client, transport http.RoundTripper) cli.Client

func NewFakeTransportFromResponse added in v0.12.0

func NewFakeTransportFromResponse(resp *http.Response) http.RoundTripper

func PodV1TableObjBody added in v0.9.0

func PodV1TableObjBody(codec runtime.Codec, pods []crclient.Object) io.ReadCloser

build a readercloser response from a pod list

func TableMetaObject added in v0.9.0

func TableMetaObject(objects []crclient.Object) *metav1.Table

build a meta table response from list of client objects

func ToInteractOutput added in v0.10.0

func ToInteractOutput(format string, args ...any) string

ToInteractOutput replaces \n to \r\n for interact library use

func ToInteractTerminal added in v0.10.0

func ToInteractTerminal(format string, args ...any) string

ToInteractTerminal writes the prompt with \r\n between each rune

Types

type Action

type Action = rtesting.Action

type CommandTestCase

type CommandTestCase 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
	// Metadata contains arbitrary value that are stored with the test case
	Metadata map[string]interface{}

	// 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 client for comparison with the expected operations.
	Config *cli.Config
	// Transport to be used as result of HttpReestClient from the kubeconfig file
	// If not specified, when creating the rest client from kubeconfig, the transport will be nil by default
	KubeConfigTransport http.RoundTripper
	// BuilderObjects represents resources needed to build the fake builder. These
	// resources are passed in the http response to the fake builder.
	BuilderObjects []client.Object
	// GivenObjects represents resources that would already exist within Kubernetes. These
	// resources are passed directly to the fake client.
	GivenObjects []client.Object
	// WithReactors installs each ReactionFunc into each fake client. ReactionFuncs intercept
	// each call to the client 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.
	Stdin []byte

	// ExpectCreates asserts each resource with the resources passed to the Create method of the
	// fake client in order.
	ExpectCreates []client.Object
	// ExpectUpdates asserts each resource with the resources passed to the Update method of the
	// fake client in order.
	ExpectUpdates []client.Object
	// ExpectDeletes assert references to the Delete method of the fake client 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 []rtesting.DeleteRef
	// ExpectDeleteCollections asserts references to the DeleteCollection method of the fake
	// client in order. DeleteCollections behaves similarly to Deletes. Unlike Delete,
	// DeleteCollection does not contain a resource Name, but may contain a LabelSelector.
	ExpectDeleteCollections []rtesting.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
	// ShouldPanic is true if and only if command is expected to panic. A panic should only be
	// used to indicate the cli is misconfigured.
	ShouldPanic 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, changing the working
	// directory or setting mock expectations.
	Prepare func(t *testing.T, ctx context.Context, config *cli.Config, tc *CommandTestCase) (context.Context, error)
	// CleanUp is called after the table record is finished and all defined assertions complete.
	// It is intended 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, tc *CommandTestCase) error
	// WithConsoleInteractions receives function with an expect.Console that can be used to send characters and verify the output send to a fake console.
	WithConsoleInteractions func(t *testing.T, console *expect.Console)
}

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

func (CommandTestCase) Run

func (tc CommandTestCase) Run(t *testing.T, scheme *k8sruntime.Scheme, cmdFactory func(context.Context, *cli.Config) *cobra.Command)

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

type CommandTestSuite

type CommandTestSuite []CommandTestCase

CommandTestSuite provides a declarative model for testing interactions with Kubernetes resources via Cobra commands.

A fake controller-runtime client is used to stub calls to the Kubernetes API server. GivenObjects populate a local cache for the client 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 client. 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 client 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 (CommandTestSuite) Run

func (ts CommandTestSuite) Run(t *testing.T, scheme *k8sruntime.Scheme, 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 FakeCachedDiscoveryClient added in v0.9.0

type FakeCachedDiscoveryClient struct {
	discovery.DiscoveryInterface
	Groups             []*metav1.APIGroup
	Resources          []*metav1.APIResourceList
	PreferredResources []*metav1.APIResourceList
	Invalidations      int
}

func NewFakeCachedDiscoveryClient added in v0.9.0

func NewFakeCachedDiscoveryClient() *FakeCachedDiscoveryClient

func (*FakeCachedDiscoveryClient) ServerGroupsAndResources added in v0.9.0

func (d *FakeCachedDiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)

type GetAction

type GetAction = rtesting.GetAction

type InduceFailureOpts

type InduceFailureOpts = rtesting.InduceFailureOpts

type ReactionFunc

type ReactionFunc = rtesting.ReactionFunc

type ValidatableTestCase

type ValidatableTestCase 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

	// Validatable to validate
	Validatable validation.Validatable

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

	// ShouldValidate is true if the validatable object is valid
	ShouldValidate bool

	// 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, changing the working
	// directory or setting mock expectations.
	Prepare func(*testing.T, context.Context) (context.Context, error)
	// CleanUp is called after the table record is finished and all defined assertions complete.
	// It is intended to clean up any state created in the Prepare step or during the test
	// execution, or to make assertions for mocks.
	CleanUp func(*testing.T, context.Context) error
}

func (ValidatableTestCase) Run

func (tc ValidatableTestCase) Run(t *testing.T)

type ValidatableTestSuite

type ValidatableTestSuite []ValidatableTestCase

func (ValidatableTestSuite) Run

func (ts ValidatableTestSuite) Run(t *testing.T)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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