Documentation ¶
Index ¶
- Constants
- Variables
- func Clean(nt *NT, failOnError FailOnError)
- func CreateNamespaceSecret(nt *NT, ns string)
- func DefaultRootSha1Fn(nt *NT, nn types.NamespacedName) (string, error)
- func DeleteManagedNamespaces(nt *NT)
- func DeletePodByLabel(nt *NT, label, value string, waitForChildren bool)
- func DeleteRemoteRepos(nt *NT)
- func FailIfUnknown(t testing.NTB, scheme *runtime.Scheme, o client.Object)
- func InitGitRepos(nt *NT, repos ...types.NamespacedName) string
- func IsEstablished(o client.Object) error
- func NewOptStruct(testName, tmpDir string, t testing2.NTB, ntOptions ...ntopts.Opt) *ntopts.New
- func NewPodReady(nt *NT, labelName, currentLabel, childLabel string, ...) error
- func NotPendingDeletion(o client.Object) error
- func RemoteNsRepoSha1Fn(nt *NT, nn types.NamespacedName) (string, error)
- func RemoteRootRepoSha1Fn(nt *NT, nn types.NamespacedName) (string, error)
- func RepoSyncClusterRole() *rbacv1.ClusterRole
- func RepoSyncNN(ns, name string) types.NamespacedName
- func RepoSyncObjectV1Alpha1(nn types.NamespacedName, repoURL string) *v1alpha1.RepoSync
- func RepoSyncObjectV1Alpha1FromNonRootRepo(nt *NT, nn types.NamespacedName) *v1alpha1.RepoSync
- func RepoSyncObjectV1Beta1(nn types.NamespacedName, repoURL string, sourceFormat filesystem.SourceFormat) *v1beta1.RepoSync
- func RepoSyncObjectV1Beta1FromNonRootRepo(nt *NT, nn types.NamespacedName) *v1beta1.RepoSync
- func RepoSyncObjectV1Beta1FromOtherRootRepo(nt *NT, nn types.NamespacedName, repoName string) *v1beta1.RepoSync
- func RepoSyncRoleBinding(nn types.NamespacedName) *rbacv1.RoleBinding
- func ResetMonoRepoSpec(nt *NT, sourceFormat filesystem.SourceFormat, policyDir string)
- func RestConfig(t testing.NTB, optsStruct *ntopts.New)
- func Retry(timeout time.Duration, fn func() error) (time.Duration, error)
- func RootSyncNN(name string) types.NamespacedName
- func RootSyncObjectV1Alpha1(name, repoURL string, sourceFormat filesystem.SourceFormat) *v1alpha1.RootSync
- func RootSyncObjectV1Alpha1FromRootRepo(nt *NT, name string) *v1alpha1.RootSync
- func RootSyncObjectV1Beta1(name, repoURL string, sourceFormat filesystem.SourceFormat) *v1beta1.RootSync
- func RootSyncObjectV1Beta1FromOtherRootRepo(nt *NT, syncName, repoName string) *v1beta1.RootSync
- func RootSyncObjectV1Beta1FromRootRepo(nt *NT, name string) *v1beta1.RootSync
- func SetPolicyDir(nt *NT, name, policyDir string)
- func StopWebhook(nt *NT)
- func StructuredNSPath(namespace, resourceName string) string
- func SwitchMode(nt *NT, sourceFormat filesystem.SourceFormat)
- func TestClusterName(t testing.NTB) string
- func TestDir(t testing2.NTB) string
- func Wait(t testing.NTB, opName string, timeout time.Duration, condition func() error, ...)
- func WaitForCRDs(nt *NT, crds []string) error
- func WaitForWebhookReadiness(nt *NT)
- func WaitToTerminate(nt *NT, gvk schema.GroupVersionKind, name, namespace string, ...)
- func WrongTypeErr(got, want interface{}) error
- type FailOnError
- type MetricsSyncOption
- type NT
- func (nt *NT) ApplyGatekeeperTestData(file, crd string) error
- func (nt *NT) Create(obj client.Object, opts ...client.CreateOption) error
- func (nt *NT) DebugLog(args ...interface{})
- func (nt *NT) DebugLogf(format string, args ...interface{})
- func (nt *NT) Delete(obj client.Object, opts ...client.DeleteOption) error
- func (nt *NT) DeleteAllOf(obj client.Object, opts ...client.DeleteAllOfOption) error
- func (nt *NT) ForwardToFreePort(ns, pod, port string) (int, error)
- func (nt *NT) Get(name, namespace string, obj client.Object) error
- func (nt *NT) GetCurrentMetrics(syncOptions ...MetricsSyncOption) (time.Duration, testmetrics.ConfigSyncMetrics)
- func (nt *NT) GitPrivateKeyPath() stringdeprecated
- func (nt *NT) GitRepoPort() intdeprecated
- func (nt *NT) KubeconfigPath() stringdeprecated
- func (nt *NT) Kubectl(args ...string) ([]byte, error)
- func (nt *NT) List(obj client.ObjectList, opts ...client.ListOption) error
- func (nt *NT) MergePatch(obj client.Object, patch string, opts ...client.PatchOption) error
- func (nt *NT) MustKubectl(args ...string) []byte
- func (nt *NT) MustMergePatch(obj client.Object, patch string, opts ...client.PatchOption)
- func (nt *NT) PodLogs(namespace, deployment, container string, previousPodLog bool)
- func (nt *NT) PortForwardOtelCollector()
- func (nt *NT) RenewClient()
- func (nt *NT) SupportV1Beta1CRD() (bool, error)
- func (nt *NT) Update(obj client.Object, opts ...client.UpdateOption) error
- func (nt *NT) Validate(name, namespace string, o client.Object, predicates ...Predicate) error
- func (nt *NT) ValidateErrorMetricsNotFound() error
- func (nt *NT) ValidateGitSyncDepthOverrideCount(count int) error
- func (nt *NT) ValidateMetricNotFound(metricName string) error
- func (nt *NT) ValidateMetrics(syncOption MetricsSyncOption, fn func() error) error
- func (nt *NT) ValidateMultiRepoMetrics(reconciler string, numResources int, gvkMetrics ...testmetrics.GVKMetric) error
- func (nt *NT) ValidateNoSSLVerifyCount(count int) error
- func (nt *NT) ValidateNotFound(name, namespace string, o client.Object) error
- func (nt *NT) ValidateReconcilerErrors(reconciler, component string) error
- func (nt *NT) ValidateResourceOverrideCount(reconciler, containerName, resourceType string, count int) error
- func (nt *NT) ValidateResourceOverrideCountMissingTags(tags []tag.Tag) error
- func (nt *NT) WaitForNamespace(timeout time.Duration, namespace string)
- func (nt *NT) WaitForNamespaces(timeout time.Duration, namespaces ...string)
- func (nt *NT) WaitForRepoImportErrorCode(code string, opts ...WaitOption)
- func (nt *NT) WaitForRepoSourceError(code string, opts ...WaitOption)
- func (nt *NT) WaitForRepoSourceErrorClear(opts ...WaitOption)
- func (nt *NT) WaitForRepoSyncSourceError(ns, rsName, code, message string, opts ...WaitOption)
- func (nt *NT) WaitForRepoSyncStalledError(rsNamespace, rsName, reason, message string)
- func (nt *NT) WaitForRepoSyncSyncError(ns, rsName, code string, message string, opts ...WaitOption)
- func (nt *NT) WaitForRepoSyncs(options ...WaitForRepoSyncsOption)
- func (nt *NT) WaitForRootSyncRenderingError(rsName, code string, message string, opts ...WaitOption)
- func (nt *NT) WaitForRootSyncSourceError(rsName, code string, message string, opts ...WaitOption)
- func (nt *NT) WaitForRootSyncStalledError(rsNamespace, rsName, reason, message string)
- func (nt *NT) WaitForRootSyncSyncError(rsName, code string, message string, ignoreSyncingCondition bool, ...)
- func (nt *NT) WaitForSync(gvk schema.GroupVersionKind, name, namespace string, timeout time.Duration, ...)
- type Predicate
- func AllResourcesAreCurrent() Predicate
- func ClusterConfigHasToken(sha1 string) Predicate
- func DeploymentHasEnvVar(containerName, key, value string) Predicate
- func DeploymentMissingEnvVar(containerName, key string) Predicate
- func HasAllAnnotationKeys(keys ...string) Predicate
- func HasAllNomosMetadata(multiRepo bool) Predicate
- func HasAnnotation(key, value string) Predicate
- func HasAnnotationKey(key string) Predicate
- func HasCorrectResourceRequestsLimits(containerName string, ...) Predicate
- func HasExactlyAnnotationKeys(wantKeys ...string) Predicate
- func HasExactlyImageName(containerName string, expectImageName string) Predicate
- func HasExactlyLabelKeys(wantKeys ...string) Predicate
- func HasLabel(key, value string) Predicate
- func HasStatus() Predicate
- func IsManagedBy(nt *NT, scope declared.Scope, syncName string) Predicate
- func IsNotManaged(nt *NT) Predicate
- func MissingAnnotation(key string) Predicate
- func MissingLabel(key string) Predicate
- func NoConfigSyncMetadata() Predicate
- func NoStatus() Predicate
- func RepoHasStatusSyncLatestToken(sha1 string) Predicate
- func RepoSyncHasStatusSyncCommit(sha1 string) Predicate
- func RepoSyncHasStatusSyncDirectory(dir string) Predicate
- func ResourceVersionEquals(nt *NT, expected string) Predicate
- func ResourceVersionNotEquals(nt *NT, unexpected string) Predicate
- func RootSyncHasStatusSyncCommit(sha1 string) Predicate
- func RootSyncHasStatusSyncDirectory(dir string) Predicate
- func SecretHasKey(key, value string) Predicate
- func SecretMissingKey(key string) Predicate
- func StatusEquals(nt *NT, expected status.Status) Predicate
- type RepoType
- type Repository
- func (g *Repository) Add(path string, obj client.Object)
- func (g *Repository) AddEmptyDir(path string)
- func (g *Repository) AddFile(path string, bytes []byte)
- func (g *Repository) CheckoutBranch(branch string)
- func (g *Repository) CommitAndPush(msg string)
- func (g *Repository) CommitAndPushBranch(msg, branch string)
- func (g *Repository) Copy(sourceDir, destDir string)
- func (g *Repository) CreateBranch(branch string)
- func (g *Repository) Get(path string) client.Object
- func (g *Repository) GetAll(dirPath string, recursive bool) []client.Object
- func (g *Repository) GetFile(path string) []byte
- func (g *Repository) Git(command ...string)
- func (g *Repository) Hash() string
- func (g *Repository) ReInit(nt *NT, sourceFormat filesystem.SourceFormat)
- func (g *Repository) Remove(path string)
- func (g *Repository) RenameBranch(current, new string)
- type Sha1Func
- type SyncDirPredicatePair
- type WaitForRepoSyncsOption
- type WaitOption
Constants ¶
const ( // AcmeDir is the sync directory of the test source repository. AcmeDir = "acme" // Manifests is the folder of the test manifests Manifests = "manifests" )
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" )
const NomosE2E = "nomos-e2e"
NomosE2E is the subdirectory inside the filesystem's temporary directory in which we write test data.
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.
const TestLabelValue = "enabled"
TestLabelValue is the value assigned to the above label.
Variables ¶
var AddTestLabel = core.Label(TestLabel, TestLabelValue)
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.
var DefaultRootReconcilerName = core.RootReconcilerName(configsync.RootSyncName)
DefaultRootReconcilerName is the root-reconciler name of the default RootSync object: "root-sync".
var DefaultRootRepoNamespacedName = RootSyncNN(configsync.RootSyncName)
DefaultRootRepoNamespacedName is the NamespacedName of the default RootSync object.
var ErrFailedPredicate = errors.New("failed predicate")
ErrFailedPredicate indicates the the object on the API server does not match the Predicate.
var ErrWrongType = errors.New("wrong type")
ErrWrongType indicates that the caller passed an object of the incorrect type to the Predicate.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
RootSyncObjectV1Beta1FromOtherRootRepo returns a v1beta1 RootSync object which uses a repo from a specific nt.RootRepo.
func RootSyncObjectV1Beta1FromRootRepo ¶
RootSyncObjectV1Beta1FromRootRepo returns a v1beta1 RootSync object which uses a repo from nt.RootRepos.
func SetPolicyDir ¶
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 ¶
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 ¶
TestClusterName returns the name of the test cluster.
func TestDir ¶
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 ¶
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 ¶
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 NewSharedNT ¶
func NewSharedNT() *NT
NewSharedNT sets up the shared config sync testing environment globally.
func SharedTestEnv ¶
SharedTestEnv connects to a shared test cluster.
func (*NT) ApplyGatekeeperTestData ¶
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 ¶
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 ¶
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 ¶
Delete is identical to Delete defined for client.Client, but without requiring Context.
func (*NT) DeleteAllOf ¶
DeleteAllOf is identical to DeleteAllOf defined for client.Client, but without requiring Context.
func (*NT) ForwardToFreePort ¶
ForwardToFreePort forwards a local port to a port on the pod and returns the local port chosen by kubectl.
func (*NT) Get ¶
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) GitRepoPort
deprecated
func (*NT) KubeconfigPath
deprecated
func (*NT) Kubectl ¶
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 ¶
MergePatch uses the object to construct a merge patch for the fields provided.
func (*NT) MustKubectl ¶
MustKubectl fails the test immediately if the kubectl command fails. On success, returns STDOUT.
func (*NT) MustMergePatch ¶
MustMergePatch is like MergePatch but will call t.Fatal if the patch fails.
func (*NT) PodLogs ¶
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 ¶
SupportV1Beta1CRD checks if v1beta1 CRD is supported in the current testing cluster.
func (*NT) Update ¶
Update is identical to Update defined for client.Client, but without requiring Context.
func (*NT) Validate ¶
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 ¶
ValidateErrorMetricsNotFound validates that no error metrics are emitted from any of the reconcilers.
func (*NT) ValidateGitSyncDepthOverrideCount ¶
ValidateGitSyncDepthOverrideCount validates the `git_sync_depth_override_count` metric.
func (*NT) ValidateMetricNotFound ¶
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 ¶
ValidateNoSSLVerifyCount checks that the `no_ssl_verify_count` metric has the correct value.
func (*NT) ValidateNotFound ¶
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 ¶
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 ¶
ValidateResourceOverrideCountMissingTags checks that the `resource_override_count` metric misses the specific the tags.
func (*NT) WaitForNamespace ¶
WaitForNamespace waits for a namespace to exist and be ready to use
func (*NT) WaitForNamespaces ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DeploymentHasEnvVar check whether the deployment contains environment variable with specified name and value
func DeploymentMissingEnvVar ¶
DeploymentMissingEnvVar check whether the deployment does not contain environment variable with specified name and value
func HasAllAnnotationKeys ¶
HasAllAnnotationKeys returns a predicate that tests if an Object has the specified annotation keys.
func HasAllNomosMetadata ¶
HasAllNomosMetadata ensures that the object contains the expected nomos labels and annotations.
func HasAnnotation ¶
HasAnnotation returns a predicate that tests if an Object has the specified annotation key/value pair.
func HasAnnotationKey ¶
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 ¶
HasExactlyAnnotationKeys ensures the Object has exactly the passed set of annotations, ignoring values.
func HasExactlyImageName ¶
HasExactlyImageName ensures a container has the expected image name
func HasExactlyLabelKeys ¶
HasExactlyLabelKeys ensures the Object has exactly the passed set of labels, ignoring values.
func HasLabel ¶
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 ¶
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 ¶
IsNotManaged checks that the object is NOT managed by configsync. Use differ.ManagedByConfigSync if you just need a boolean without errors.
func MissingAnnotation ¶
MissingAnnotation returns a predicate that tests that an object does not have a specified annotation.
func MissingLabel ¶
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 ¶
RepoHasStatusSyncLatestToken ensures ACM has reported all objects were successfully synced to the repository.
func RepoSyncHasStatusSyncCommit ¶
RepoSyncHasStatusSyncCommit creates a Predicate that ensures that the .status.sync.commit field on the passed RepoSync matches sha1.
func RepoSyncHasStatusSyncDirectory ¶
RepoSyncHasStatusSyncDirectory creates a Predicate that ensures that the .status.sync.gitStatus.dir field on the passed RepoSync matches the provided dir.
func ResourceVersionEquals ¶
ResourceVersionEquals checks that the object's ResourceVersion matches the specified value.
func ResourceVersionNotEquals ¶
ResourceVersionNotEquals checks that the object's ResourceVersion does NOT match specified value.
func RootSyncHasStatusSyncCommit ¶
RootSyncHasStatusSyncCommit creates a Predicate that ensures that the .status.sync.commit field on the passed RootSync matches sha1.
func RootSyncHasStatusSyncDirectory ¶
RootSyncHasStatusSyncDirectory creates a Predicate that ensures that the .status.sync.gitStatus.dir field on the passed RootSync matches the provided dir.
func SecretHasKey ¶
SecretHasKey checks that the secret contains key with value
func SecretMissingKey ¶
SecretMissingKey checks that the secret does not contain key
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 ¶
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.