nomostest

package
v1.13.0-rc.4 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2022 License: Apache-2.0 Imports: 88 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AcmeDir is the sync directory of the test source repository.
	AcmeDir = "acme"
	// Manifests is the folder of the test manifests
	Manifests = "manifests"
)
View Source
const (

	// MainBranch is static as behavior when switching branches is never under
	// test.
	MainBranch = "main"

	// GitKeepFileName is a conventional name for an empty file you add to
	// directories in git when you want to make sure the directory is retained even
	// when all the other files are deleted.
	// Without this file, the directory may remain locally, but won't exist in git.
	GitKeepFileName = ".gitkeep"
)
View Source
const NomosE2E = "nomos-e2e"

NomosE2E is the subdirectory inside the filesystem's temporary directory in which we write test data.

View Source
const TestLabel = "nomos-test"

TestLabel is the label added to all test objects, ensuring we can clean up non-ephemeral clusters when tests are complete.

View Source
const TestLabelValue = "enabled"

TestLabelValue is the value assigned to the above label.

Variables

AddTestLabel is automatically added to objects created or declared with the NT methods, or declared with Repository.Add.

This isn't perfect - objects added via other means (such as kubectl) will bypass this.

View Source
var DefaultRootReconcilerName = core.RootReconcilerName(configsync.RootSyncName)

DefaultRootReconcilerName is the root-reconciler name of the default RootSync object: "root-sync".

View Source
var DefaultRootRepoNamespacedName = RootSyncNN(configsync.RootSyncName)

DefaultRootRepoNamespacedName is the NamespacedName of the default RootSync object.

View Source
var ErrFailedPredicate = errors.New("failed predicate")

ErrFailedPredicate indicates the the object on the API server does not match the Predicate.

View Source
var ErrWrongType = errors.New("wrong type")

ErrWrongType indicates that the caller passed an object of the incorrect type to the Predicate.

View Source
var IsReconcilerManagerConfigMap = func(obj client.Object) bool {
	return obj.GetName() == "reconciler-manager-cm" &&
		obj.GetNamespace() == "config-management-system" &&
		obj.GetObjectKind().GroupVersionKind() == kinds.ConfigMap()
}

IsReconcilerManagerConfigMap returns true if passed obj is the reconciler-manager ConfigMap reconciler-manager-cm in config-management namespace.

Functions

func Clean

func Clean(nt *NT, failOnError FailOnError)

Clean removes all objects of types registered in the scheme, with the above caveats. It should be run before and after a test is run against any non-ephemeral cluster.

It is unnecessary to run this on Kind clusters that exist only for the duration of a single test.

func CreateNamespaceSecret

func CreateNamespaceSecret(nt *NT, ns string)

CreateNamespaceSecret creates secrets in a given namespace using local paths.

func DefaultRootSha1Fn

func DefaultRootSha1Fn(nt *NT, nn types.NamespacedName) (string, error)

DefaultRootSha1Fn is the default function to retrieve the commit hash of the root repo.

func DeleteManagedNamespaces

func DeleteManagedNamespaces(nt *NT)

DeleteManagedNamespaces deletes all the namespaces managed by Config Sync.

func DeletePodByLabel

func DeletePodByLabel(nt *NT, label, value string, waitForChildren bool)

DeletePodByLabel deletes pods that have the label and waits until new pods come up.

func DeleteRemoteRepos

func DeleteRemoteRepos(nt *NT)

DeleteRemoteRepos removes all remote repos on the Git provider.

func FailIfUnknown

func FailIfUnknown(t testing.NTB, scheme *runtime.Scheme, o client.Object)

FailIfUnknown fails the test if the passed type is not declared in the passed scheme.

func InitGitRepos

func InitGitRepos(nt *NT, repos ...types.NamespacedName) string

InitGitRepos initializes the repositories in the testing git-server and returns the pod names.

func IsEstablished

func IsEstablished(o client.Object) error

IsEstablished returns true if the given CRD is established on the cluster, which indicates if discovery knows about it yet. For more info see https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#create-a-customresourcedefinition

func NewOptStruct

func NewOptStruct(testName, tmpDir string, t testing2.NTB, ntOptions ...ntopts.Opt) *ntopts.New

NewOptStruct initializes the nomostest options.

func NewPodReady

func NewPodReady(nt *NT, labelName, currentLabel, childLabel string, oldCurrentPods, oldChildPods []corev1.Pod) error

NewPodReady checks if the new created pods are ready. It also checks if the new children pods that are managed by the pods are ready.

func NotPendingDeletion

func NotPendingDeletion(o client.Object) error

NotPendingDeletion ensures o is not pending deletion.

Check this when the object could be scheduled for deletion, to avoid flaky behavior when we're ensuring we don't want something to be deleted.

func RemoteNsRepoSha1Fn

func RemoteNsRepoSha1Fn(nt *NT, nn types.NamespacedName) (string, error)

RemoteNsRepoSha1Fn returns .status.lastSyncedCommit as the latest sha1 for the Namespace Repo.

func RemoteRootRepoSha1Fn

func RemoteRootRepoSha1Fn(nt *NT, nn types.NamespacedName) (string, error)

