test

package
v0.0.0-...-e2048a1 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const LabelRemoveAllFinalizersOnDeletion = "greenhouse.test/removeAllFinalizersOnDeletion"

LabelRemoveAllFinalizersOnDeletion is used in the test context only to indicate a resource must be deleted even with finalizers present.

View Source
const (
	// TestNamespace is the namespace used for testing. Name reflects it represents a greenhouse org.
	TestNamespace = "test-org"
)

Variables

View Source
var (
	Cfg              *rest.Config
	RestClientGetter *clientutil.RestClientGetter
	K8sClient        client.Client
	K8sManager       ctrl.Manager
	KubeConfig       []byte

	Ctx context.Context

	// TestBeforeSuite configures the test suite.
	TestBeforeSuite = func() {
		logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

		SetDefaultEventuallyPollingInterval(1 * time.Second)
		SetDefaultEventuallyTimeout(1 * time.Minute)

		installCRDs := clientutil.GetEnvOrDefault("TEST_INSTALL_CRDS", "true") == "true"
		installWebhooks := len(allRegisterWebhookFuncs) > 0 && os.Getenv("TEST_INSTALL_WEBHOOKS") != "false"

		Cfg, K8sClient, testEnv, KubeConfig = StartControlPlane("", installCRDs, installWebhooks)
		_ = K8sClient

		RestClientGetter = clientutil.NewRestClientGetterFromRestConfig(Cfg, TestNamespace, clientutil.WithPersistentConfig())
		Expect(RestClientGetter).ToNot(BeNil(), "the RestClientGetter should not be nil")

		//+kubebuilder:scaffold:scheme
		var err error
		K8sManager, err = ctrl.NewManager(Cfg, ctrl.Options{
			Scheme: scheme.Scheme,
			Metrics: metricsserver.Options{
				BindAddress: "0",
			},
			WebhookServer: webhook.NewServer(webhook.Options{
				Host:    testEnv.WebhookInstallOptions.LocalServingHost,
				Port:    testEnv.WebhookInstallOptions.LocalServingPort,
				CertDir: testEnv.WebhookInstallOptions.LocalServingCertDir,
			}),
			LeaderElection: false,
		})
		Expect(err).
			ToNot(HaveOccurred(), "there must be no error creating a manager")
		Expect(K8sManager).
			NotTo(BeNil(), "the manager must not be nil")

		for webhookName, registerFunc := range allRegisterWebhookFuncs {
			logf.FromContext(Ctx, "message", "registering webhook", "name", webhookName)
			Expect(registerFunc(K8sManager)).To(Succeed(), "there must be no error registering the webhook", "name", webhookName)
		}

		for controllerName, registerFunc := range allRegisterControllerFuncs {
			Expect(registerFunc(controllerName, K8sManager)).
				To(Succeed(), "there must be no error registering the controller", "name", controllerName)
		}

		Ctx, cancel = context.WithCancel(context.TODO())
		go func() {
			defer GinkgoRecover()
			err = K8sManager.Start(Ctx)
			Expect(err).
				ToNot(HaveOccurred(), "there must be no error starting the manager")
		}()

		if len(allRegisterWebhookFuncs) > 0 {

			dialer := &net.Dialer{Timeout: time.Second}
			addrPort := fmt.Sprintf("%s:%d", testEnv.WebhookInstallOptions.LocalServingHost, testEnv.WebhookInstallOptions.LocalServingPort)
			Eventually(func() error {
				conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true})
				if err != nil {
					return err
				}
				conn.Close()
				return nil
			}, updateTimeout, pollInterval).Should(Succeed(), "there should be no error dialing the webhook server")
		}

		err = K8sClient.Create(Ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: TestNamespace}})
		Expect(err).NotTo(HaveOccurred(), "there should be no error creating the test namespace")
	}

	// TestAfterSuite configures the test suite.
	TestAfterSuite = func() {
		cancel()
		By("tearing down the test environment")
		Eventually(func() error {
			return testEnv.Stop()
		}).Should(Succeed(), "there should be no error stopping the test environment")
	}
)
View Source
var ClientObjectMatcherByName = func(name string) gomegaTypes.GomegaMatcher {
	return gstruct.MatchFields(
		gstruct.IgnoreExtras, gstruct.Fields{"ObjectMeta": gstruct.MatchFields(
			gstruct.IgnoreExtras, gstruct.Fields{"Name": Equal(
				name)})})
}

