testutil

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2024 License: Apache-2.0 Imports: 50 Imported by: 0

Documentation

Overview

Package testutil provides utilities for writing functional tests

Index

Constants

This section is empty.

Variables

View Source
var PodMetricsCRD = apiextensionsv1.CustomResourceDefinition{
	ObjectMeta: metav1.ObjectMeta{
		Name: "podmetrics.metrics.k8s.io",
		Annotations: map[string]string{
			"api-approved.kubernetes.io": "unapproved",
		},
	},
	Spec: apiextensionsv1.CustomResourceDefinitionSpec{
		Group: "metrics.k8s.io",
		Versions: []apiextensionsv1.CustomResourceDefinitionVersion{
			{
				Name:    "v1beta1",
				Served:  true,
				Storage: true,
				Schema: &apiextensionsv1.CustomResourceValidation{

					OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
						XPreserveUnknownFields: pointer.Bool(true),
						Type:                   "object",
					},
				},
			},
		},
		Names: apiextensionsv1.CustomResourceDefinitionNames{
			Singular: "podmetrics",
			Plural:   "podmetrics",
			Kind:     "PodMetrics",
		},
		Scope: apiextensionsv1.NamespaceScoped,
	},
}

PodMetricsCRD fakes the PodMetrics API as a CRD so we can manually set the values

View Source
var ResourceQuotaDescriptorCRD = apiextensionsv1.CustomResourceDefinition{
	ObjectMeta: metav1.ObjectMeta{
		Name: "resourcequotadescriptors.quotamanagement.usagemetricscollector.sigs.k8s.io",
		Annotations: map[string]string{
			"api-approved.kubernetes.io": "unapproved",
		},
	},
	Spec: apiextensionsv1.CustomResourceDefinitionSpec{
		Group: "quotamanagement.usagemetricscollector.sigs.k8s.io",
		Versions: []apiextensionsv1.CustomResourceDefinitionVersion{
			{
				Name:    "v1alpha1",
				Served:  true,
				Storage: true,
				Schema: &apiextensionsv1.CustomResourceValidation{

					OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
						XPreserveUnknownFields: pointer.Bool(true),
						Type:                   "object",
						Properties: map[string]apiextensionsv1.JSONSchemaProps{
							"metadata": {
								Type: "object",
							},
						},
					},
				},
			},
		},
		Names: apiextensionsv1.CustomResourceDefinitionNames{
			Singular: "resourcequotadescriptor",
			Plural:   "resourcequotadescriptors",
			Kind:     "ResourceQuotaDescriptor",
			ListKind: "ResourceQuotaDescriptorList",
		},
		Scope: apiextensionsv1.NamespaceScoped,
	},
}

ResourceQuotaDescriptorCRD fakes the ResourceQuotaDescriptor API as a CRD so we can manually set the values

Functions

func GetFreePorts

func GetFreePorts(n int) ([]int, error)

GetFreePorts request n free ready to use ports from the kernel

Types

type FakeContainer

type FakeContainer struct {
	containerd.Container
	UnderlyingContainer containers.Container
	FakeTask            FakeTask
	FakeID              string
}

func (FakeContainer) ID

func (fc FakeContainer) ID() string

ID returns container id

func (FakeContainer) Info

Info returns the underlying container for a fake container

func (FakeContainer) Task

Task returns the fake container task

type FakeContainerdClient

type FakeContainerdClient struct {
	Labels []map[string]string

	MetricsV1 []*statsv1.Metrics
	MetricsV2 []*statsv2.Metrics
	// contains filtered or unexported fields
}

func (*FakeContainerdClient) Close

func (c *FakeContainerdClient) Close() error

func (*FakeContainerdClient) Containers

func (c *FakeContainerdClient) Containers(ctx context.Context, filters ...string) ([]containerd.Container, error)

Containers returns fake containers with populate metrics

type FakeTask

type FakeTask struct {
	containerd.Task
	FakeMetrics types.Metric
}

func (*FakeTask) Metrics

func (t *FakeTask) Metrics(ctx context.Context) (*types.Metric, error)

Metrics returns metrics in a fake task

type IntegrationTestSuite

type IntegrationTestSuite struct {
	// Environment is the test control-plane environment
	Environment envtest.Environment

	// Config is a config for the control-plane
	Config *rest.Config
	// ConfigFilepath is set to the kubeconfig path to talk to the control-plane
	ConfigFilepath string
	// Client is a client to talk to the apiserver
	Client client.Client

	// TestCase is the test case to config
	TestCase TestCase
	// TestCaseObjects are the objects parsed for the test case
	TestCaseObjects []client.Object
}

IntegrationTestSuite is a test suite that configures a test environment

func (*IntegrationTestSuite) CheckDeleted

func (suite *IntegrationTestSuite) CheckDeleted(t testing.TB) bool

func (*IntegrationTestSuite) CheckHealth

func (suite *IntegrationTestSuite) CheckHealth(t testing.TB, url string, out *bytes.Buffer)