RemoteRootRepoSha1Fn returns .status.lastSyncedCommit as the latest sha1.

func RepoSyncClusterRole

func RepoSyncClusterRole() *rbacv1.ClusterRole

RepoSyncClusterRole returns clusterrole with permissions to manage resources in the cluster.

func RepoSyncNN

func RepoSyncNN(ns, name string) types.NamespacedName

RepoSyncNN returns the NamespacedName of the RepoSync object.

func RepoSyncObjectV1Alpha1

func RepoSyncObjectV1Alpha1(nn types.NamespacedName, repoURL string) *v1alpha1.RepoSync

RepoSyncObjectV1Alpha1 returns the default RepoSync object in the given namespace. SourceFormat for RepoSync must be Unstructured (default), so it's left unspecified.

func RepoSyncObjectV1Alpha1FromNonRootRepo

func RepoSyncObjectV1Alpha1FromNonRootRepo(nt *NT, nn types.NamespacedName) *v1alpha1.RepoSync

RepoSyncObjectV1Alpha1FromNonRootRepo returns a v1alpha1 RepoSync object which uses a repo from nt.NonRootRepos.

func RepoSyncObjectV1Beta1

func RepoSyncObjectV1Beta1(nn types.NamespacedName, repoURL string, sourceFormat filesystem.SourceFormat) *v1beta1.RepoSync

RepoSyncObjectV1Beta1 returns the default RepoSync object with version v1beta1 in the given namespace.

func RepoSyncObjectV1Beta1FromNonRootRepo

func RepoSyncObjectV1Beta1FromNonRootRepo(nt *NT, nn types.NamespacedName) *v1beta1.RepoSync

RepoSyncObjectV1Beta1FromNonRootRepo returns a v1beta1 RepoSync object which uses a repo from nt.NonRootRepos.

func RepoSyncObjectV1Beta1FromOtherRootRepo

func RepoSyncObjectV1Beta1FromOtherRootRepo(nt *NT, nn types.NamespacedName, repoName string) *v1beta1.RepoSync

RepoSyncObjectV1Beta1FromOtherRootRepo returns a v1beta1 RepoSync object which uses a repo from nt.RootRepos.

func RepoSyncRoleBinding

func RepoSyncRoleBinding(nn types.NamespacedName) *rbacv1.RoleBinding

RepoSyncRoleBinding returns rolebinding that grants service account permission to manage resources in the namespace.

func ResetMonoRepoSpec

func ResetMonoRepoSpec(nt *NT, sourceFormat filesystem.SourceFormat, policyDir string)

ResetMonoRepoSpec sets the mono repo's SOURCE_FORMAT and POLICY_DIR. It might cause the git-importer to restart.

func RestConfig

func RestConfig(t testing.NTB, optsStruct *ntopts.New)

RestConfig sets up the config for creating a Client connection to a K8s cluster. If --test-cluster=kind, it creates a Kind cluster. If --test-cluster=kubeconfig, it uses the context specified in kubeconfig.

func Retry

func Retry(timeout time.Duration, fn func() error) (time.Duration, error)

Retry calls the passed function until it returns nil, or the passed timeout expires.

Retries once per second until timeout expires. Returns how long the function retried, and the last error if the command timed out.

func RootSyncNN

func RootSyncNN(name string) types.NamespacedName

RootSyncNN returns the NamespacedName of the RootSync object.

func RootSyncObjectV1Alpha1

func RootSyncObjectV1Alpha1(name, repoURL string, sourceFormat filesystem.SourceFormat) *v1alpha1.RootSync

RootSyncObjectV1Alpha1 returns the default RootSync object.

func RootSyncObjectV1Alpha1FromRootRepo

func RootSyncObjectV1Alpha1FromRootRepo(nt *NT, name string) *v1alpha1.RootSync

RootSyncObjectV1Alpha1FromRootRepo returns a v1alpha1 RootSync object which uses a repo from nt.RootRepos.

func RootSyncObjectV1Beta1

func RootSyncObjectV1Beta1(name, repoURL string, sourceFormat filesystem.SourceFormat) *v1beta1.RootSync

RootSyncObjectV1Beta1 returns the default RootSync object with version v1beta1.

func RootSyncObjectV1Beta1FromOtherRootRepo

func RootSyncObjectV1Beta1FromOtherRootRepo(nt *NT, syncName, repoName string) *v1beta1.RootSync

RootSyncObjectV1Beta1FromOtherRootRepo returns a v1beta1 RootSync object which uses a repo from a specific nt.RootRepo.

func RootSyncObjectV1Beta1FromRootRepo

func RootSyncObjectV1Beta1FromRootRepo(nt *NT, name string) *v1beta1.RootSync

RootSyncObjectV1Beta1FromRootRepo returns a v1beta1 RootSync object which uses a repo from nt.RootRepos.

func SetPolicyDir

func SetPolicyDir(nt *NT, name, policyDir string)

SetPolicyDir updates the root-sync object with the provided policyDir.

func StopWebhook

func StopWebhook(nt *NT)

StopWebhook removes the Config Sync ValidatingWebhookConfiguration object.

func StructuredNSPath

func StructuredNSPath(namespace, resourceName string) string

