package
1.33.0-alpha.2
Repository: https://github.com/kubernetes/kubernetes.git
Documentation: pkg.go.dev

# README

Overview

The Kubernetes E2E framework simplifies writing Ginkgo tests suites. It's main usage is for these tests suites in the Kubernetes repository itself:

  • test/e2e: runs as client for a Kubernetes cluster. The e2e.test binary is used for conformance testing.
  • test/e2e_node: runs on the same node as a kubelet instance. Used for testing kubelet.
  • test/e2e_kubeadm: test suite for kubeadm.

Usage of the framework outside of Kubernetes is possible, but not encouraged. Downstream users have to be prepared to deal with API changes.

Code Organization

The core framework is the k8s.io/kubernetes/test/e2e/framework package. It contains functionality that all E2E suites are expected to need:

  • connecting to the apiserver
  • managing per-test namespaces
  • logging (Logf)
  • failure handling (Fail, Failf)
  • writing concise JUnit test results

It also contains a TestContext with settings that can be controlled via command line flags. For historic reasons, this also contains settings for individual tests or packages that are not part of the core framework.

Optional functionality is placed in sub packages like test/e2e/framework/pod. The core framework does not depend on those. Sub packages may depend on the core framework.

The advantages of splitting the code like this are:

  • leaner go doc packages by grouping related functions together
  • not forcing all E2E suites to import all functionality
  • avoiding import cycles

Execution Flow

When a test suite gets invoked, the top-level Describe calls register the callbacks that define individual tests, but does not invoke them yet. After that init phase, command line flags are parsed and the Describe callbacks are invoked. Those then define the actual tests for the test suite. Command line flags can be used to influence the test definitions.

Now Context/BeforeEach/AfterEach/It define code that will be called later when executing a specific test. During this setup phase, f := framework.NewDefaultFramework("some tests") creates a Framework instance for one or more tests. NewDefaultFramework initializes that instance anew for each test with a BeforeEach callback. Starting with Kubernetes 1.26, that instance gets cleaned up after all other code for a test has been invoked, so the following code is correct:

f := framework.NewDefaultFramework("some tests")