Functions

func DummyTailscaleClientGetter

func DummyTailscaleClientGetter(restClientGetter genericclioptions.RESTClientGetter, proxy, headscaleAddress string) (client.Client, error)

DummyTailscaleClienGetter is a dummy tailscale client getter for testing purposes. As we do not have a headscale setup for testing, we need to mock the tailscale client getter.

func MustDeleteCluster

func MustDeleteCluster(ctx context.Context, c client.Client, id client.ObjectKey)

MustDeleteCluster is used in the test context only and removes all clusters.

func MustDeleteSecretWithLabel

func MustDeleteSecretWithLabel(ctx context.Context, c client.Client, l string)

MustDeleteSecretWithLabel is used in the test context only and removes all secrets.

func MustReturnJSONFor

func MustReturnJSONFor(val any) *apiextensionsv1.JSON

MustReturnJSONFor marshals val to JSON and returns an apiextensionsv1.JSON.

func RegisterController

func RegisterController(controllerName string, f registerControllerFunc)

RegisterController registers a controller for the testbed. A currently running testbed is not affected.

func RegisterWebhook

func RegisterWebhook(webhookName string, f registerWebhookFunc)

RegisterWebhook registers a webhook for the testbed. A currently running testbed is not affected.

func StartControlPlane

func StartControlPlane(port string, installCRDs, installWebhooks bool) (*rest.Config, client.Client, *envtest.Environment, []byte)

Starts a envTest control plane and returns the config, client, envtest.Environment and raw kubeconfig.

func UnregisterController

func UnregisterController(controllerName string)

UnregisterController removes a controller from the testbed. A currently running testbed is not affected.

func UnregisterWebhook

func UnregisterWebhook(webhookName string)

UnregisterWebhook removes a webhook from the testbed. A currently running testbed is not affected.

Types

type FakeHeadscaleClient