StructuredNSPath returns structured path with namespace and resourcename in repo.

func SwitchMode

func SwitchMode(nt *NT, sourceFormat filesystem.SourceFormat)

SwitchMode switches either from mono-repo to multi-repo or from multi-repo to mono-repo. It then installs ConfigSync for the new mode.

func TestClusterName

func TestClusterName(t testing.NTB) string

TestClusterName returns the name of the test cluster.

func TestDir

func TestDir(t testing2.NTB) string

TestDir creates a unique temporary directory for the E2E test.

Returned directory is absolute and OS-specific.

func Wait

func Wait(t testing.NTB, opName string, timeout time.Duration, condition func() error, opts ...WaitOption)

Wait provides a logged wait for condition to return nil with options for timeout. It fails the test on errors.

func WaitForCRDs

func WaitForCRDs(nt *NT, crds []string) error

WaitForCRDs waits until the specified CRDs are established on the cluster.

func WaitForWebhookReadiness

func WaitForWebhookReadiness(nt *NT)

WaitForWebhookReadiness waits up to 3 minutes for the wehbook becomes ready. If the webhook still is not ready after 3 minutes, the test would fail.

func WaitToTerminate

func WaitToTerminate(nt *NT, gvk schema.GroupVersionKind, name, namespace string, opts ...WaitOption)

WaitToTerminate waits for the passed object to be deleted. Immediately fails the test if the object is not deleted within the timeout.

func WrongTypeErr

func WrongTypeErr(got, want interface{}) error

WrongTypeErr reports that the passed type was not equivalent to the wanted type.

Types

type FailOnError

type FailOnError bool

FailOnError indicates whether the clean task should fail the test. If it is false, it only logs the failure without failing the test. The test should fail if the cleanup task fails before running a test. We tolerate the after-test cleanup failure as the before-test cleanup will guarantee the cluster is clean.

type MetricsSyncOption

type MetricsSyncOption func(csm *testmetrics.ConfigSyncMetrics) error

MetricsSyncOption determines where metrics will be synced to

func SyncMetricsToLatestCommit

func SyncMetricsToLatestCommit(nt *NT) MetricsSyncOption

SyncMetricsToLatestCommit syncs metrics to the latest commit

func SyncMetricsToReconcilerSourceError

func SyncMetricsToReconcilerSourceError(reconciler string) MetricsSyncOption

SyncMetricsToReconcilerSourceError syncs metrics to a reconciler source error

func SyncMetricsToReconcilerSyncError

func SyncMetricsToReconcilerSyncError(reconciler string) MetricsSyncOption

SyncMetricsToReconcilerSyncError syncs metrics to a reconciler sync error

type NT

type NT struct {
	Context context.Context

	// T is the test environment for the test.
	// Used to exit tests early when setup fails, and for logging.
	T testing.NTB

	// ClusterName is the unique name of the test run.
	ClusterName string

	// TmpDir is the temporary directory the test will write to.
	// By default, automatically deleted when the test finishes.
	TmpDir string

	// Config specifies how to create a new connection to the cluster.
	Config *rest.Config

	// Client is the underlying client used to talk to the Kubernetes cluster.
	//
	// Most tests shouldn't need to talk directly to this, unless simulating
	// direct interactions with the API Server.
	Client client.Client

	// IsGKEAutopilot indicates if the test cluster is a GKE Autopilot cluster.
	IsGKEAutopilot bool

	// DefaultWaitTimeout is the default timeout for tests to wait for sync completion.
	DefaultWaitTimeout time.Duration

	// DefaultReconcileTimeout is the default timeout for the applier to wait
	// for object reconcilition.
	DefaultReconcileTimeout time.Duration

	// RootRepos is the root repositories the cluster is syncing to.
	// The key is the RootSync name and the value points to the corresponding Repository object.
	// Each test case was set up with a default RootSync (`root-sync`) installed.
	// After the test, all other RootSync or RepoSync objects are deleted, but the default one persists.
	RootRepos map[string]*Repository

	// NonRootRepos is the Namespace repositories the cluster is syncing to.
	// Only used in multi-repo tests.
	// The key is the namespace and name of the RepoSync object, the value points to the corresponding Repository object.
	NonRootRepos map[types.NamespacedName]*Repository

	// MultiRepo indicates that the test case is for multi-repo Config Sync.
	MultiRepo bool

	// ReconcilerPollingPeriod defines how often the reconciler should poll the
	// filesystem for updates to the source or rendered configs.
	ReconcilerPollingPeriod time.Duration

	// HydrationPollingPeriod defines how often the hydration-controller should
	// poll the filesystem for rendering the DRY configs.
	HydrationPollingPeriod time.Duration

	// ReconcilerMetrics is a map of scraped multirepo metrics.
	ReconcilerMetrics testmetrics.ConfigSyncMetrics

	// GitProvider is the provider that hosts the Git repositories.
	GitProvider gitproviders.GitProvider

	// RemoteRepositories maintains a map between the repo local name and the remote repository.
	// It includes both root repo and namespace repos and can be shared among test cases.
	// It is used to reuse existing repositories instead of creating new ones.
	RemoteRepositories map[types.NamespacedName]*Repository
	// contains filtered or unexported fields
}

