Documentation ¶
Index ¶
- Constants
- Variables
- func DefaultHeader() http.Header
- func InteractInputLine(format string, args ...any) string
- func NewFakeCliClient(c crclient.Client) cli.Client
- func NewFakeCliClientWithTransport(c crclient.Client, transport http.RoundTripper) cli.Client
- func NewFakeTransportFromResponse(resp *http.Response) http.RoundTripper
- func PodV1TableObjBody(codec runtime.Codec, pods []crclient.Object) io.ReadCloser
- func TableMetaObject(objects []crclient.Object) *metav1.Table
- func ToInteractOutput(format string, args ...any) string
- func ToInteractTerminal(format string, args ...any) string
- type Action
- type CommandTestCase
- type CommandTestSuite
- type FakeCachedDiscoveryClient
- type GetAction
- type InduceFailureOpts
- type ReactionFunc
- type ValidatableTestCase
- type ValidatableTestSuite
Constants ¶
const TestField = "test-field"
Variables ¶
var InduceFailure = rtesting.InduceFailure
var NewFakeClient = rtesting.NewFakeClient
Functions ¶
func DefaultHeader ¶ added in v0.9.0
func InteractInputLine ¶ added in v0.10.0
InteractInputLine generate a string based on the format and args with a EnterKey (\r) suffix
func NewFakeCliClientWithTransport ¶ added in v0.12.0
func NewFakeTransportFromResponse ¶ added in v0.12.0
func NewFakeTransportFromResponse(resp *http.Response) http.RoundTripper
func PodV1TableObjBody ¶ added in v0.9.0
build a readercloser response from a pod list
func TableMetaObject ¶ added in v0.9.0
build a meta table response from list of client objects
func ToInteractOutput ¶ added in v0.10.0
ToInteractOutput replaces \n to \r\n for interact library use
func ToInteractTerminal ¶ added in v0.10.0
ToInteractTerminal writes the prompt with \r\n between each rune
Types ¶
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.
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 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)