type FakeHeadscaleClient struct {
	// IsUserDeleted is used to simulate the deletion of a user. If set to true, the GetUserFunc will return an error.
	IsUserDeleted bool

	CreateApiKeyFunc       func(context.Context, *v1.CreateApiKeyRequest, ...grpc.CallOption) (*v1.CreateApiKeyResponse, error) //no-lint:stylecheck
	CreatePreAuthKeyFunc   func(context.Context, *v1.CreatePreAuthKeyRequest, ...grpc.CallOption) (*v1.CreatePreAuthKeyResponse, error)
	CreateUserFunc         func(context.Context, *v1.CreateUserRequest, ...grpc.CallOption) (*v1.CreateUserResponse, error)
	DebugCreateMachineFunc func(context.Context, *v1.DebugCreateMachineRequest, ...grpc.CallOption) (*v1.DebugCreateMachineResponse, error)
	DeleteMachineFunc      func(context.Context, *v1.DeleteMachineRequest, ...grpc.CallOption) (*v1.DeleteMachineResponse, error)
	DeleteRouteFunc        func(context.Context, *v1.DeleteRouteRequest, ...grpc.CallOption) (*v1.DeleteRouteResponse, error)
	DeleteUserFunc         func(context.Context, *v1.DeleteUserRequest, ...grpc.CallOption) (*v1.DeleteUserResponse, error)
	DisableRouteFunc       func(context.Context, *v1.DisableRouteRequest, ...grpc.CallOption) (*v1.DisableRouteResponse, error)
	EnableRouteFunc        func(context.Context, *v1.EnableRouteRequest, ...grpc.CallOption) (*v1.EnableRouteResponse, error)
	ExpireApiKeyFunc       func(context.Context, *v1.ExpireApiKeyRequest, ...grpc.CallOption) (*v1.ExpireApiKeyResponse, error) //no-lint:stylecheck
	ExpireMachineFunc      func(context.Context, *v1.ExpireMachineRequest, ...grpc.CallOption) (*v1.ExpireMachineResponse, error)
	ExpirePreAuthKeyFunc   func(context.Context, *v1.ExpirePreAuthKeyRequest, ...grpc.CallOption) (*v1.ExpirePreAuthKeyResponse, error)
	GetMachineFunc         func(context.Context, *v1.GetMachineRequest, ...grpc.CallOption) (*v1.GetMachineResponse, error)
	GetMachineRoutesFunc   func(context.Context, *v1.GetMachineRoutesRequest, ...grpc.CallOption) (*v1.GetMachineRoutesResponse, error)
	GetRoutesFunc          func(context.Context, *v1.GetRoutesRequest, ...grpc.CallOption) (*v1.GetRoutesResponse, error)
	GetUserFunc            func(context.Context, *v1.GetUserRequest, ...grpc.CallOption) (*v1.GetUserResponse, error)
	ListApiKeysFunc        func(context.Context, *v1.ListApiKeysRequest, ...grpc.CallOption) (*v1.ListApiKeysResponse, error)
	ListMachinesFunc       func(context.Context, *v1.ListMachinesRequest, ...grpc.CallOption) (*v1.ListMachinesResponse, error)
	ListPreAuthKeysFunc    func(context.Context, *v1.ListPreAuthKeysRequest, ...grpc.CallOption) (*v1.ListPreAuthKeysResponse, error)
	ListUsersFunc          func(context.Context, *v1.ListUsersRequest, ...grpc.CallOption) (*v1.ListUsersResponse, error)
	MoveMachineFunc        func(context.Context, *v1.MoveMachineRequest, ...grpc.CallOption) (*v1.MoveMachineResponse, error)
	RegisterMachineFunc    func(context.Context, *v1.RegisterMachineRequest, ...grpc.CallOption) (*v1.RegisterMachineResponse, error)
	RenameMachineFunc      func(context.Context, *v1.RenameMachineRequest, ...grpc.CallOption) (*v1.RenameMachineResponse, error)
	RenameUserFunc         func(context.Context, *v1.RenameUserRequest, ...grpc.CallOption) (*v1.RenameUserResponse, error)
	SetTagsFunc            func(context.Context, *v1.SetTagsRequest, ...grpc.CallOption) (*v1.SetTagsResponse, error)
}

FakeHeadscaleClient is a fake implementation of the HeadscaleClient interface.

func (FakeHeadscaleClient) CreateApiKey

func (FakeHeadscaleClient) CreatePreAuthKey

func (FakeHeadscaleClient) CreateUser

func (FakeHeadscaleClient) DebugCreateMachine

func (FakeHeadscaleClient) DeleteMachine

func (FakeHeadscaleClient) DeleteRoute

func (FakeHeadscaleClient) DeleteUser

func (FakeHeadscaleClient) DisableRoute

func (FakeHeadscaleClient) EnableRoute

func (FakeHeadscaleClient) ExpireApiKey

func (FakeHeadscaleClient) ExpireMachine

func (FakeHeadscaleClient) ExpirePreAuthKey

func (FakeHeadscaleClient) GetMachine

func (FakeHeadscaleClient) GetMachineRoutes

func (FakeHeadscaleClient) GetRoutes

func (FakeHeadscaleClient) GetUser

func (FakeHeadscaleClient) ListApiKeys

func (FakeHeadscaleClient) ListMachines

func (FakeHeadscaleClient) ListPreAuthKeys

func (FakeHeadscaleClient) ListUsers

func (FakeHeadscaleClient) MoveMachine

func (FakeHeadscaleClient) RegisterMachine

func (FakeHeadscaleClient) RenameMachine

func (FakeHeadscaleClient) RenameUser

func (FakeHeadscaleClient) SetTags

Jump to

Keyboard shortcuts

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