NT represents the test environment for a single Nomos end-to-end test case.

func FreshTestEnv

func FreshTestEnv(t testing2.NTB, opts *ntopts.New) *NT

FreshTestEnv establishes a connection to a test cluster based on the passed

options.

Marks the test as parallel. For now we have no tests which *can't* be made parallel; if we need that in the future we can make a version of this function that doesn't do this. As below keeps us from forgetting to mark tests as parallel, and unnecessarily waiting.

The following are guaranteed to be available when this function returns: 1) A connection to the Kubernetes cluster. 2) A functioning git server hosted on the cluster. 3) A fresh ACM installation.

func New

func New(t *testing.T, ntOptions ...ntopts.Opt) *NT

New establishes a connection to a test cluster and prepares it for testing.

func NewSharedNT

func NewSharedNT() *NT

NewSharedNT sets up the shared config sync testing environment globally.

func SharedNT

func SharedNT() *NT

SharedNT returns the shared test environment.

func SharedTestEnv

func SharedTestEnv(t testing2.NTB, opts *ntopts.New) *NT

SharedTestEnv connects to a shared test cluster.

func (*NT) ApplyGatekeeperTestData

func (nt *NT) ApplyGatekeeperTestData(file, crd string) error

ApplyGatekeeperTestData is an exception to the "all test data is specified inline" rule. It isn't informative to literally have the CRD specifications in the test code, and we have strict type requirements on how the CRD is laid out.

func (*NT) Create

func (nt *NT) Create(obj client.Object, opts ...client.CreateOption) error

Create is identical to Create defined for client.Client, but without requiring Context.

func (*NT) DebugLog

func (nt *NT) DebugLog(args ...interface{})

DebugLog is like nt.T.Log, but only prints the message if --debug is passed. Use for fine-grained information that is unlikely to cause failures in CI.

func (*NT) DebugLogf

func (nt *NT) DebugLogf(format string, args ...interface{})

DebugLogf is like nt.T.Logf, but only prints the message if --debug is passed. Use for fine-grained information that is unlikely to cause failures in CI.

func (*NT) Delete

func (nt *NT) Delete(obj client.Object, opts ...client.DeleteOption) error

Delete is identical to Delete defined for client.Client, but without requiring Context.

func (*NT) DeleteAllOf

func (nt *NT) DeleteAllOf(obj client.Object, opts ...client.DeleteAllOfOption) error

DeleteAllOf is identical to DeleteAllOf defined for client.Client, but without requiring Context.

func (*NT) ForwardToFreePort

func (nt *NT) ForwardToFreePort(ns, pod, port string) (int, error)

ForwardToFreePort forwards a local port to a port on the pod and returns the local port chosen by kubectl.

func (*NT) Get

func (nt *NT) Get(name, namespace string, obj client.Object) error

Get is identical to Get defined for client.Client, except:

1) Context implicitly uses the one created for the test case. 2) name and namespace are strings instead of requiring client.ObjectKey.

Leave namespace as empty string for cluster-scoped resources.

func (*NT) GetCurrentMetrics

func (nt *NT) GetCurrentMetrics(syncOptions ...MetricsSyncOption) (time.Duration, testmetrics.ConfigSyncMetrics)

GetCurrentMetrics fetches metrics from the otel-collector ensuring that the metrics have been updated for with the most recent commit hashes.

func (*NT) GitPrivateKeyPath deprecated

func (nt *NT) GitPrivateKeyPath() string

GitPrivateKeyPath returns the path to the git private key.

Deprecated: only the legacy bats tests should make use of this function.

func (*NT) GitRepoPort deprecated

func (nt *NT) GitRepoPort() int

GitRepoPort returns the path to the git private key.

Deprecated: only the legacy bats tests should make use of this function.

func (*NT) KubeconfigPath deprecated

func (nt *NT) KubeconfigPath() string

KubeconfigPath returns the path to the kubeconifg file.

Deprecated: only the legacy bats tests should make use of this function.

func (*NT) Kubectl

func (nt *NT) Kubectl(args ...string) ([]byte, error)

Kubectl is a convenience method for calling kubectl against the currently-connected cluster. Returns STDOUT, and an error if kubectl exited abnormally.

If you want to fail the test immediately on failure, use MustKubectl.

func (*NT) List

func (nt *NT) List(obj client.ObjectList, opts ...client.ListOption) error

List is identical to List defined for client.Client, but without requiring Context.

func (*NT) MergePatch

func (nt *NT) MergePatch(obj client.Object, patch string, opts ...client.PatchOption) error

MergePatch uses the object to construct a merge patch for the fields provided.

func (*NT) MustKubectl

func (nt *NT) MustKubectl(args ...string) []byte

MustKubectl fails the test immediately if the kubectl command fails. On success, returns STDOUT.

func (*NT) MustMergePatch

func (nt *NT) MustMergePatch(obj client.Object, patch string, opts ...client.PatchOption)

MustMergePatch is like MergePatch but will call t.Fatal if the patch fails.

func (*NT) PodLogs

func (nt *NT) PodLogs(namespace, deployment, container string, previousPodLog bool)

PodLogs prints the logs from the specified deployment. If there is an error getting the logs for the specified deployment, prints the error.