ginkgo.AfterEach(func() {
    # Do something with f.ClientSet.
}

ginkgo.It("test something", func(ctx context.Context) {
    # The actual test.
})

Optional functionality can be injected into each test by adding a callback to NewFrameworkExtensions in an init function. NewDefaultFramework will invoke those callbacks as if the corresponding code had been added to each test like this:

f := framework.NewDefaultFramework("some tests")

optional.SomeCallback(f)

SomeCallback then can register additional BeforeEach or AfterEach callbacks that use the test's Framework instance.

When a test runs, callbacks defined for it with BeforeEach and AfterEach are called in first-in-first-out order. Since the migration to ginkgo v2 in Kubernetes 1.25, the AfterEach callback is called also when there has been a test failure. This can be used to run cleanup code for a test reliably. However, ginkgo.DeferCleanup is often a better alternative. Its callbacks are executed in first-in-last-out order.

test/e2e/framework/internal/unittests/cleanup/cleanup.go shows how these different callbacks can be used and in which order they are going to run.

# Packages

Package config simplifies the declaration of configuration options.
Package testfiles provides a wrapper around various optional ways of retrieving additional files needed during a test run: - builtin bindata - filesystem access Because it is a is self-contained package, it can be used by test/e2e/framework and test/e2e/manifest without creating a circular dependency.

# Functions

AfterReadingAllFlags makes changes to the context after all flags have been read and prepares the process for a test run.
AnnotatedLocation can be used to provide more informative source code locations by passing the result as additional parameter to a BeforeEach/AfterEach/DeferCleanup/It/etc.
AnnotatedLocationWithOffset skips additional call stack levels.
APIAddress returns a address of an instance.
AppendContainerCommandGroupIfNeeded returns container command group parameter if necessary.
CheckTestingNSDeletedExcept checks whether all e2e based existing namespaces are in the Terminating state and waits until they are finally deleted.
ConformanceIt is wrapper function for ginkgo It.
Context is a wrapper around [ginkgo.Context] which supports framework With* labels as optional arguments in addition to those already supported by ginkgo itself, like [ginkgo.Label] and [ginkgo.Offset].
CoreDump SSHs to the master and all nodes and dumps their logs into dir.
CreateTestingNS should be used by every test, note that we append a common prefix to the provided test name.
DeleteNamespaces deletes all namespaces that match the given delete and skip filters.
Describe is a wrapper around [ginkgo.Describe] which supports framework With* labels as optional arguments in addition to those already supported by ginkgo itself, like [ginkgo.Label] and [ginkgo.Offset].
EnsureLoadBalancerResourcesDeleted ensures that cloud load balancer resources that were created are actually cleaned up.
ExpectNoError checks if "err" is set, and if so, fails assertion while logging the error.
ExpectNoErrorWithOffset checks if "err" is set, and if so, fails assertion while logging the error at "offset" levels above its caller (for example, for call chain f -> g -> ExpectNoErrorWithOffset(1, ...) error would be logged for "f").
Failf logs the fail info, including a stack trace starts with its direct caller (for example, for call chain f -> g -> Failf("foo", ...) error would be logged for "g").
FormatBugs produces a report that includes all bugs recorded earlier via RecordBug.
GetControlPlaneNodes returns a list of control plane nodes.
GetGroupNodes returns a node name for the specified node group.
GetNodeExternalIPs returns a list of external ip address(es) if any for a node.
GetObject takes a get function like clientset.CoreV1().Pods(ns).Get and the parameters for it and returns a function that executes that get operation in a [gomega.Eventually] or [gomega.Consistently].
GetProviders returns the names of all currently registered providers.
Gomega returns an interface that can be used like gomega to express assertions.
GroupSize returns the size of an instance group.
HandleRetry wraps an arbitrary get function.
IgnoreNotFound can be used to wrap an arbitrary function in a call to [ginkgo.DeferCleanup].
It is a wrapper around [ginkgo.It] which supports framework With* labels as optional arguments in addition to those already supported by ginkgo itself, like [ginkgo.Label] and [ginkgo.Offset].
ListObjects takes a list function like clientset.CoreV1().Pods(ns).List and the parameters for it and returns a function that executes that list operation in a [gomega.Eventually] or [gomega.Consistently].
LoadClientset returns clientset for connecting to kubernetes clusters.
LoadConfig returns a config for a rest client with the UserAgent set to include the current test name.
Logf logs the info.
MakeMatcher builds a gomega.Matcher based on a single callback function.
MasterOSDistroIs returns true if the master OS distro is included in the supportedMasterOsDistros.
NewBug creates a new bug with a location that is obtained by skipping a certain number of stack frames.
NewDefaultFramework makes a new framework and sets up a BeforeEach which initializes the framework instance.
NewFlakeReport returns a new flake report.
NewFramework creates a test framework.
NewFrameworkWithCustomTimeouts makes a framework with custom timeouts.
NewTimeoutContext returns a TimeoutContext with all values set either to hard-coded defaults or a value that was configured when running the E2E suite.
NodeOSArchIs returns true if the node OS arch is included in the supportedNodeOsArchs.
NodeOSDistroIs returns true if the node OS distro is included in the supportedNodeOsDistros.
PollInterval defines how long to wait between API server queries while waiting for some condition.
PrettyPrintJSON converts metrics to JSON format.
ProviderIs returns true if the provider is included is the providers.
RandomSuffix provides a random sequence to append to pods,services,rcs.
RecordBug stores information about a bug in the E2E suite source code that cannot be reported through ginkgo.Fail because it was found outside of some test, for example during test registration.
RegisterClusterFlags registers flags specific to the cluster e2e test suite.
RegisterCommonFlags registers flags common to all e2e test suites.
RegisterProvider is expected to be called during application init, typically by an init function in a provider package.
ResizeGroup resizes an instance group.
RetryNotFound wraps an arbitrary get function.
RunCmd runs cmd using args and returns its stdout and stderr.
RunCmdEnv runs cmd with the provided environment and args and returns its stdout and stderr.
SetupProviderConfig validates the chosen provider and creates an interface instance for it.
ShouldRetry decides whether to retry an API request.
SIGDescribe returns a wrapper function for ginkgo.Describe which injects the SIG name as annotation.
StartCmdAndStreamOutput returns stdout and stderr after starting the given cmd.
TagsEqual can be used to check whether two tags are the same.
TryKill is rough equivalent of ctrl+c for cleaning up processes.
WaitForDefaultServiceAccountInNamespace waits for the default service account to be provisioned the default service account is what is associated with pods when they do not specify a service account as a result, pods are not able to be provisioned in a namespace until the service account is provisioned.
WaitForGroupSize waits for node instance group reached the desired size.
WaitForKubeRootCAInNamespace waits for the configmap kube-root-ca.crt containing the service account CA trust bundle to be provisioned in the specified namespace so that pods do not have to retry mounting the config map (which creates noise that hides other issues in the Kubelet).
WaitForNamespacesDeleted waits for the namespaces to be deleted.
WaitForServiceEndpointsNum waits until there are EndpointSlices for serviceName containing a total of expectNum endpoints.
WatchEventSequenceVerifier ..
WithConformace specifies that a certain test or group of tests must pass in all conformant Kubernetes clusters.
WithDisruptive specifies that a certain test or group of tests temporarily affects the functionality of the Kubernetes cluster.
WithEnvironment specifies that a certain test or group of tests only works in a certain environment.
WithEnvironment specifies that a certain test or group of tests only works with a feature available.
WithFeatureGate specifies that a certain test or group of tests depends on a feature gate being enabled.
WithFlaky specifies that a certain test or group of tests are failing randomly.
WithLabel is a wrapper around [ginkgo.Label].
WithNodeConformance specifies that a certain test or group of tests for node functionality that does not depend on runtime or Kubernetes distro specific behavior.
WithSerial specifies that a certain test or group of tests must not run in parallel with other tests.
WithSlow specifies that a certain test or group of tests must not run in parallel with other tests.

# Constants

ClaimProvisionShortTimeout is same as `ClaimProvisionTimeout` to wait for claim to be dynamically provisioned, but shorter.
ClaimProvisionTimeout is how long claims have to become dynamically provisioned.
ControlPlaneLabel is valid label for kubeadm based clusters like kops ONLY.
DefaultNamespaceDeletionTimeout is timeout duration for waiting for a namespace deletion.
DefaultNumNodes is the number of nodes.
KubeControllerManagerPort is the default port for the controller manager status server.
KubeletPort is the default port for the kubelet server on each host machine.
NodeReadyInitialTimeout is how long nodes have to be "ready" when a test begins.
PodDeleteTimeout is how long to wait for a pod to be deleted.
PodEventTimeout is how much we wait for a pod event to occur.
PodGetTimeout is how long to wait for a pod to be got.
PodListTimeout is how long to wait for the pod to be listable.
PodReadyBeforeTimeout is how long pods have to be "ready" when a test begins.
PodStartShortTimeout is same as `PodStartTimeout` to wait for the pod to be started, but shorter.
PodStartTimeout is how long to wait for the pod to be started.
Poll is how often to Poll pods, nodes and claims.
PollShortTimeout is the short timeout value in polling.
RestartNodeReadyAgainTimeout is how long a node is allowed to become "Ready" after it is restarted before the test is considered failed.
RestartPodReadyAgainTimeout is how long a pod is allowed to become "running" and "ready" after a node restart before test is considered failed.
ServiceAccountProvisionTimeout is how long to wait for a service account to be provisioned.
ServiceStartTimeout is how long to wait for a service endpoint to be resolvable.
SingleCallTimeout is how long to try single API calls (like 'get' or 'list').
SnapshotCreateTimeout is how long for snapshot to create snapshotContent.
SnapshotDeleteTimeout is how long for snapshot to delete snapshotContent.

# Variables

CheckForBugs determines whether the framework bails out when test initialization found any bugs.
ErrFailure is an empty error that can be wrapped to indicate that an error is a FailureError.
Exit is called when the framework detects fatal errors or when it is done with the execution of e.g.
Fail is an alias for ginkgo.Fail.
NewFrameworkExtensions lists functions that get called by NewFramework after constructing a new framework and after calling ginkgo.BeforeEach for the framework.
Output is used for output when not running tests, for example in -list-tests.
Can be stubbed out for testing.
ProvidersWithSSH are those providers where each node is accessible with SSH.
RunID is a unique identifier of the e2e run.
TestContext should be used by all tests to access common context data.
Can be stubbed out for testing.
These variables contain the parameters that [WithFeature] and [WithEnvironment] accept.
These variables contain the parameters that [WithFeature] and [WithEnvironment] accept.

# Structs

CloudConfig holds the cloud configuration for e2e test suites.
ClusterVerification is a struct for a verification of cluster state.
FailureError is an error where the error string is meant to be passed to ginkgo.Fail directly, i.e.
FlakeReport is a struct for managing the flake report.
Framework supports common operations used by e2e tests; it will keep a client & a namespace for you.
KubeCluster is a struct for managing kubernetes cluster info.
KubeConfig is a struct for managing kubernetes config.
KubeUser is a struct for managing kubernetes user info.
NamespacedName comprises a resource name, with a mandatory namespace, rendered as "<namespace>/<name>".
NodeKillerConfig describes configuration of NodeKiller -- a utility to simulate node failures.
NodeTestContextType is part of TestContextType, it is shared by all node e2e test.
NullProvider is the default implementation of the ProviderInterface which doesn't do anything.
Options is a struct for managing test framework options.
PodStateVerification represents a verification of pod state.
TestContextType contains test settings and global state.
TimeoutContext contains timeout settings for several actions.

# Interfaces

NamedObject is a subset of metav1.Object which provides read-only access to name and namespace of an object.
ProviderInterface contains the implementation for certain provider-specific functionality.
TestDataSummary is an interface for managing test data.

# Type aliases

APIGetFunc is a get functions as used in client-go.
APIListFunc is a list functions as used in client-go.
ClientConfigGetter is a func that returns getter to return a config.
CreateTestingNSFn is a func that is responsible for creating namespace used for executing e2e tests.
DumpAllNamespaceInfoAction is called after each failed test for namespaces created for the test.
Environment is the name for the environment in which a test can run, like "Linux" or "Windows".
Factory is a func which operates provider specific behavior.
Feature is the name of a certain feature that the cluster under test must have.
GetFunc is a function which retrieves a certain object.