testutil

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2023 License: Apache-2.0 Imports: 38 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.BoolPtr(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.BoolPtr(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.T) bool

func (*IntegrationTestSuite) CheckHealth

func (suite *IntegrationTestSuite) CheckHealth(t *testing.T, 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.T, url string, cmdOut *bytes.Buffer, prefixes ...string) string

GetMetrics reads the metrics from the metrics endpoint nolint: gosec

func (*IntegrationTestSuite) RunCommand

func (suite *IntegrationTestSuite) RunCommand(t *testing.T, 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.T, tc TestCase)

SetupTest creates the objects in the apiserver

func (*IntegrationTestSuite) SetupTestSuite

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

SetupTestSuite implements SetupSuite

func (*IntegrationTestSuite) StopCommand

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

StopCommand kills the command and it's child processes

func (*IntegrationTestSuite) TearDownTest

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

TearDownTest implements TearDownTest

func (*IntegrationTestSuite) TearDownTestSuite

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

TearDownTestSuite implements TearDownSuite

func (*IntegrationTestSuite) WriteKubeconfig

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

WriteKubeconfig writes the Config to a `kubeconfig` file

type TestCase

type TestCase struct {
	T *testing.T

	// Name of the test cases
	Name string

	// 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

	// Actual is the actual results observed
	Actual 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
}

TestCase contains a test case parsed from a testdata directory

func (TestCase) GetFakeClient

func (tc TestCase) GetFakeClient(s *runtime.Scheme) (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) GetObjects

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

GetObjects 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)

type TestCaseParser

type TestCaseParser struct {
	// NameSuffix is appended to the test name
	NameSuffix string

	// Subdir is an optional subdirectory
	Subdir 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
}

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) GetTestCases

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

GetTestCases parses the test cases from the testdata dir

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