func (*NT) PortForwardOtelCollector

func (nt *NT) PortForwardOtelCollector()

PortForwardOtelCollector forwards the otel-collector pod.

func (*NT) RenewClient

func (nt *NT) RenewClient()

RenewClient gets a new Client for talking to the cluster.

Required whenever we expect the set of available types on the cluster to change. Called automatically at the end of WaitForRootSync.

The only reason to call this manually from within a test is if we expect a controller to create a CRD dynamically, or if the test requires applying a CRD directly to the API Server.

func (*NT) SupportV1Beta1CRD

func (nt *NT) SupportV1Beta1CRD() (bool, error)

SupportV1Beta1CRD checks if v1beta1 CRD is supported in the current testing cluster.

func (*NT) Update

func (nt *NT) Update(obj client.Object, opts ...client.UpdateOption) error

Update is identical to Update defined for client.Client, but without requiring Context.

func (*NT) Validate

func (nt *NT) Validate(name, namespace string, o client.Object, predicates ...Predicate) error

Validate returns an error if the indicated object does not exist.

Validates the object against each of the passed Predicates, returning error if any Predicate fails.

func (*NT) ValidateErrorMetricsNotFound

func (nt *NT) ValidateErrorMetricsNotFound() error

ValidateErrorMetricsNotFound validates that no error metrics are emitted from any of the reconcilers.

func (*NT) ValidateGitSyncDepthOverrideCount

func (nt *NT) ValidateGitSyncDepthOverrideCount(count int) error

ValidateGitSyncDepthOverrideCount validates the `git_sync_depth_override_count` metric.

func (*NT) ValidateMetricNotFound

func (nt *NT) ValidateMetricNotFound(metricName string) error

ValidateMetricNotFound validates that a metric does not exist.

func (*NT) ValidateMetrics

func (nt *NT) ValidateMetrics(syncOption MetricsSyncOption, fn func() error) error

ValidateMetrics pulls the latest metrics, updates the metrics on NT and executes the parameter function.

func (*NT) ValidateMultiRepoMetrics

func (nt *NT) ValidateMultiRepoMetrics(reconciler string, numResources int, gvkMetrics ...testmetrics.GVKMetric) error

ValidateMultiRepoMetrics validates all the multi-repo metrics. It checks all non-error metrics are recorded with the correct tags and values.

func (*NT) ValidateNoSSLVerifyCount

func (nt *NT) ValidateNoSSLVerifyCount(count int) error

ValidateNoSSLVerifyCount checks that the `no_ssl_verify_count` metric has the correct value.

func (*NT) ValidateNotFound

func (nt *NT) ValidateNotFound(name, namespace string, o client.Object) error

ValidateNotFound returns an error if the indicated object exists.

`o` must either be: 1) a struct pointer to the type of the object to search for, or 2) an unstructured.Unstructured with the type information filled in.

func (*NT) ValidateReconcilerErrors

func (nt *NT) ValidateReconcilerErrors(reconciler, component string) error

ValidateReconcilerErrors validates that the `reconciler_error` metric exists for the correct reconciler and the tagged component has the correct value.

func (*NT) ValidateResourceOverrideCount

func (nt *NT) ValidateResourceOverrideCount(reconciler, containerName, resourceType string, count int) error

ValidateResourceOverrideCount validates that the `resource_override_count` metric exists for the correct reconciler.

func (*NT) ValidateResourceOverrideCountMissingTags

func (nt *NT) ValidateResourceOverrideCountMissingTags(tags []tag.Tag) error

ValidateResourceOverrideCountMissingTags checks that the `resource_override_count` metric misses the specific the tags.

func (*NT) WaitForNamespace

func (nt *NT) WaitForNamespace(timeout time.Duration, namespace string)

WaitForNamespace waits for a namespace to exist and be ready to use

func (*NT) WaitForNamespaces

func (nt *NT) WaitForNamespaces(timeout time.Duration, namespaces ...string)

WaitForNamespaces waits for namespaces to exist and be ready to use

func (*NT) WaitForRepoImportErrorCode

func (nt *NT) WaitForRepoImportErrorCode(code string, opts ...WaitOption)

WaitForRepoImportErrorCode waits until the given error code is present on the Repo resource.

func (*NT) WaitForRepoSourceError

func (nt *NT) WaitForRepoSourceError(code string, opts ...WaitOption)

WaitForRepoSourceError waits until the given error (code and message) is present on the Repo resource

func (*NT) WaitForRepoSourceErrorClear

func (nt *NT) WaitForRepoSourceErrorClear(opts ...WaitOption)

WaitForRepoSourceErrorClear waits until the given error code disappears from the Repo resource

func (*NT) WaitForRepoSyncSourceError

func (nt *NT) WaitForRepoSyncSourceError(ns, rsName, code, message string, opts ...WaitOption)

WaitForRepoSyncSourceError waits until the given error (code and message) is present on the RepoSync resource

func (*NT) WaitForRepoSyncStalledError

func (nt *NT) WaitForRepoSyncStalledError(rsNamespace, rsName, reason, message string)

WaitForRepoSyncStalledError waits until the given Stalled error is present on the RepoSync resource.