CheckHealth ensures the localhost:8080/healthz is healthy nolint: godox TODO: make this more generic

func (*IntegrationTestSuite) GetMetrics

func (suite *IntegrationTestSuite) GetMetrics(t testing.TB, url string, cmdOut *bytes.Buffer, prefixes ...string) (string, string)

GetMetrics reads the metrics from the metrics endpoint nolint: gosec

func (*IntegrationTestSuite) RunCommand

func (suite *IntegrationTestSuite) RunCommand(t testing.TB, cmd string, args ...string) (*exec.Cmd, *bytes.Buffer, chan error)

RunCommand runs the command asynchronously, returning the command + the output buffer

func (*IntegrationTestSuite) SetupTest

func (suite *IntegrationTestSuite) SetupTest(t testing.TB, tc TestCase)

SetupTest creates the objects in the apiserver

func (*IntegrationTestSuite) SetupTestSuite

func (suite *IntegrationTestSuite) SetupTestSuite(t testing.TB)

SetupTestSuite implements SetupSuite

func (*IntegrationTestSuite) StopCommand

func (suite *IntegrationTestSuite) StopCommand(t testing.TB, c *exec.Cmd)

StopCommand kills the command and it's child processes

func (*IntegrationTestSuite) TearDownTest

func (suite *IntegrationTestSuite) TearDownTest(t testing.TB)

TearDownTest implements TearDownTest

func (*IntegrationTestSuite) TearDownTestSuite

func (suite *IntegrationTestSuite) TearDownTestSuite(t testing.TB)

TearDownTestSuite implements TearDownSuite

func (*IntegrationTestSuite) WriteKubeconfig

func (suite *IntegrationTestSuite) WriteKubeconfig(t testing.TB) error

WriteKubeconfig writes the Config to a `kubeconfig` file

type TestCase

type TestCase struct {
	T testing.TB

	// Name of the test cases
	Name string

	// Environment is a envtest.Environment for integration tests
	EnvironmentFn func(*TestCase) *envtest.Environment

	// Environment is populated by EnvironmentFn
	Environment *envtest.Environment

	// MaskExpectedMetadata will drop all metadata fields except
	// name, namespace, labels, and annotations when doing comparison.
	MaskExpectedMetadata bool

	// Inputs are the input files
	Inputs map[string]string

	// Expected is the contents of the expected output
	Expected string

	// Error is the contents of the expected error if one is expected
	Error string

	// ErrorFilepath is where the error was read from
	ErrorFilepath string

	// ExpectedFilepath is where the expected results were read from
	ExpectedFilepath string

	// ExpectedValues are the expected values read from files configured
	// through ExpectedFiles in the TestCaseParser
	ExpectedValues map[string]string

	// Actual is the actual results observed
	Actual string

	// ActualValues are the actual values to compare to the ExpectedValues read from
	// the ExpectedFiles configured in the TestCaseParser
	ActualValues map[string]string

	// ClientInputsSuffix is a suffix to append to files which
	// should be parsed as inputs for a fake client.Client.
	ClientInputsSuffix string

	// ClearMeta if set to true will clear metadata that shouldn't be set
	// at creation time
	ClearMeta bool

	// ExpectedObjects are the expected objects read from expected_objects.yaml if present
	ExpectedObjects string

	// ExpectedEvents are the expected events read from expected_events.yaml if present
	ExpectedEvents string

	// ExpectedMetrics are the expected metrics to read from expected_metrics.txt if present
	ExpectedMetrics string

	// CompareObjects is set to lists' of object types to read from the apiserver and compare
	// to ExpectedObjects
	CompareObjects []client.ObjectList

	// CompareMetrics is set to a list of metric names to compare the results of
	CompareMetrics []string

	// FakeRecorder is set when requesting a fake recorder and used to compare ExpectedEvents
	FakeRecorder *record.FakeRecorder

	// Client is set when requesting a fake client and used to compare ExpectedObjects
	Client client.Client
}

TestCase contains a test case parsed from a testdata directory

func (TestCase) CreateObjects added in v0.6.2

func (tc TestCase) CreateObjects()

func (*TestCase) GetFakeClient

func (tc *TestCase) GetFakeClient(s *runtime.Scheme, buildOpts ...TestCaseFakeClientBuilder) (client.Client, error)

GetFakeClient returns a new client.Client populated with Kubernetes parsed from the testdata input files. Defaults to parsing objects from files with suffix `_client_runtime_objects.yaml`

func (*TestCase) GetFakeRecorder added in v0.6.2

func (tc *TestCase) GetFakeRecorder() *record.FakeRecorder

GetFakeRecorder returns a fake recorder which can be used to compare events

func (TestCase) GetObjects

func (tc TestCase) GetObjects(s *runtime.Scheme) ([]client.Object, []client.ObjectList, error)

func (TestCase) GetObjectsFromFile added in v0.6.2

