Documentation
¶
Overview ¶
Package testing provides support for testing reconcilers. It was inspired by knative.dev/pkg/reconciler/testing.
Index ¶
- Variables
- func ColorizeDiff(diff string) string
- func CreateTrackRequest(trackedObjGroup, trackedObjKind, trackedObjNamespace, trackedObjName string) trackBy
- func NewFakeClientWrapper(client client.Client, tracker clientgotesting.ObjectTracker) *clientWrapper
- func ObjectManagerReconcilerTestHarnessActualStasher[T client.Object]() reconcilers.Stasher[T]
- func ObjectManagerReconcilerTestHarnessDesiredStasher[T client.Object]() reconcilers.Stasher[T]
- func ObjectManagerReconcilerTestHarnessResultStasher[T client.Object]() reconcilers.Stasher[T]
- type Action
- type AdmissionWebhookFactory
- type AdmissionWebhookFactoryWithContext
- type AdmissionWebhookTestCase
- type AdmissionWebhookTestSuite
- type AdmissionWebhookTests
- type CreateAction
- type DeleteAction
- type DeleteCollectionAction
- type DeleteCollectionRef
- type DeleteRef
- type Differ
- type Event
- type ExpectConfig
- func (c *ExpectConfig) AssertClientCreateExpectations(t *testing.T)
- func (c *ExpectConfig) AssertClientDeleteCollectionExpectations(t *testing.T)
- func (c *ExpectConfig) AssertClientDeleteExpectations(t *testing.T)
- func (c *ExpectConfig) AssertClientExpectations(t *testing.T)
- func (c *ExpectConfig) AssertClientPatchExpectations(t *testing.T)
- func (c *ExpectConfig) AssertClientStatusPatchExpectations(t *testing.T)
- func (c *ExpectConfig) AssertClientStatusUpdateExpectations(t *testing.T)
- func (c *ExpectConfig) AssertClientUpdateExpectations(t *testing.T)
- func (c *ExpectConfig) AssertExpectations(t *testing.T)
- func (c *ExpectConfig) AssertRecorderExpectations(t *testing.T)
- func (c *ExpectConfig) AssertTrackerExpectations(t *testing.T)
- func (c *ExpectConfig) Config() reconcilers.Config
- type GetAction
- type InduceFailureOpts
- type ListAction
- type ObjectManagerReconcilerTestHarness
- type PatchAction
- type PatchRef
- type ReactionFunc
- type Reactor
- type ReconcilerFactory
- type ReconcilerTestCase
- type ReconcilerTestSuite
- type ReconcilerTests
- type StubObjectManager
- type SubReconcilerFactory
- type SubReconcilerTestCase
- type SubReconcilerTestSuite
- type SubReconcilerTests
- type TestClient
- type TrackRequest
- type UpdateAction
- type VerifyFunc
- type VerifyStashedValueFunc
Constants ¶
This section is empty.
Variables ¶
var ( DiffAddedColor = color.New(color.FgGreen) DiffRemovedColor = color.New(color.FgRed) )
var ( IgnoreLastTransitionTime = cmp.FilterPath(func(p cmp.Path) bool { str := p.String() gostr := p.GoString() return strings.HasSuffix(str, "LastTransitionTime") || strings.HasSuffix(gostr, `["lastTransitionTime"]`) }, cmp.Ignore()) IgnoreTypeMeta = cmp.FilterPath(func(p cmp.Path) bool { str := p.String() return strings.HasSuffix(str, "TypeMeta.APIVersion") || strings.HasSuffix(str, "TypeMeta.Kind") }, cmp.Ignore()) IgnoreCreationTimestamp = cmp.FilterPath(func(p cmp.Path) bool { str := p.String() gostr := p.GoString() return strings.HasSuffix(str, "ObjectMeta.CreationTimestamp") || strings.HasSuffix(gostr, `(*unstructured.Unstructured).Object["metadata"].(map[string]any)["creationTimestamp"]`) || strings.HasSuffix(gostr, `{*unstructured.Unstructured}.Object["metadata"].(map[string]any)["creationTimestamp"]`) || strings.HasSuffix(gostr, `(*unstructured.Unstructured).Object["metadata"].(map[string]interface {})["creationTimestamp"]`) || strings.HasSuffix(gostr, `{*unstructured.Unstructured}.Object["metadata"].(map[string]interface {})["creationTimestamp"]`) }, cmp.Ignore()) IgnoreResourceVersion = cmp.FilterPath(func(p cmp.Path) bool { str := p.String() gostr := p.GoString() return strings.HasSuffix(str, "ObjectMeta.ResourceVersion") || strings.HasSuffix(gostr, `(*unstructured.Unstructured).Object["metadata"].(map[string]any)["resourceVersion"]`) || strings.HasSuffix(gostr, `{*unstructured.Unstructured}.Object["metadata"].(map[string]any)["resourceVersion"]`) || strings.HasSuffix(gostr, `(*unstructured.Unstructured).Object["metadata"].(map[string]interface {})["resourceVersion"]`) || strings.HasSuffix(gostr, `{*unstructured.Unstructured}.Object["metadata"].(map[string]interface {})["resourceVersion"]`) }, cmp.Ignore()) NormalizeLabelSelector = cmp.Transformer("labels.Selector", func(s labels.Selector) *string { if s == nil || s.Empty() { return nil } return ptr.To[string](s.String()) }) NormalizeFieldSelector = cmp.Transformer("fields.Selector", func(s fields.Selector) *string { if s == nil || s.Empty() { return nil } return ptr.To[string](s.String()) }) )
Functions ¶
func ColorizeDiff ¶
func CreateTrackRequest ¶
func CreateTrackRequest(trackedObjGroup, trackedObjKind, trackedObjNamespace, trackedObjName string) trackBy
func NewFakeClientWrapper ¶
func NewFakeClientWrapper(client client.Client, tracker clientgotesting.ObjectTracker) *clientWrapper
func ObjectManagerReconcilerTestHarnessActualStasher ¶ added in v0.23.0
func ObjectManagerReconcilerTestHarnessActualStasher[T client.Object]() reconcilers.Stasher[T]
func ObjectManagerReconcilerTestHarnessDesiredStasher ¶ added in v0.23.0
func ObjectManagerReconcilerTestHarnessDesiredStasher[T client.Object]() reconcilers.Stasher[T]
func ObjectManagerReconcilerTestHarnessResultStasher ¶ added in v0.23.0
func ObjectManagerReconcilerTestHarnessResultStasher[T client.Object]() reconcilers.Stasher[T]
Types ¶
type Action ¶
type Action = clientgotesting.Action
type AdmissionWebhookFactory ¶
type AdmissionWebhookFactory func(t *testing.T, wtc *AdmissionWebhookTestCase, c reconcilers.Config) *admission.Webhook
type AdmissionWebhookFactoryWithContext ¶ added in v0.23.0
type AdmissionWebhookFactoryWithContext func(t *testing.T, ctx context.Context, wtc *AdmissionWebhookTestCase, c reconcilers.Config) (*admission.Webhook, error)
type AdmissionWebhookTestCase ¶
type AdmissionWebhookTestCase struct { // Name is a descriptive name for this test suitable as a first argument to t.Run() Name string // Focus is true if and only if only this and any other focused tests are to be executed. // If one or more tests are focused, the overall test suite will fail. Focus bool // Skip is true if and only if this test should be skipped. Skip bool // Metadata contains arbitrary values that are stored with the test case Metadata map[string]interface{} // Request is the admission request passed to the handler Request *admission.Request // HTTPRequest is the http request used to create the admission request object. If not defined, a minimal request is provided. HTTPRequest *http.Request // WithClientBuilder allows a test to modify the fake client initialization. WithClientBuilder func(*fake.ClientBuilder) *fake.ClientBuilder // 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 // StatusSubResourceTypes is a set of object types that support the status sub-resource. For // these types, the only way to modify the resource's status is update or patch the status // sub-resource. Patching or updating the main resource will not mutated the status field. // Built-in Kubernetes types (e.g. Pod, Deployment, etc) are already accounted for and do not // need to be listed. // // Interacting with a status sub-resource for a type not enumerated as having a status // sub-resource will return a not found error. StatusSubResourceTypes []client.Object // GivenObjects build the kubernetes objects which are present at the onset of reconciliation GivenObjects []client.Object // APIGivenObjects contains objects that are only available via an API reader instead of the normal cache APIGivenObjects []client.Object // GivenTracks provide a set of tracked resources to seed the tracker with GivenTracks []TrackRequest // ExpectTracks holds the ordered list of Track calls expected during reconciliation ExpectTracks []TrackRequest // ExpectEvents holds the ordered list of events recorded during the reconciliation ExpectEvents []Event // ExpectCreates builds the ordered list of objects expected to be created during reconciliation ExpectCreates []client.Object // ExpectUpdates builds the ordered list of objects expected to be updated during reconciliation ExpectUpdates []client.Object // ExpectPatches builds the ordered list of objects expected to be patched during reconciliation ExpectPatches []PatchRef // ExpectDeletes holds the ordered list of objects expected to be deleted during reconciliation ExpectDeletes []DeleteRef // ExpectDeleteCollections holds the ordered list of collections expected to be deleted during reconciliation ExpectDeleteCollections []DeleteCollectionRef // ExpectStatusUpdates builds the ordered list of objects whose status is updated during reconciliation ExpectStatusUpdates []client.Object // ExpectStatusPatches builds the ordered list of objects whose status is patched during reconciliation ExpectStatusPatches []PatchRef // ShouldPanic is true if and only if webhook is expected to panic. A panic should only be // used to indicate the webhook is misconfigured. ShouldPanic bool // ExpectedResponse is compared to the response returned from the webhook ExpectedResponse admission.Response // Prepare is called before the reconciler is executed. It is intended to prepare the broader // environment before the specific test case is executed. For example, setting mock // expectations, or adding values to the context. Prepare func(t *testing.T, ctx context.Context, tc *AdmissionWebhookTestCase) (context.Context, error) // CleanUp is called after the test case 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, tc *AdmissionWebhookTestCase) error // Now is the time the test should run as, defaults to the current time. This value can be used // by reconcilers via the reconcilers.RetireveNow(ctx) method. Now time.Time // Differ methods to use to compare expected and actual values. An empty string is returned for equivalent items. Differ Differ }
AdmissionWebhookTestCase holds a single testcase of an admission webhook.
func (*AdmissionWebhookTestCase) Run ¶
func (tc *AdmissionWebhookTestCase) Run(t *testing.T, scheme *runtime.Scheme, factory AdmissionWebhookFactory)
Deprecated use RunWithContext instead
func (*AdmissionWebhookTestCase) RunWithContext ¶ added in v0.23.0
func (tc *AdmissionWebhookTestCase) RunWithContext(t *testing.T, scheme *runtime.Scheme, factory AdmissionWebhookFactoryWithContext)
Run executes the test case.
type AdmissionWebhookTestSuite ¶
type AdmissionWebhookTestSuite []AdmissionWebhookTestCase
AdmissionWebhookTestSuite represents a list of webhook test cases. The test cases are executed in order.
func (AdmissionWebhookTestSuite) Run ¶
func (ts AdmissionWebhookTestSuite) Run(t *testing.T, scheme *runtime.Scheme, factory AdmissionWebhookFactory)
Deprecated use RunWithContext instead
func (AdmissionWebhookTestSuite) RunWithContext ¶ added in v0.23.0
func (ts AdmissionWebhookTestSuite) RunWithContext(t *testing.T, scheme *runtime.Scheme, factory AdmissionWebhookFactoryWithContext)
Run executes the webhook test suite.
type AdmissionWebhookTests ¶
type AdmissionWebhookTests map[string]AdmissionWebhookTestCase
AdmissionWebhookTests represents a map of reconciler test cases. The map key is the name of each test case. Test cases are executed in random order.
func (AdmissionWebhookTests) Run ¶
func (wt AdmissionWebhookTests) Run(t *testing.T, scheme *runtime.Scheme, factory AdmissionWebhookFactory)
Deprecated use RunWithContext instead
func (AdmissionWebhookTests) RunWithContext ¶ added in v0.23.0
func (wt AdmissionWebhookTests) RunWithContext(t *testing.T, scheme *runtime.Scheme, factory AdmissionWebhookFactoryWithContext)
Run executes the test cases.
type CreateAction ¶
type CreateAction = clientgotesting.CreateAction
type DeleteAction ¶
type DeleteAction = clientgotesting.DeleteAction
type DeleteCollectionAction ¶
type DeleteCollectionAction = clientgotesting.DeleteCollectionAction
type DeleteCollectionRef ¶
type DeleteCollectionRef struct { Group string Kind string Namespace string Labels labels.Selector Fields fields.Selector }
func NewDeleteCollectionRef ¶
func NewDeleteCollectionRef(action DeleteCollectionAction) DeleteCollectionRef
type DeleteRef ¶
func NewDeleteRef ¶
func NewDeleteRef(action DeleteAction) DeleteRef
type Differ ¶ added in v0.23.0
type Differ interface { Result(expected, actual reconcilers.Result) string TrackRequest(expected, actual TrackRequest) string Event(expected, actual Event) string PatchRef(expected, actual PatchRef) string DeleteRef(expected, actual DeleteRef) string DeleteCollectionRef(expected, actual DeleteCollectionRef) string StashedValue(expected, actual any, key reconcilers.StashKey) string Resource(expected, actual client.Object) string ResourceStatusUpdate(expected, actual client.Object) string ResourceUpdate(expected, actual client.Object) string ResourceCreate(expected, actual client.Object) string WebhookResponse(expected, actual admission.Response) string }
var DefaultDiffer Differ = &differ{}
DefaultDiffer is a basic implementation of the Differ interface that is used by default unless overridden for a specific test case or globally.
type ExpectConfig ¶
type ExpectConfig struct { // Name is used when reporting assertion failures to distinguish configs Name string // Scheme allows the client to map Go structs to Kubernetes GVKs. All structured resources // that are expected to interact with this config should be registered within the scheme. Scheme *runtime.Scheme // StatusSubResourceTypes is a set of object types that support the status sub-resource. For // these types, the only way to modify the resource's status is update or patch the status // sub-resource. Patching or updating the main resource will not mutated the status field. // Built-in Kubernetes types (e.g. Pod, Deployment, etc) are already accounted for and do not // need to be listed. // // Interacting with a status sub-resource for a type not enumerated as having a status // sub-resource will return a not found error. StatusSubResourceTypes []client.Object // Differ methods to use to compare expected and actual values Differ Differ // GivenObjects build the kubernetes objects which are present at the onset of reconciliation GivenObjects []client.Object // APIGivenObjects contains objects that are only available via an API reader instead of the normal cache APIGivenObjects []client.Object // WithClientBuilder allows a test to modify the fake client initialization. WithClientBuilder func(*fake.ClientBuilder) *fake.ClientBuilder // 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 // GivenTracks provide a set of tracked resources to seed the tracker with GivenTracks []TrackRequest // ExpectTracks holds the ordered list of Track calls expected during reconciliation ExpectTracks []TrackRequest // ExpectEvents holds the ordered list of events recorded during the reconciliation ExpectEvents []Event // ExpectCreates builds the ordered list of objects expected to be created during reconciliation ExpectCreates []client.Object // ExpectUpdates builds the ordered list of objects expected to be updated during reconciliation ExpectUpdates []client.Object // ExpectPatches builds the ordered list of objects expected to be patched during reconciliation ExpectPatches []PatchRef // ExpectDeletes holds the ordered list of objects expected to be deleted during reconciliation ExpectDeletes []DeleteRef // ExpectDeleteCollections holds the ordered list of collections expected to be deleted during reconciliation ExpectDeleteCollections []DeleteCollectionRef // ExpectStatusUpdates builds the ordered list of objects whose status is updated during reconciliation ExpectStatusUpdates []client.Object // ExpectStatusPatches builds the ordered list of objects whose status is patched during reconciliation ExpectStatusPatches []PatchRef // contains filtered or unexported fields }
ExpectConfig encompasses the creation of a config object using given state, captures observed behavior of the reconciler and asserts expected behavior against the observed behavior.
This object is driven implicitly by ReconcilerTestCase and SubReconcilerTestCase. A reconciler that needs to interact with multiple configs can create and manage additional ExpectConfigs with their own expectations. For example, when a WithConfig reconciler is used the SubReconcilers under it use a config separate from the config originally used to load the reconciled resource.
func (*ExpectConfig) AssertClientCreateExpectations ¶
func (c *ExpectConfig) AssertClientCreateExpectations(t *testing.T)
AssertClientCreateExpectations asserts observed reconciler client create behavior matches the expected client create behavior
func (*ExpectConfig) AssertClientDeleteCollectionExpectations ¶
func (c *ExpectConfig) AssertClientDeleteCollectionExpectations(t *testing.T)
AssertClientDeleteCollectionExpectations asserts observed reconciler client delete collection behavior matches the expected client delete collection behavior
func (*ExpectConfig) AssertClientDeleteExpectations ¶
func (c *ExpectConfig) AssertClientDeleteExpectations(t *testing.T)
AssertClientDeleteExpectations asserts observed reconciler client delete behavior matches the expected client delete behavior
func (*ExpectConfig) AssertClientExpectations ¶
func (c *ExpectConfig) AssertClientExpectations(t *testing.T)
AssertClientExpectations asserts observed reconciler client behavior matches the expected client behavior
func (*ExpectConfig) AssertClientPatchExpectations ¶
func (c *ExpectConfig) AssertClientPatchExpectations(t *testing.T)
AssertClientPatchExpectations asserts observed reconciler client patch behavior matches the expected client patch behavior
func (*ExpectConfig) AssertClientStatusPatchExpectations ¶
func (c *ExpectConfig) AssertClientStatusPatchExpectations(t *testing.T)
AssertClientStatusPatchExpectations asserts observed reconciler client status patch behavior matches the expected client status patch behavior
func (*ExpectConfig) AssertClientStatusUpdateExpectations ¶
func (c *ExpectConfig) AssertClientStatusUpdateExpectations(t *testing.T)
AssertClientStatusUpdateExpectations asserts observed reconciler client status update behavior matches the expected client status update behavior
func (*ExpectConfig) AssertClientUpdateExpectations ¶
func (c *ExpectConfig) AssertClientUpdateExpectations(t *testing.T)
AssertClientUpdateExpectations asserts observed reconciler client update behavior matches the expected client update behavior
func (*ExpectConfig) AssertExpectations ¶
func (c *ExpectConfig) AssertExpectations(t *testing.T)
AssertExpectations asserts all observed reconciler behavior matches the expected behavior
func (*ExpectConfig) AssertRecorderExpectations ¶
func (c *ExpectConfig) AssertRecorderExpectations(t *testing.T)
AssertRecorderExpectations asserts observed event recorder behavior matches the expected event recorder behavior
func (*ExpectConfig) AssertTrackerExpectations ¶
func (c *ExpectConfig) AssertTrackerExpectations(t *testing.T)
AssertTrackerExpectations asserts observed tracker behavior matches the expected tracker behavior
func (*ExpectConfig) Config ¶
func (c *ExpectConfig) Config() reconcilers.Config
Config returns the Config object. This method should only be called once. Subsequent calls are ignored returning the Config from the first call.
type GetAction ¶
type GetAction = clientgotesting.GetAction
type InduceFailureOpts ¶
type ListAction ¶
type ListAction = clientgotesting.ListAction
type ObjectManagerReconcilerTestHarness ¶ added in v0.23.0
type ObjectManagerReconcilerTestHarness[T client.Object] struct { ObjectManager reconcilers.ObjectManager[T] }
ObjectManagerReconcilerTestHarness orchestrates an ObjectManager as a SubReconciler so that it can be easily tested within a SubReconcilerTestCase.
The actual and desired objects must be defined in the stash via the ObjectManagerReconcilerTestHarnessActualStasher and ObjectManagerReconcilerTestHarnessDesiredStasher stashers. Failure to stash these values will panic the reconciler. The resulting object is stashed with ObjectManagerReconcilerTestHarnessResultStasher.
The actual object, when defined, is automatically added as a given object.
func (*ObjectManagerReconcilerTestHarness[T]) Reconcile ¶ added in v0.23.0
func (h *ObjectManagerReconcilerTestHarness[T]) Reconcile(ctx context.Context, resource client.Object) (reconcilers.Result, error)
func (*ObjectManagerReconcilerTestHarness[T]) SetupWithManager ¶ added in v0.23.0
type PatchAction ¶
type PatchAction = clientgotesting.PatchAction
type PatchRef ¶
type PatchRef struct { Group string Kind string Namespace string Name string SubResource string PatchType types.PatchType Patch []byte }
func NewPatchRef ¶
func NewPatchRef(action PatchAction) PatchRef
type ReactionFunc ¶
type ReactionFunc = clientgotesting.ReactionFunc
func CalledAtMostTimes ¶
func CalledAtMostTimes(verb, kind string, maxCalls int) ReactionFunc
CalledAtMostTimes error if the client is called more than the max number of times for a verb and kind
func InduceFailure ¶
func InduceFailure(verb, kind string, o ...InduceFailureOpts) ReactionFunc
InduceFailure is used in conjunction with reconciler test's WithReactors field. Tests that want to induce a failure in a testcase of a reconciler test would add:
WithReactors: []rtesting.ReactionFunc{ // Makes calls to create stream return an error. rtesting.InduceFailure("create", "Stream"), },
type Reactor ¶
type Reactor = clientgotesting.Reactor
type ReconcilerFactory ¶
type ReconcilerFactory func(t *testing.T, rtc *ReconcilerTestCase, c reconcilers.Config) reconcile.Reconciler
ReconcilerFactory returns a Reconciler.Interface to perform reconciliation of a test case, ActionRecorderList/EventList to capture k8s actions/events produced during reconciliation and FakeStatsReporter to capture stats.
type ReconcilerTestCase ¶
type ReconcilerTestCase struct { // Name is a descriptive name for this test suitable as a first argument to t.Run() Name string // Focus is true if and only if only this and any other focused tests are to be executed. // If one or more tests are focused, the overall test suite will fail. Focus bool // Skip is true if and only if this test should be skipped. Skip bool // Metadata contains arbitrary values that are stored with the test case Metadata map[string]interface{} // Request identifies the object to be reconciled Request reconcilers.Request // 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 // WithClientBuilder allows a test to modify the fake client initialization. WithClientBuilder func(*fake.ClientBuilder) *fake.ClientBuilder // StatusSubResourceTypes is a set of object types that support the status sub-resource. For // these types, the only way to modify the resource's status is update or patch the status // sub-resource. Patching or updating the main resource will not mutated the status field. // Built-in Kubernetes types (e.g. Pod, Deployment, etc) are already accounted for and do not // need to be listed. // // Interacting with a status sub-resource for a type not enumerated as having a status // sub-resource will return a not found error. StatusSubResourceTypes []client.Object // GivenObjects build the kubernetes objects which are present at the onset of reconciliation GivenObjects []client.Object // APIGivenObjects contains objects that are only available via an API reader instead of the normal cache APIGivenObjects []client.Object // GivenTracks provide a set of tracked resources to seed the tracker with GivenTracks []TrackRequest // ExpectTracks holds the ordered list of Track calls expected during reconciliation ExpectTracks []TrackRequest // ExpectEvents holds the ordered list of events recorded during the reconciliation ExpectEvents []Event // ExpectCreates builds the ordered list of objects expected to be created during reconciliation ExpectCreates []client.Object // ExpectUpdates builds the ordered list of objects expected to be updated during reconciliation ExpectUpdates []client.Object // ExpectPatches builds the ordered list of objects expected to be patched during reconciliation ExpectPatches []PatchRef // ExpectDeletes holds the ordered list of objects expected to be deleted during reconciliation ExpectDeletes []DeleteRef // ExpectDeleteCollections holds the ordered list of collections expected to be deleted during reconciliation ExpectDeleteCollections []DeleteCollectionRef // ExpectStatusUpdates builds the ordered list of objects whose status is updated during reconciliation ExpectStatusUpdates []client.Object // ExpectStatusPatches builds the ordered list of objects whose status is patched during reconciliation ExpectStatusPatches []PatchRef // AdditionalConfigs holds ExceptConfigs that are available to the test case and will have // their expectations checked again the observed config interactions. The key in this map is // set as the ExpectConfig's name. AdditionalConfigs map[string]ExpectConfig // ShouldErr is true if and only if reconciliation is expected to return an error ShouldErr bool // ExpectedResult is compared to the result returned from the reconciler if there was no error ExpectedResult reconcilers.Result // Verify provides the reconciliation Result and error for custom assertions Verify VerifyFunc // Prepare is called before the reconciler is executed. It is intended to prepare the broader // environment before the specific test case is executed. For example, setting mock // expectations, or adding values to the context. Prepare func(t *testing.T, ctx context.Context, tc *ReconcilerTestCase) (context.Context, error) // CleanUp is called after the test case 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, tc *ReconcilerTestCase) error // Now is the time the test should run as, defaults to the current time. This value can be used // by reconcilers via the reconcilers.RetireveNow(ctx) method. Now time.Time // Differ methods to use to compare expected and actual values. An empty string is returned for equivalent items. Differ Differ }
ReconcilerTestCase holds a single test case of a reconciler test suite.
func (*ReconcilerTestCase) Run ¶
func (tc *ReconcilerTestCase) Run(t *testing.T, scheme *runtime.Scheme, factory ReconcilerFactory)
Run executes the test case.
type ReconcilerTestSuite ¶
type ReconcilerTestSuite []ReconcilerTestCase
ReconcilerTestSuite represents a list of reconciler test cases. The test cases are executed in order.
func (ReconcilerTestSuite) Run ¶
func (ts ReconcilerTestSuite) Run(t *testing.T, scheme *runtime.Scheme, factory ReconcilerFactory)
Run executes the reconciler test suite.
type ReconcilerTests ¶
type ReconcilerTests map[string]ReconcilerTestCase
ReconcilerTests represents a map of reconciler test cases. The map key is the name of each test case. Test cases are executed in random order.
func (ReconcilerTests) Run ¶
func (rt ReconcilerTests) Run(t *testing.T, scheme *runtime.Scheme, factory ReconcilerFactory)
Run executes the test cases.
type StubObjectManager ¶ added in v0.23.0
StubObjectManager is used for testing the orchestration of an ObjectManager's essential behavior without the full robustness of a real ObjectManager implementation.
There are four possible outcomes: - create a desired resource, returning the created object - update an outdated resource, returning the updated object - delete an undesired resource, returning nil - do nothing when the resources are in sync, returning the actual object
If any of the client calls error, the error is returned.
There are no user configurable values. Merging of desired and actual objects is handled reflectively and may be unsafe for some resources.
func (*StubObjectManager[T]) SetupWithManager ¶ added in v0.23.0
type SubReconcilerFactory ¶
type SubReconcilerFactory[Type client.Object] func(t *testing.T, rtc *SubReconcilerTestCase[Type], c reconcilers.Config) reconcilers.SubReconciler[Type]
SubReconcilerFactory returns a Reconciler.Interface to perform reconciliation of a test case, ActionRecorderList/EventList to capture k8s actions/events produced during reconciliation and FakeStatsReporter to capture stats.
type SubReconcilerTestCase ¶
type SubReconcilerTestCase[Type client.Object] struct { // Name is a descriptive name for this test suitable as a first argument to t.Run() Name string // Focus is true if and only if only this and any other focused tests are to be executed. // If one or more tests are focused, the overall test suite will fail. Focus bool // Skip is true if and only if this test should be skipped. Skip bool // Metadata contains arbitrary values that are stored with the test case Metadata map[string]interface{} // Resource is the initial object passed to the sub reconciler Resource Type // GivenStashedValues adds these items to the stash passed into the reconciler. Factories are resolved to their object. GivenStashedValues map[reconcilers.StashKey]interface{} // WithClientBuilder allows a test to modify the fake client initialization. WithClientBuilder func(*fake.ClientBuilder) *fake.ClientBuilder // 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 // StatusSubResourceTypes is a set of object types that support the status sub-resource. For // these types, the only way to modify the resource's status is update or patch the status // sub-resource. Patching or updating the main resource will not mutated the status field. // Built-in Kubernetes types (e.g. Pod, Deployment, etc) are already accounted for and do not // need to be listed. // // Interacting with a status sub-resource for a type not enumerated as having a status // sub-resource will return a not found error. StatusSubResourceTypes []client.Object // GivenObjects build the kubernetes objects which are present at the onset of reconciliation GivenObjects []client.Object // APIGivenObjects contains objects that are only available via an API reader instead of the normal cache APIGivenObjects []client.Object // GivenTracks provide a set of tracked resources to seed the tracker with GivenTracks []TrackRequest // ExpectResource is the expected reconciled resource as mutated after the sub reconciler, or nil if no modification ExpectResource Type // ExpectStashedValues ensures each value is stashed. Values in the stash that are not expected are ignored. Factories are resolved to their object. ExpectStashedValues map[reconcilers.StashKey]interface{} // VerifyStashedValue is an optional, custom verification function for stashed values VerifyStashedValue VerifyStashedValueFunc // ExpectTracks holds the ordered list of Track calls expected during reconciliation ExpectTracks []TrackRequest // ExpectEvents holds the ordered list of events recorded during the reconciliation ExpectEvents []Event // ExpectCreates builds the ordered list of objects expected to be created during reconciliation ExpectCreates []client.Object // ExpectUpdates builds the ordered list of objects expected to be updated during reconciliation ExpectUpdates []client.Object // ExpectPatches builds the ordered list of objects expected to be patched during reconciliation ExpectPatches []PatchRef // ExpectDeletes holds the ordered list of objects expected to be deleted during reconciliation ExpectDeletes []DeleteRef // ExpectDeleteCollections holds the ordered list of collections expected to be deleted during reconciliation ExpectDeleteCollections []DeleteCollectionRef // AdditionalConfigs holds configs that are available to the test case and will have their // expectations checked again the observed config interactions. The key in this map is set as // the ExpectConfig's name. AdditionalConfigs map[string]ExpectConfig // ShouldErr is true if and only if reconciliation is expected to return an error ShouldErr bool // ShouldPanic is true if and only if reconciliation is expected to panic. A panic should only be // used to indicate the reconciler is misconfigured. ShouldPanic bool // ExpectedResult is compared to the result returned from the reconciler if there was no error ExpectedResult reconcilers.Result // Verify provides the reconciliation Result and error for custom assertions Verify VerifyFunc // Prepare is called before the reconciler is executed. It is intended to prepare the broader // environment before the specific test case is executed. For example, setting mock // expectations, or adding values to the context, Prepare func(t *testing.T, ctx context.Context, tc *SubReconcilerTestCase[Type]) (context.Context, error) // CleanUp is called after the test case 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, tc *SubReconcilerTestCase[Type]) error // Now is the time the test should run as, defaults to the current time. This value can be used // by reconcilers via the reconcilers.RetireveNow(ctx) method. Now time.Time // Differ methods to use to compare expected and actual values. An empty string is returned for equivalent items. Differ Differ }
SubReconcilerTestCase holds a single testcase of a sub reconciler test.
func (*SubReconcilerTestCase[T]) Run ¶
func (tc *SubReconcilerTestCase[T]) Run(t *testing.T, scheme *runtime.Scheme, factory SubReconcilerFactory[T])
Run executes the test case.
type SubReconcilerTestSuite ¶
type SubReconcilerTestSuite[Type client.Object] []SubReconcilerTestCase[Type]
SubReconcilerTestSuite represents a list of subreconciler test cases. The test cases are executed in order.
func (SubReconcilerTestSuite[T]) Run ¶
func (ts SubReconcilerTestSuite[T]) Run(t *testing.T, scheme *runtime.Scheme, factory SubReconcilerFactory[T])
Run executes the subreconciler test suite.
type SubReconcilerTests ¶
type SubReconcilerTests[Type client.Object] map[string]SubReconcilerTestCase[Type]
SubReconcilerTests represents a map of reconciler test cases. The map key is the name of each test case. Test cases are executed in random order.
func (SubReconcilerTests[T]) Run ¶
func (rt SubReconcilerTests[T]) Run(t *testing.T, scheme *runtime.Scheme, factory SubReconcilerFactory[T])
Run executes the test cases.
type TestClient ¶ added in v0.23.0
type TestClient interface { client.Client AddGiven(objs ...client.Object) AddReactor(verb, kind string, reaction ReactionFunc) PrependReactor(verb, kind string, reaction ReactionFunc) }
type TrackRequest ¶
type TrackRequest struct { // Tracker is the object doing the tracking Tracker types.NamespacedName // Deprecated use TrackedReference // Tracked is the object being tracked Tracked tracker.Key // TrackedReference is a ref to the object being tracked TrackedReference tracker.Reference }
TrackRequest records that one object is tracking another object.
func NewTrackRequest ¶
func NewTrackRequest(t, b client.Object, scheme *runtime.Scheme) TrackRequest
type UpdateAction ¶
type UpdateAction = clientgotesting.UpdateAction
type VerifyFunc ¶
type VerifyFunc func(t *testing.T, result reconcilers.Result, err error)
VerifyFunc is a verification function for a reconciler's result
type VerifyStashedValueFunc ¶
type VerifyStashedValueFunc func(t *testing.T, key reconcilers.StashKey, expected, actual interface{})
VerifyStashedValueFunc is a verification function for the entries in the stash