func (*NT) WaitForRepoSyncSyncError

func (nt *NT) WaitForRepoSyncSyncError(ns, rsName, code string, message string, opts ...WaitOption)

WaitForRepoSyncSyncError waits until the given error (code and message) is present on the RepoSync resource

func (*NT) WaitForRepoSyncs

func (nt *NT) WaitForRepoSyncs(options ...WaitForRepoSyncsOption)

WaitForRepoSyncs is a convenience method that waits for all repositories to sync.

Unless you're testing pre-CSMR functionality related to in-cluster objects, you should be using this function to block on ConfigSync to sync everything.

If you want to check the internals of specific objects (e.g. the error field of a RepoSync), use nt.Validate() - possibly in a Retry.

func (*NT) WaitForRootSyncRenderingError

func (nt *NT) WaitForRootSyncRenderingError(rsName, code string, message string, opts ...WaitOption)

WaitForRootSyncRenderingError waits until the given error (code and message) is present on the RootSync resource

func (*NT) WaitForRootSyncSourceError

func (nt *NT) WaitForRootSyncSourceError(rsName, code string, message string, opts ...WaitOption)

WaitForRootSyncSourceError waits until the given error (code and message) is present on the RootSync resource

func (*NT) WaitForRootSyncStalledError

func (nt *NT) WaitForRootSyncStalledError(rsNamespace, rsName, reason, message string)

WaitForRootSyncStalledError waits until the given Stalled error is present on the RootSync resource.

func (*NT) WaitForRootSyncSyncError

func (nt *NT) WaitForRootSyncSyncError(rsName, code string, message string, ignoreSyncingCondition bool, opts ...WaitOption)

WaitForRootSyncSyncError waits until the given error (code and message) is present on the RootSync resource

func (*NT) WaitForSync

func (nt *NT) WaitForSync(gvk schema.GroupVersionKind, name, namespace string, timeout time.Duration,
	sha1Func Sha1Func, syncSha1 func(string) Predicate, syncDirPair *SyncDirPredicatePair)

WaitForSync waits for the specified object to be synced.

o returns a new object of the type to check is synced. It can't just be a struct pointer as calling .Get on the same struct pointer multiple times has undefined behavior.

name and namespace identify the specific object to check.

timeout specifies the maximum duration allowed for the object to sync.

sha1Func is the function that dynamically computes the expected commit sha1.

syncSha1 is a Predicate to use to tell whether the object is synced as desired.

syncDirPair is a pair of sync dir and the corresponding predicate that tells whether it is synced to the expected directory. It will skip the validation if it is not provided.

type Predicate

type Predicate func(o client.Object) error

Predicate evaluates a client.Object, returning an error if it fails validation.

func AllResourcesAreCurrent

func AllResourcesAreCurrent() Predicate

AllResourcesAreCurrent ensures that the managed resources are all Current in the ResourceGroup CR.

func ClusterConfigHasToken

func ClusterConfigHasToken(sha1 string) Predicate

ClusterConfigHasToken created a Predicate that ensures .spec.token and .status.token on the passed ClusterConfig matches sha1.

This means ACM has successfully synced all cluster-scoped objects from the latest repo commit to the cluster.

func DeploymentHasEnvVar

func DeploymentHasEnvVar(containerName, key, value string) Predicate

DeploymentHasEnvVar check whether the deployment contains environment variable with specified name and value

func DeploymentMissingEnvVar

func DeploymentMissingEnvVar(containerName, key string) Predicate

DeploymentMissingEnvVar check whether the deployment does not contain environment variable with specified name and value

func HasAllAnnotationKeys

func HasAllAnnotationKeys(keys ...string) Predicate

HasAllAnnotationKeys returns a predicate that tests if an Object has the specified annotation keys.

func HasAllNomosMetadata

func HasAllNomosMetadata(multiRepo bool) Predicate

HasAllNomosMetadata ensures that the object contains the expected nomos labels and annotations.

func HasAnnotation

func HasAnnotation(key, value string) Predicate

HasAnnotation returns a predicate that tests if an Object has the specified annotation key/value pair.

func HasAnnotationKey

func HasAnnotationKey(key string) Predicate

HasAnnotationKey returns a predicate that tests if an Object has the specified annotation key.

func HasCorrectResourceRequestsLimits

func HasCorrectResourceRequestsLimits(containerName string, cpuRequest, cpuLimit, memoryRequest, memoryLimit resource.Quantity) Predicate

HasCorrectResourceRequestsLimits verify a root/namespace reconciler container has the correct resource requests and limits.

func HasExactlyAnnotationKeys

func HasExactlyAnnotationKeys(wantKeys ...string) Predicate

HasExactlyAnnotationKeys ensures the Object has exactly the passed set of annotations, ignoring values.

func HasExactlyImageName

func HasExactlyImageName(containerName string, expectImageName string) Predicate

HasExactlyImageName ensures a container has the expected image name

func HasExactlyLabelKeys

func HasExactlyLabelKeys(wantKeys ...string) Predicate

HasExactlyLabelKeys ensures the Object has exactly the passed set of labels, ignoring values.

func HasLabel

func HasLabel(key, value string) Predicate