func (tc TestCase) GetObjectsFromFile(js *sjson.Serializer, s *runtime.Scheme, filename, data string) ([]client.Object, []client.ObjectList, error)

GetObjectsFromFile parses the input objects from the test case

func (TestCase) UnmarshalInputsStrict

func (tc TestCase) UnmarshalInputsStrict(into map[string]interface{})

UnmarshalInputsStrict Unmarshals the TestCase Inputs (i.e. by filename) into the corresponding objects (e.g. pointers to structs)

func (TestCase) UpdateObjects added in v0.6.2

func (tc TestCase) UpdateObjects(s *runtime.Scheme, fn func()) error

UpdateObjects will update objects from files prefixed with "input_client_objects_updates" After each set of updates fn is called. Updates are performed in alphanumberic order by filename.

type TestCaseFakeClientBuilder added in v0.6.2

type TestCaseFakeClientBuilder func(*fake.ClientBuilder) *fake.ClientBuilder

TestCaseFakeClientBuilder is a function that can be used to modify the fake client builder before building the client.

type TestCaseParser

type TestCaseParser struct {
	// EnvironmentFn if specified will create an integration test environment for the test
	EnvironmentFn func(*TestCase) *envtest.Environment

	// EnvironmentStopFn if specified will create an integration test environment for the test
	EnvironmentStopFn func(*TestCase)

	// MaskExpectedMetadata will drop all metadata fields except
	// name, namespace, labels, and annotations when doing comparison.
	MaskExpectedMetadata bool

	// NameSuffix is appended to the test name
	NameSuffix string

	// Subdir is an optional subdirectory
	Subdir string

	// ExpectedFiles is a list of expected files.  The "expected_" prefix is applied to each
	// item when matching files. e.g. ExpectedFiles: [ "values.txt" ] will look for "expected_values.txt".
	// These are compared to the ActualValues map in the TestCase.  e.g. ActualValues[ "values.txt" ]
	// will be compared to the values read from the "expected_values.txt" file in the test directory
	// and is configured by setting ExpectedFiles to [ "values.txt" ] in the TestCaseParser.
	ExpectedFiles []string

	// InputSuffix is a suffix to append to the expected file
	ExpectedSuffix string

	// ClientInputsSuffix is a suffix to append to files which
	// should be parsed as inputs for a fake client.Client.
	ClientInputsSuffix string

	// DirPrefix is the directory prefix to filter on
	DirPrefix string

	// ClearMeta if set to true will clear metadata that shouldn't be set
	// at creation time
	ClearMeta bool

	// CompareObjects is set to a lists' of objects to read from the apiserver and
	// compare to the objects in expected_objects.yaml.
	CompareObjects []client.ObjectList

	// CompareListOptions are list options applied when comparing objects
	CompareListOptions []client.ListOption

	// CompareMetrics is set to a list of metrics to compare the results of
	CompareMetrics []string

	// CompareEvents if set to true will compare the events from the FakeRecorder to
	// the events in expected_events.yaml.
	CompareEvents bool
}

TestCaseParser parses tests cases from testdata directories. Test cases are assumed to be 1 per-subdirectory under "testdata" with the input in a file called "input" and the expected value in a file called "expected". Errors are stored

func (TestCaseParser) GetActualEvents added in v0.6.2

func (p TestCaseParser) GetActualEvents(t *testing.T, tc *TestCase) string

GetActualEvents reads objects from the FakeRecorder and returns them as yaml

func (TestCaseParser) GetActualMetrics added in v0.6.2

func (p TestCaseParser) GetActualMetrics(t *testing.T, names []string) string

GetActualMetrics gathers the metrics from the registry and returns a string value

func (TestCaseParser) GetActualObjects added in v0.6.2

func (p TestCaseParser) GetActualObjects(t *testing.T, tc *TestCase) string

GetActualObjects reads objects from the apiserver and returns them as yaml

func (TestCaseParser) GetTestCases

func (p TestCaseParser) GetTestCases() ([]TestCase, error)

GetTestCases parses the test cases from the testdata dir

func (TestCaseParser) SetupEnvTest added in v0.6.2

func (p TestCaseParser) SetupEnvTest(t *testing.T, tc *TestCase) func()

SetupEnvTest will setup and run and envtest environment (apiserver and etcd) for integration tests.Returns a function to stop the envtest. Credentials and coordinates will be injected into each webhook.

func (TestCaseParser) TestDir

func (p TestCaseParser) TestDir(t *testing.T, fn func(*TestCase) error)

TestDir invokes fn for each TestCase for in a "testdata" directory and verifies that the actual observed value matches the expected value

func (TestCaseParser) UpdateExpectedDir

func (p TestCaseParser) UpdateExpectedDir(t *testing.T, cases []TestCase, fn func(*TestCase) error)

UpdateExpectedDir invokes fn for each TestCase for in a "testdata" directory and updates the expected data file with the actual observed value

Jump to

Keyboard shortcuts

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