HasLabel returns a predicate that tests if an Object has the specified label key/value pair.

func HasStatus

func HasStatus() Predicate

HasStatus checks that the ResourceGroup object has a non empty status field.

func IsManagedBy

func IsManagedBy(nt *NT, scope declared.Scope, syncName string) Predicate

IsManagedBy checks that the object is managed by configsync, has the expected resource manager, and has a valid resource-id. Use diff.IsManager if you just need a boolean without errors.

func IsNotManaged

func IsNotManaged(nt *NT) Predicate

IsNotManaged checks that the object is NOT managed by configsync. Use differ.ManagedByConfigSync if you just need a boolean without errors.

func MissingAnnotation

func MissingAnnotation(key string) Predicate

MissingAnnotation returns a predicate that tests that an object does not have a specified annotation.

func MissingLabel

func MissingLabel(key string) Predicate

MissingLabel returns a predicate that tests that an object does not have a specified label.

func NoConfigSyncMetadata

func NoConfigSyncMetadata() Predicate

NoConfigSyncMetadata ensures that the object doesn't contain configsync labels and annotations.

func NoStatus

func NoStatus() Predicate

NoStatus checks that the ResourceGroup object has an empty status field.

func RepoHasStatusSyncLatestToken

func RepoHasStatusSyncLatestToken(sha1 string) Predicate

RepoHasStatusSyncLatestToken ensures ACM has reported all objects were successfully synced to the repository.

func RepoSyncHasStatusSyncCommit

func RepoSyncHasStatusSyncCommit(sha1 string) Predicate

RepoSyncHasStatusSyncCommit creates a Predicate that ensures that the .status.sync.commit field on the passed RepoSync matches sha1.

func RepoSyncHasStatusSyncDirectory

func RepoSyncHasStatusSyncDirectory(dir string) Predicate

RepoSyncHasStatusSyncDirectory creates a Predicate that ensures that the .status.sync.gitStatus.dir field on the passed RepoSync matches the provided dir.

func ResourceVersionEquals

func ResourceVersionEquals(nt *NT, expected string) Predicate

ResourceVersionEquals checks that the object's ResourceVersion matches the specified value.

func ResourceVersionNotEquals

func ResourceVersionNotEquals(nt *NT, unexpected string) Predicate

ResourceVersionNotEquals checks that the object's ResourceVersion does NOT match specified value.

func RootSyncHasStatusSyncCommit

func RootSyncHasStatusSyncCommit(sha1 string) Predicate

RootSyncHasStatusSyncCommit creates a Predicate that ensures that the .status.sync.commit field on the passed RootSync matches sha1.

func RootSyncHasStatusSyncDirectory

func RootSyncHasStatusSyncDirectory(dir string) Predicate

RootSyncHasStatusSyncDirectory creates a Predicate that ensures that the .status.sync.gitStatus.dir field on the passed RootSync matches the provided dir.

func SecretHasKey

func SecretHasKey(key, value string) Predicate

SecretHasKey checks that the secret contains key with value

func SecretMissingKey

func SecretMissingKey(key string) Predicate

SecretMissingKey checks that the secret does not contain key

func StatusEquals

func StatusEquals(nt *NT, expected status.Status) Predicate

StatusEquals checks that the object's computed status matches the specified status.

type RepoType

type RepoType string

RepoType represents the type of the source repository.

const NamespaceRepo RepoType = "namespace"

NamespaceRepo indicates the resources in the repository are namespace-scoped.

const RootRepo RepoType = "root"

RootRepo indicates the resources in the repository are cluster-scoped.

type Repository

type Repository struct {
	// Root is the location on the machine running the test at which the local
	// repository is stored.
	Root string
	// Format is the source format for parsing the repository (hierarchy or
	// unstructured).
	Format filesystem.SourceFormat

	T testing.NTB

	// Type refers to the type of the repository, i.e. if it is a root repo or a namespace repo.
	Type RepoType

	// SafetyNSPath is the path to the safety namespace yaml file.
	SafetyNSPath string

	// SafetyNS is the name of the safety namespace.
	SafetyNSName string

	// RemoteRepoName is the name of the remote repository.
	// It is the same as Name for the testing git-server.
	// For other git providers, it appends a UUID to Name for uniqueness.
	RemoteRepoName string

	// RemoteURL is the remote URL of the repository.
	// It is used to set the url for the remote origin using `git remote add origin <REMOTE_URL>.
	RemoteURL string

	// UpstreamRepoURL is the URL of the seed repo
	UpstreamRepoURL string

	// Scheme used for encoding and decoding objects.
	Scheme *runtime.Scheme
}

Repository is a local git repository with a connection to a repository on the git-server for the test.

We shell out for git commands as the git libraries are difficult to configure ssh for, and git-server requires ssh authentication.

func NewRepository

func NewRepository(nt *NT, repoType RepoType, nn types.NamespacedName, upstream string, sourceFormat filesystem.SourceFormat) *Repository

NewRepository creates a remote repo on the git provider. Locally, it writes the repository to `tmpdir`/repos/`name`.

The repo name is in the format of <NAMESPACE>/<NAME> of RootSync|RepoSync.

func (*Repository) Add

func (g *Repository) Add(path string, obj client.Object)

Add writes a YAML or JSON representation of obj to `path` in the git repository, and `git add`s the file. Does not commit/push.

Overwrites the file if it already exists. Automatically writes YAML or JSON based on the path's extension.

Don't put multiple manifests in the same file unless parsing multi-manifest files is the behavior under test. In that case, use AddFile.

func (*Repository) AddEmptyDir

func (g *Repository) AddEmptyDir(path string)

AddEmptyDir creates an empty dir containing an empty .gitkeep file, so the empty dir will be retained in git.

Use this when creating empty sync directories, otherwise Config Sync will error that the directory doesn't exist.

func (*Repository) AddFile

func (g *Repository) AddFile(path string, bytes []byte)

AddFile writes `bytes` to `file` in the git repository. This function should only be directly used for testing the literal YAML/JSON parsing logic.

Path is relative to the Git repository root. Overwrites `file` if it already exists. Does not commit/push.

func (*Repository) CheckoutBranch

func (g *Repository) CheckoutBranch(branch string)

CheckoutBranch checkouts a branch.

func (*Repository) CommitAndPush

func (g *Repository) CommitAndPush(msg string)

CommitAndPush commits any changes to the git repository, and pushes them to the git server. We don't care about differentiating between committing and pushing for tests.

func (*Repository) CommitAndPushBranch

func (g *Repository) CommitAndPushBranch(msg, branch string)

CommitAndPushBranch commits any changes to the git branch, and pushes them to the git server.

func (*Repository) Copy

func (g *Repository) Copy(sourceDir, destDir string)

Copy copies the file or directory from source to destination. Overwrites the file if it already exists. Does not commit/push.

func (*Repository) CreateBranch

func (g *Repository) CreateBranch(branch string)

CreateBranch creates and checkouts a new branch at once.

func (*Repository) Get

func (g *Repository) Get(path string) client.Object

Get reads, parses, and returns the specified file as an object.

File must have one of these suffixes: .yaml, .yml, .json This is meant to read files written with Add. So it only reads one object per file. If you need to parse multiple objects from one file, use GetFile.

func (*Repository) GetAll

func (g *Repository) GetAll(dirPath string, recursive bool) []client.Object

GetAll reads, parses, and returns all the files in a specified directory as objects.

func (*Repository) GetFile

func (g *Repository) GetFile(path string) []byte

GetFile reads and returns the specified file.

func (*Repository) Git

func (g *Repository) Git(command ...string)

Git wraps shelling out to git, ensuring we're running from the git repository

Fails immediately if any git command fails.

func (*Repository) Hash

func (g *Repository) Hash() string

Hash returns the current hash of the git repository.

Immediately ends the test on error.

func (*Repository) ReInit

func (g *Repository) ReInit(nt *NT, sourceFormat filesystem.SourceFormat)

ReInit re-initializes the repo to the initial state.

func (*Repository) Remove

func (g *Repository) Remove(path string)

Remove deletes `file` from the git repository. If `file` is a directory, deletes the directory. Returns error if the file does not exist. Does not commit/push.

func (*Repository) RenameBranch

func (g *Repository) RenameBranch(current, new string)

RenameBranch renames the current branch with a new one both locally and remotely. The old branch will be deleted from remote.

type Sha1Func

type Sha1Func func(nt *NT, nn types.NamespacedName) (string, error)

Sha1Func is the function type that retrieves the commit sha1.

func DefaultRepoSha1Fn

func DefaultRepoSha1Fn() Sha1Func

DefaultRepoSha1Fn is the default function to retrieve the commit hash of the namespace repo.

type SyncDirPredicatePair

type SyncDirPredicatePair struct {
	Dir       string
	Predicate func(string) Predicate
}

SyncDirPredicatePair is a pair of the sync directory and the predicate.

type WaitForRepoSyncsOption

type WaitForRepoSyncsOption func(*waitForRepoSyncsOptions)

WaitForRepoSyncsOption is an optional parameter for WaitForRepoSyncs.

func RootSyncOnly

func RootSyncOnly() WaitForRepoSyncsOption

RootSyncOnly specifies that only the root-sync repo should be synced.

func WithRootSha1Func

func WithRootSha1Func(fn Sha1Func) WaitForRepoSyncsOption

WithRootSha1Func provides the function to get commit sha1 to WaitForRepoSyncs.

func WithSyncDirectoryMap

func WithSyncDirectoryMap(syncDirectoryMap map[types.NamespacedName]string) WaitForRepoSyncsOption

WithSyncDirectoryMap provides a map of RootSync|RepoSync and the corresponding sync directory. The function is used to get the sync directory based on different RootSync|RepoSync name.

func WithTimeout

func WithTimeout(timeout time.Duration) WaitForRepoSyncsOption

WithTimeout provides the timeout to WaitForRepoSyncs.

type WaitOption

type WaitOption func(wait *waitSpec)

WaitOption is an optional parameter for Wait

func WaitNoFail

func WaitNoFail() WaitOption

WaitNoFail sets failOnError to false so the Wait function only logs the error but not fails the test.

func WaitTimeout

func WaitTimeout(timeout time.Duration) WaitOption

WaitTimeout provides the timeout option to Wait.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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