From 2fdbed226a7a4aa814cd4e2deef85380bb3a93ea Mon Sep 17 00:00:00 2001 From: Pasquale Congiusti Date: Sat, 16 Nov 2024 09:39:45 +0100 Subject: [PATCH] chore: remove dead code Added a routine, make dead-code, to identify code which is never reached internally. Removed all the unused code and moved code used for testing --- addons/addons_test.go | 18 +- addons/keda/client_test.go | 299 ++++++++++++++++++ addons/keda/duck/v1alpha1/register.go | 5 - addons/keda/keda_test.go | 3 +- addons/master/client_test.go | 299 ++++++++++++++++++ addons/master/master_test.go | 7 +- addons/vault/aws/aws_secrets_manager_test.go | 3 +- addons/vault/aws/client_test.go | 299 ++++++++++++++++++ addons/vault/azure/azure_key_vault_test.go | 3 +- addons/vault/azure/client_test.go | 299 ++++++++++++++++++ addons/vault/hashicorp/client_test.go | 299 ++++++++++++++++++ .../vault/hashicorp/hashicorp_vault_test.go | 3 +- e2e/advanced/maven_http_proxy_test.go | 4 +- e2e/common/traits/route_test.go | 4 +- e2e/install/olm/olm_install_test.go | 16 +- e2e/support/test_nexus_hooks.go | 68 ---- e2e/support/test_staging_hooks.go | 54 ---- e2e/support/test_support.go | 14 +- e2e/support/util/temp_file.go | 75 ++++- pkg/apis/camel/v1/build_types_support.go | 9 - .../v1/integrationprofile_types_support.go | 10 - pkg/apis/duck/strimzi/v1beta2/register.go | 5 - pkg/base/root.go | 63 ---- .../builder_support_test.go} | 12 +- pkg/builder/builder_test.go | 19 +- pkg/builder/image_test.go | 7 +- pkg/builder/project_test.go | 10 +- pkg/builder/quarkus_test.go | 8 +- pkg/cmd/bind_test.go | 28 +- pkg/cmd/builder_test.go | 9 +- .../test/cmd.go => cmd/cmd_support_test.go} | 2 +- pkg/cmd/config_test.go | 25 +- pkg/cmd/debug_test.go | 6 +- pkg/cmd/delete_test.go | 7 +- pkg/cmd/install_test.go | 91 +++--- pkg/cmd/kamelet_add_repo_test.go | 7 +- pkg/cmd/kamelet_remove_repo_test.go | 7 +- pkg/cmd/kit_create_test.go | 19 +- pkg/cmd/log_test.go | 4 +- pkg/cmd/operator_test.go | 11 +- pkg/cmd/promote_test.go | 28 +- pkg/cmd/rebuild_test.go | 7 +- pkg/cmd/root_test.go | 14 +- pkg/cmd/run_test.go | 98 +++--- pkg/cmd/source/content.go | 60 ---- pkg/cmd/source/content_test.go | 74 ----- pkg/cmd/uninstall_test.go | 9 +- pkg/cmd/version_test.go | 16 +- pkg/controller/build/build_monitor_test.go | 10 +- pkg/controller/build/build_pod_test.go | 4 +- pkg/controller/integration/build_kit_test.go | 20 +- pkg/controller/integration/initialize_test.go | 10 +- pkg/controller/integration/kits_test.go | 10 +- pkg/controller/integration/monitor.go | 14 +- pkg/controller/integration/monitor_cronjob.go | 4 - .../integration/monitor_deployment.go | 4 - pkg/controller/integration/monitor_knative.go | 4 - .../integration/monitor_synthetic_test.go | 14 +- pkg/controller/integration/monitor_test.go | 44 ++- .../integrationplatform/create_test.go | 16 +- .../integrationplatform/initialize_test.go | 12 +- .../integrationplatform/kamelets_test.go | 4 +- .../integrationplatform/monitor_test.go | 16 +- pkg/controller/pipe/initialize_test.go | 18 +- pkg/controller/pipe/integration_test.go | 20 +- pkg/controller/pipe/monitor_test.go | 28 +- pkg/install/common.go | 5 - pkg/{util/test => internal}/client.go | 2 +- pkg/platform/defaults_test.go | 12 +- pkg/platform/profile_test.go | 12 +- pkg/platform/resources.go | 52 --- pkg/resources/resources_support.go | 8 - pkg/trait/builder_test.go | 4 +- pkg/trait/camel_test.go | 4 +- pkg/trait/container_probes_test.go | 4 +- pkg/trait/container_test.go | 22 +- pkg/trait/cron_test.go | 34 +- pkg/trait/deployment_test.go | 6 +- pkg/trait/environment_test.go | 4 +- pkg/trait/gc_test.go | 24 +- pkg/trait/health_test.go | 4 +- pkg/trait/istio_test.go | 4 +- pkg/trait/jvm_test.go | 4 +- pkg/trait/kamelets_test.go | 4 +- pkg/trait/knative_service_test.go | 32 +- pkg/trait/knative_test.go | 52 +-- pkg/trait/logging_test.go | 4 +- pkg/trait/mount_test.go | 8 +- pkg/trait/openapi_test.go | 40 ++- pkg/trait/platform_test.go | 8 +- pkg/trait/pull_secret_test.go | 4 +- pkg/trait/quarkus_test.go | 4 +- pkg/trait/route_test.go | 4 +- pkg/trait/security_context_test.go | 8 +- pkg/trait/service_binding_test.go | 4 +- pkg/trait/service_test.go | 20 +- pkg/trait/trait_catalog_test.go | 4 +- pkg/trait/trait_configure_test.go | 18 -- ...{test_support.go => trait_support_test.go} | 2 +- pkg/trait/trait_test.go | 12 +- pkg/trait/trait_types_test.go | 6 +- pkg/trait/util.go | 14 - pkg/trait/util_test.go | 35 +- ...est_support.go => binding_support_test.go} | 0 pkg/util/bindings/bindings_test.go | 5 +- pkg/util/bindings/catalog_test.go | 6 +- pkg/util/bindings/kamelet.go | 10 - pkg/util/bindings/kamelet_test.go | 8 +- pkg/util/bindings/knative_ref.go | 11 - pkg/util/bindings/knative_ref_test.go | 12 +- pkg/util/bindings/strimzi_test.go | 4 +- pkg/util/camel/camel_runtime_test.go | 4 +- pkg/util/camel/catalog_test.go | 18 ++ pkg/util/defaults/defaults_support.go | 9 - pkg/util/defaults/defaults_test.go | 8 +- pkg/util/docker/docker.go | 174 ---------- pkg/util/docker/docker_base.go | 261 --------------- pkg/util/docker/docker_base_test.go | 96 ------ pkg/util/docker/docker_test.go | 145 --------- pkg/util/envvar/envvar.go | 12 - pkg/util/jib/configuration_test.go | 4 +- pkg/util/kubernetes/factory.go | 32 -- pkg/util/kubernetes/loader.go | 16 - pkg/util/log/log.go | 5 - pkg/util/registry/registry_test.go | 4 +- pkg/util/resource/config.go | 15 - pkg/util/source/kamelet.go | 11 - ...test_support.go => source_support_test.go} | 0 pkg/util/test/assertions.go | 58 ---- pkg/util/test/catalog_test.go | 44 --- pkg/util/util.go | 125 -------- pkg/util/util_test.go | 35 +- script/Makefile | 6 + 133 files changed, 2238 insertions(+), 2077 deletions(-) create mode 100644 addons/keda/client_test.go create mode 100644 addons/master/client_test.go create mode 100644 addons/vault/aws/client_test.go create mode 100644 addons/vault/azure/client_test.go create mode 100644 addons/vault/hashicorp/client_test.go delete mode 100644 e2e/support/test_nexus_hooks.go delete mode 100644 e2e/support/test_staging_hooks.go delete mode 100644 pkg/base/root.go rename pkg/{util/cancellable/cancellable.go => builder/builder_support_test.go} (80%) rename pkg/{util/test/cmd.go => cmd/cmd_support_test.go} (99%) rename pkg/{util/test => internal}/client.go (99%) delete mode 100644 pkg/platform/resources.go rename pkg/trait/{test_support.go => trait_support_test.go} (98%) rename pkg/util/bindings/{test_support.go => binding_support_test.go} (100%) delete mode 100644 pkg/util/docker/docker.go delete mode 100644 pkg/util/docker/docker_base.go delete mode 100644 pkg/util/docker/docker_base_test.go delete mode 100644 pkg/util/docker/docker_test.go rename pkg/util/source/{test_support.go => source_support_test.go} (100%) delete mode 100644 pkg/util/test/assertions.go delete mode 100644 pkg/util/test/catalog_test.go diff --git a/addons/addons_test.go b/addons/addons_test.go index dc5fa92efc..9ae5dc165c 100644 --- a/addons/addons_test.go +++ b/addons/addons_test.go @@ -18,6 +18,7 @@ limitations under the License. package addons import ( + "encoding/json" "testing" "github.com/apache/camel-k/v2/addons/master" @@ -35,13 +36,13 @@ func TestTraitConfiguration(t *testing.T) { Profile: v1.TraitProfileKubernetes, Traits: v1.Traits{ Addons: map[string]v1.AddonTrait{ - "master": trait.ToAddonTrait(t, map[string]interface{}{ + "master": toAddonTrait(t, map[string]interface{}{ "enabled": true, "resourceName": "test-lock", "labelKey": "test-label", "labelValue": "test-value", }), - "telemetry": trait.ToAddonTrait(t, map[string]interface{}{ + "telemetry": toAddonTrait(t, map[string]interface{}{ "enabled": true, }), }, @@ -61,3 +62,16 @@ func TestTraitConfiguration(t *testing.T) { assert.Equal(t, "test-value", *master.LabelValue) } + +func toAddonTrait(t *testing.T, config map[string]interface{}) v1.AddonTrait { + t.Helper() + + data, err := json.Marshal(config) + require.NoError(t, err) + + var addon v1.AddonTrait + err = json.Unmarshal(data, &addon) + require.NoError(t, err) + + return addon +} diff --git a/addons/keda/client_test.go b/addons/keda/client_test.go new file mode 100644 index 0000000000..1f9c28614a --- /dev/null +++ b/addons/keda/client_test.go @@ -0,0 +1,299 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// IMPORTANT: this is a clone of pkg/internal. As the addons will be moved into pkg, we are using this utility here temporarily only! + +package keda + +import ( + "context" + "fmt" + "strings" + + "github.com/apache/camel-k/v2/pkg/apis" + v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/client" + fakecamelclientset "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/fake" + camelv1 "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/typed/camel/v1" + "github.com/apache/camel-k/v2/pkg/util" + autoscalingv1 "k8s.io/api/autoscaling/v1" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" + "k8s.io/client-go/kubernetes" + fakeclientset "k8s.io/client-go/kubernetes/fake" + clientscheme "k8s.io/client-go/kubernetes/scheme" + authorizationv1 "k8s.io/client-go/kubernetes/typed/authorization/v1" + "k8s.io/client-go/rest" + "k8s.io/client-go/scale" + fakescale "k8s.io/client-go/scale/fake" + "k8s.io/client-go/testing" + controller "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// newFakeClient ---. +func newFakeClient(initObjs ...runtime.Object) (client.Client, error) { + scheme := clientscheme.Scheme + + // Setup Scheme for all resources + if err := apis.AddToScheme(scheme); err != nil { + return nil, err + } + + c := fake. + NewClientBuilder(). + WithScheme(scheme). + WithIndex( + &corev1.Pod{}, + "status.phase", + func(obj controller.Object) []string { + pod, _ := obj.(*corev1.Pod) + return []string{string(pod.Status.Phase)} + }, + ). + WithRuntimeObjects(initObjs...). + WithStatusSubresource(&v1.IntegrationKit{}). + Build() + + camelClientset := fakecamelclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return strings.Contains(gvk.Group, "camel") + })...) + clientset := fakeclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return !strings.Contains(gvk.Group, "camel") && !strings.Contains(gvk.Group, "knative") + })...) + replicasCount := make(map[string]int32) + fakescaleclient := fakescale.FakeScaleClient{} + fakescaleclient.AddReactor("update", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.UpdateAction) + + //nolint:forcetypeassert + obj := action.GetObject().(*autoscalingv1.Scale) + + replicas := obj.Spec.Replicas + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), obj.GetName()) + replicasCount[key] = replicas + return true, &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: obj.Name, + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicas, + }, + }, nil + }) + fakescaleclient.AddReactor("get", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.GetAction) + + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), action.GetName()) + obj := &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: action.GetName(), + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicasCount[key], + }, + } + return true, obj, nil + }) + + return &FakeClient{ + Client: c, + Interface: clientset, + camel: camelClientset, + scales: &fakescaleclient, + enabledKnativeServing: true, + enabledKnativeEventing: true, + }, nil +} + +func filterObjects(scheme *runtime.Scheme, input []runtime.Object, filter func(gvk schema.GroupVersionKind) bool) []runtime.Object { + var res []runtime.Object + for _, obj := range input { + kinds, _, _ := scheme.ObjectKinds(obj) + for _, k := range kinds { + if filter(k) { + res = append(res, obj) + break + } + } + } + return res +} + +// FakeClient ---. +type FakeClient struct { + controller.Client + kubernetes.Interface + camel *fakecamelclientset.Clientset + scales *fakescale.FakeScaleClient + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (c *FakeClient) Intercept(intercept *interceptor.Funcs) { + //nolint:forcetypeassert + cw := c.Client.(controller.WithWatch) + c.Client = interceptor.NewClient(cw, *intercept) +} + +func (c *FakeClient) AddReactor(verb, resource string, reaction testing.ReactionFunc) { + c.camel.AddReactor(verb, resource, reaction) +} + +func (c *FakeClient) CamelV1() camelv1.CamelV1Interface { + return c.camel.CamelV1() +} + +// GetScheme ---. +func (c *FakeClient) GetScheme() *runtime.Scheme { + return clientscheme.Scheme +} + +func (c *FakeClient) GetConfig() *rest.Config { + return &rest.Config{} +} + +func (c *FakeClient) GetCurrentNamespace(kubeConfig string) (string, error) { + return "", nil +} + +// Patch mimicks patch for server-side apply and simply creates the obj. +func (c *FakeClient) Patch(ctx context.Context, obj controller.Object, patch controller.Patch, opts ...controller.PatchOption) error { + if err := c.Create(ctx, obj); err != nil { + // Create fails if object already exists. Try to update it. + return c.Update(ctx, obj) + } + return nil +} + +func (c *FakeClient) DisableAPIGroupDiscovery(group string) { + c.disabledGroups = append(c.disabledGroups, group) +} + +func (c *FakeClient) EnableOpenshiftDiscovery() { + c.enabledOpenshift = true +} + +func (c *FakeClient) DisableKnativeServing() { + c.enabledKnativeServing = false +} + +func (c *FakeClient) DisableKnativeEventing() { + c.enabledKnativeEventing = false +} + +func (c *FakeClient) AuthorizationV1() authorizationv1.AuthorizationV1Interface { + return &FakeAuthorization{ + AuthorizationV1Interface: c.Interface.AuthorizationV1(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + } +} + +func (c *FakeClient) Discovery() discovery.DiscoveryInterface { + return &FakeDiscovery{ + DiscoveryInterface: c.Interface.Discovery(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + enabledKnativeServing: c.enabledKnativeServing, + enabledKnativeEventing: c.enabledKnativeEventing, + } +} + +func (c *FakeClient) ServerOrClientSideApplier() client.ServerOrClientSideApplier { + return client.ServerOrClientSideApplier{ + Client: c, + } +} + +func (c *FakeClient) ScalesClient() (scale.ScalesGetter, error) { + return c.scales, nil +} + +type FakeAuthorization struct { + authorizationv1.AuthorizationV1Interface + disabledGroups []string + enabledOpenshift bool +} + +func (f *FakeAuthorization) SelfSubjectRulesReviews() authorizationv1.SelfSubjectRulesReviewInterface { + return f.AuthorizationV1Interface.SelfSubjectRulesReviews() +} + +type FakeDiscovery struct { + discovery.DiscoveryInterface + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (f *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) { + // Normalize the fake discovery to behave like the real implementation when checking for openshift + if groupVersion == "image.openshift.io/v1" { + if f.enabledOpenshift { + return &metav1.APIResourceList{ + GroupVersion: "image.openshift.io/v1", + }, nil + } else { + return nil, k8serrors.NewNotFound(schema.GroupResource{ + Group: "image.openshift.io", + }, "") + } + } + + // used to verify if Knative Serving is installed + if f.enabledKnativeServing { + if groupVersion == "serving.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "serving.knative.dev/v1", + }, nil + } + } + + // used to verify if Knative Eventing is installed + if f.enabledKnativeEventing { + if groupVersion == "eventing.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "eventing.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1beta1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1beta1", + }, nil + } + } + + return f.DiscoveryInterface.ServerResourcesForGroupVersion(groupVersion) +} diff --git a/addons/keda/duck/v1alpha1/register.go b/addons/keda/duck/v1alpha1/register.go index 8ed07911f3..666397b32c 100644 --- a/addons/keda/duck/v1alpha1/register.go +++ b/addons/keda/duck/v1alpha1/register.go @@ -39,11 +39,6 @@ var ( AddToScheme = SchemeBuilder.AddToScheme ) -// Resource takes an unqualified resource and returns a Group qualified GroupResource. -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, diff --git a/addons/keda/keda_test.go b/addons/keda/keda_test.go index 4b4be7d7e5..aecc4d6116 100644 --- a/addons/keda/keda_test.go +++ b/addons/keda/keda_test.go @@ -29,7 +29,6 @@ import ( "github.com/apache/camel-k/v2/pkg/trait" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -449,7 +448,7 @@ func getSecret(e *trait.Environment) *corev1.Secret { } func createBasicTestEnvironment(resources ...runtime.Object) *trait.Environment { - fakeClient, err := test.NewFakeClient(resources...) + fakeClient, err := newFakeClient(resources...) if err != nil { panic(fmt.Errorf("could not create fake client: %w", err)) } diff --git a/addons/master/client_test.go b/addons/master/client_test.go new file mode 100644 index 0000000000..1c2aaef57f --- /dev/null +++ b/addons/master/client_test.go @@ -0,0 +1,299 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// IMPORTANT: this is a clone of pkg/internal. As the addons will be moved into pkg, we are using this utility here temporarily only! + +package master + +import ( + "context" + "fmt" + "strings" + + "github.com/apache/camel-k/v2/pkg/apis" + v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/client" + fakecamelclientset "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/fake" + camelv1 "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/typed/camel/v1" + "github.com/apache/camel-k/v2/pkg/util" + autoscalingv1 "k8s.io/api/autoscaling/v1" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" + "k8s.io/client-go/kubernetes" + fakeclientset "k8s.io/client-go/kubernetes/fake" + clientscheme "k8s.io/client-go/kubernetes/scheme" + authorizationv1 "k8s.io/client-go/kubernetes/typed/authorization/v1" + "k8s.io/client-go/rest" + "k8s.io/client-go/scale" + fakescale "k8s.io/client-go/scale/fake" + "k8s.io/client-go/testing" + controller "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// newFakeClient ---. +func newFakeClient(initObjs ...runtime.Object) (client.Client, error) { + scheme := clientscheme.Scheme + + // Setup Scheme for all resources + if err := apis.AddToScheme(scheme); err != nil { + return nil, err + } + + c := fake. + NewClientBuilder(). + WithScheme(scheme). + WithIndex( + &corev1.Pod{}, + "status.phase", + func(obj controller.Object) []string { + pod, _ := obj.(*corev1.Pod) + return []string{string(pod.Status.Phase)} + }, + ). + WithRuntimeObjects(initObjs...). + WithStatusSubresource(&v1.IntegrationKit{}). + Build() + + camelClientset := fakecamelclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return strings.Contains(gvk.Group, "camel") + })...) + clientset := fakeclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return !strings.Contains(gvk.Group, "camel") && !strings.Contains(gvk.Group, "knative") + })...) + replicasCount := make(map[string]int32) + fakescaleclient := fakescale.FakeScaleClient{} + fakescaleclient.AddReactor("update", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.UpdateAction) + + //nolint:forcetypeassert + obj := action.GetObject().(*autoscalingv1.Scale) + + replicas := obj.Spec.Replicas + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), obj.GetName()) + replicasCount[key] = replicas + return true, &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: obj.Name, + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicas, + }, + }, nil + }) + fakescaleclient.AddReactor("get", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.GetAction) + + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), action.GetName()) + obj := &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: action.GetName(), + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicasCount[key], + }, + } + return true, obj, nil + }) + + return &FakeClient{ + Client: c, + Interface: clientset, + camel: camelClientset, + scales: &fakescaleclient, + enabledKnativeServing: true, + enabledKnativeEventing: true, + }, nil +} + +func filterObjects(scheme *runtime.Scheme, input []runtime.Object, filter func(gvk schema.GroupVersionKind) bool) []runtime.Object { + var res []runtime.Object + for _, obj := range input { + kinds, _, _ := scheme.ObjectKinds(obj) + for _, k := range kinds { + if filter(k) { + res = append(res, obj) + break + } + } + } + return res +} + +// FakeClient ---. +type FakeClient struct { + controller.Client + kubernetes.Interface + camel *fakecamelclientset.Clientset + scales *fakescale.FakeScaleClient + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (c *FakeClient) Intercept(intercept *interceptor.Funcs) { + //nolint:forcetypeassert + cw := c.Client.(controller.WithWatch) + c.Client = interceptor.NewClient(cw, *intercept) +} + +func (c *FakeClient) AddReactor(verb, resource string, reaction testing.ReactionFunc) { + c.camel.AddReactor(verb, resource, reaction) +} + +func (c *FakeClient) CamelV1() camelv1.CamelV1Interface { + return c.camel.CamelV1() +} + +// GetScheme ---. +func (c *FakeClient) GetScheme() *runtime.Scheme { + return clientscheme.Scheme +} + +func (c *FakeClient) GetConfig() *rest.Config { + return &rest.Config{} +} + +func (c *FakeClient) GetCurrentNamespace(kubeConfig string) (string, error) { + return "", nil +} + +// Patch mimicks patch for server-side apply and simply creates the obj. +func (c *FakeClient) Patch(ctx context.Context, obj controller.Object, patch controller.Patch, opts ...controller.PatchOption) error { + if err := c.Create(ctx, obj); err != nil { + // Create fails if object already exists. Try to update it. + return c.Update(ctx, obj) + } + return nil +} + +func (c *FakeClient) DisableAPIGroupDiscovery(group string) { + c.disabledGroups = append(c.disabledGroups, group) +} + +func (c *FakeClient) EnableOpenshiftDiscovery() { + c.enabledOpenshift = true +} + +func (c *FakeClient) DisableKnativeServing() { + c.enabledKnativeServing = false +} + +func (c *FakeClient) DisableKnativeEventing() { + c.enabledKnativeEventing = false +} + +func (c *FakeClient) AuthorizationV1() authorizationv1.AuthorizationV1Interface { + return &FakeAuthorization{ + AuthorizationV1Interface: c.Interface.AuthorizationV1(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + } +} + +func (c *FakeClient) Discovery() discovery.DiscoveryInterface { + return &FakeDiscovery{ + DiscoveryInterface: c.Interface.Discovery(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + enabledKnativeServing: c.enabledKnativeServing, + enabledKnativeEventing: c.enabledKnativeEventing, + } +} + +func (c *FakeClient) ServerOrClientSideApplier() client.ServerOrClientSideApplier { + return client.ServerOrClientSideApplier{ + Client: c, + } +} + +func (c *FakeClient) ScalesClient() (scale.ScalesGetter, error) { + return c.scales, nil +} + +type FakeAuthorization struct { + authorizationv1.AuthorizationV1Interface + disabledGroups []string + enabledOpenshift bool +} + +func (f *FakeAuthorization) SelfSubjectRulesReviews() authorizationv1.SelfSubjectRulesReviewInterface { + return f.AuthorizationV1Interface.SelfSubjectRulesReviews() +} + +type FakeDiscovery struct { + discovery.DiscoveryInterface + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (f *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) { + // Normalize the fake discovery to behave like the real implementation when checking for openshift + if groupVersion == "image.openshift.io/v1" { + if f.enabledOpenshift { + return &metav1.APIResourceList{ + GroupVersion: "image.openshift.io/v1", + }, nil + } else { + return nil, k8serrors.NewNotFound(schema.GroupResource{ + Group: "image.openshift.io", + }, "") + } + } + + // used to verify if Knative Serving is installed + if f.enabledKnativeServing { + if groupVersion == "serving.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "serving.knative.dev/v1", + }, nil + } + } + + // used to verify if Knative Eventing is installed + if f.enabledKnativeEventing { + if groupVersion == "eventing.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "eventing.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1beta1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1beta1", + }, nil + } + } + + return f.DiscoveryInterface.ServerResourcesForGroupVersion(groupVersion) +} diff --git a/addons/master/master_test.go b/addons/master/master_test.go index 0754331b8f..6e0e028d35 100644 --- a/addons/master/master_test.go +++ b/addons/master/master_test.go @@ -25,7 +25,6 @@ import ( "github.com/apache/camel-k/v2/pkg/trait" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -37,7 +36,7 @@ func TestMasterOn(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, err := test.NewFakeClient() + client, err := newFakeClient() require.NoError(t, err) traitCatalog := trait.NewCatalog(nil) @@ -128,7 +127,7 @@ func TestMasterOff(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, err := test.NewFakeClient() + client, err := newFakeClient() require.NoError(t, err) traitCatalog := trait.NewCatalog(nil) @@ -191,7 +190,7 @@ func TestMasterAuto(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, err := test.NewFakeClient() + client, err := newFakeClient() require.NoError(t, err) traitCatalog := trait.NewCatalog(nil) diff --git a/addons/vault/aws/aws_secrets_manager_test.go b/addons/vault/aws/aws_secrets_manager_test.go index aecfd83588..18fb607fa8 100644 --- a/addons/vault/aws/aws_secrets_manager_test.go +++ b/addons/vault/aws/aws_secrets_manager_test.go @@ -22,7 +22,6 @@ import ( "github.com/apache/camel-k/v2/pkg/util/boolean" - "github.com/apache/camel-k/v2/pkg/util/test" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -168,7 +167,7 @@ func createEnvironment(t *testing.T, catalogGen func() (*camel.RuntimeCatalog, e t.Helper() catalog, err := catalogGen() - client, _ := test.NewFakeClient(objects...) + client, _ := newFakeClient(objects...) require.NoError(t, err) e := trait.Environment{ diff --git a/addons/vault/aws/client_test.go b/addons/vault/aws/client_test.go new file mode 100644 index 0000000000..b2c77c7d52 --- /dev/null +++ b/addons/vault/aws/client_test.go @@ -0,0 +1,299 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// IMPORTANT: this is a clone of pkg/internal. As the addons will be moved into pkg, we are using this utility here temporarily only! + +package aws + +import ( + "context" + "fmt" + "strings" + + "github.com/apache/camel-k/v2/pkg/apis" + v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/client" + fakecamelclientset "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/fake" + camelv1 "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/typed/camel/v1" + "github.com/apache/camel-k/v2/pkg/util" + autoscalingv1 "k8s.io/api/autoscaling/v1" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" + "k8s.io/client-go/kubernetes" + fakeclientset "k8s.io/client-go/kubernetes/fake" + clientscheme "k8s.io/client-go/kubernetes/scheme" + authorizationv1 "k8s.io/client-go/kubernetes/typed/authorization/v1" + "k8s.io/client-go/rest" + "k8s.io/client-go/scale" + fakescale "k8s.io/client-go/scale/fake" + "k8s.io/client-go/testing" + controller "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// newFakeClient ---. +func newFakeClient(initObjs ...runtime.Object) (client.Client, error) { + scheme := clientscheme.Scheme + + // Setup Scheme for all resources + if err := apis.AddToScheme(scheme); err != nil { + return nil, err + } + + c := fake. + NewClientBuilder(). + WithScheme(scheme). + WithIndex( + &corev1.Pod{}, + "status.phase", + func(obj controller.Object) []string { + pod, _ := obj.(*corev1.Pod) + return []string{string(pod.Status.Phase)} + }, + ). + WithRuntimeObjects(initObjs...). + WithStatusSubresource(&v1.IntegrationKit{}). + Build() + + camelClientset := fakecamelclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return strings.Contains(gvk.Group, "camel") + })...) + clientset := fakeclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return !strings.Contains(gvk.Group, "camel") && !strings.Contains(gvk.Group, "knative") + })...) + replicasCount := make(map[string]int32) + fakescaleclient := fakescale.FakeScaleClient{} + fakescaleclient.AddReactor("update", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.UpdateAction) + + //nolint:forcetypeassert + obj := action.GetObject().(*autoscalingv1.Scale) + + replicas := obj.Spec.Replicas + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), obj.GetName()) + replicasCount[key] = replicas + return true, &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: obj.Name, + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicas, + }, + }, nil + }) + fakescaleclient.AddReactor("get", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.GetAction) + + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), action.GetName()) + obj := &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: action.GetName(), + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicasCount[key], + }, + } + return true, obj, nil + }) + + return &FakeClient{ + Client: c, + Interface: clientset, + camel: camelClientset, + scales: &fakescaleclient, + enabledKnativeServing: true, + enabledKnativeEventing: true, + }, nil +} + +func filterObjects(scheme *runtime.Scheme, input []runtime.Object, filter func(gvk schema.GroupVersionKind) bool) []runtime.Object { + var res []runtime.Object + for _, obj := range input { + kinds, _, _ := scheme.ObjectKinds(obj) + for _, k := range kinds { + if filter(k) { + res = append(res, obj) + break + } + } + } + return res +} + +// FakeClient ---. +type FakeClient struct { + controller.Client + kubernetes.Interface + camel *fakecamelclientset.Clientset + scales *fakescale.FakeScaleClient + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (c *FakeClient) Intercept(intercept *interceptor.Funcs) { + //nolint:forcetypeassert + cw := c.Client.(controller.WithWatch) + c.Client = interceptor.NewClient(cw, *intercept) +} + +func (c *FakeClient) AddReactor(verb, resource string, reaction testing.ReactionFunc) { + c.camel.AddReactor(verb, resource, reaction) +} + +func (c *FakeClient) CamelV1() camelv1.CamelV1Interface { + return c.camel.CamelV1() +} + +// GetScheme ---. +func (c *FakeClient) GetScheme() *runtime.Scheme { + return clientscheme.Scheme +} + +func (c *FakeClient) GetConfig() *rest.Config { + return &rest.Config{} +} + +func (c *FakeClient) GetCurrentNamespace(kubeConfig string) (string, error) { + return "", nil +} + +// Patch mimicks patch for server-side apply and simply creates the obj. +func (c *FakeClient) Patch(ctx context.Context, obj controller.Object, patch controller.Patch, opts ...controller.PatchOption) error { + if err := c.Create(ctx, obj); err != nil { + // Create fails if object already exists. Try to update it. + return c.Update(ctx, obj) + } + return nil +} + +func (c *FakeClient) DisableAPIGroupDiscovery(group string) { + c.disabledGroups = append(c.disabledGroups, group) +} + +func (c *FakeClient) EnableOpenshiftDiscovery() { + c.enabledOpenshift = true +} + +func (c *FakeClient) DisableKnativeServing() { + c.enabledKnativeServing = false +} + +func (c *FakeClient) DisableKnativeEventing() { + c.enabledKnativeEventing = false +} + +func (c *FakeClient) AuthorizationV1() authorizationv1.AuthorizationV1Interface { + return &FakeAuthorization{ + AuthorizationV1Interface: c.Interface.AuthorizationV1(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + } +} + +func (c *FakeClient) Discovery() discovery.DiscoveryInterface { + return &FakeDiscovery{ + DiscoveryInterface: c.Interface.Discovery(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + enabledKnativeServing: c.enabledKnativeServing, + enabledKnativeEventing: c.enabledKnativeEventing, + } +} + +func (c *FakeClient) ServerOrClientSideApplier() client.ServerOrClientSideApplier { + return client.ServerOrClientSideApplier{ + Client: c, + } +} + +func (c *FakeClient) ScalesClient() (scale.ScalesGetter, error) { + return c.scales, nil +} + +type FakeAuthorization struct { + authorizationv1.AuthorizationV1Interface + disabledGroups []string + enabledOpenshift bool +} + +func (f *FakeAuthorization) SelfSubjectRulesReviews() authorizationv1.SelfSubjectRulesReviewInterface { + return f.AuthorizationV1Interface.SelfSubjectRulesReviews() +} + +type FakeDiscovery struct { + discovery.DiscoveryInterface + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (f *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) { + // Normalize the fake discovery to behave like the real implementation when checking for openshift + if groupVersion == "image.openshift.io/v1" { + if f.enabledOpenshift { + return &metav1.APIResourceList{ + GroupVersion: "image.openshift.io/v1", + }, nil + } else { + return nil, k8serrors.NewNotFound(schema.GroupResource{ + Group: "image.openshift.io", + }, "") + } + } + + // used to verify if Knative Serving is installed + if f.enabledKnativeServing { + if groupVersion == "serving.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "serving.knative.dev/v1", + }, nil + } + } + + // used to verify if Knative Eventing is installed + if f.enabledKnativeEventing { + if groupVersion == "eventing.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "eventing.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1beta1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1beta1", + }, nil + } + } + + return f.DiscoveryInterface.ServerResourcesForGroupVersion(groupVersion) +} diff --git a/addons/vault/azure/azure_key_vault_test.go b/addons/vault/azure/azure_key_vault_test.go index 4c3252ed25..f4ddfc25f2 100644 --- a/addons/vault/azure/azure_key_vault_test.go +++ b/addons/vault/azure/azure_key_vault_test.go @@ -20,7 +20,6 @@ package azure import ( "testing" - "github.com/apache/camel-k/v2/pkg/util/test" corev1 "k8s.io/api/core/v1" "k8s.io/utils/ptr" @@ -205,7 +204,7 @@ func createEnvironment(t *testing.T, catalogGen func() (*camel.RuntimeCatalog, e t.Helper() catalog, err := catalogGen() - client, _ := test.NewFakeClient(objects...) + client, _ := newFakeClient(objects...) require.NoError(t, err) e := trait.Environment{ diff --git a/addons/vault/azure/client_test.go b/addons/vault/azure/client_test.go new file mode 100644 index 0000000000..c7fc29c290 --- /dev/null +++ b/addons/vault/azure/client_test.go @@ -0,0 +1,299 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// IMPORTANT: this is a clone of pkg/internal. As the addons will be moved into pkg, we are using this utility here temporarily only! + +package azure + +import ( + "context" + "fmt" + "strings" + + "github.com/apache/camel-k/v2/pkg/apis" + v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/client" + fakecamelclientset "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/fake" + camelv1 "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/typed/camel/v1" + "github.com/apache/camel-k/v2/pkg/util" + autoscalingv1 "k8s.io/api/autoscaling/v1" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" + "k8s.io/client-go/kubernetes" + fakeclientset "k8s.io/client-go/kubernetes/fake" + clientscheme "k8s.io/client-go/kubernetes/scheme" + authorizationv1 "k8s.io/client-go/kubernetes/typed/authorization/v1" + "k8s.io/client-go/rest" + "k8s.io/client-go/scale" + fakescale "k8s.io/client-go/scale/fake" + "k8s.io/client-go/testing" + controller "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// newFakeClient ---. +func newFakeClient(initObjs ...runtime.Object) (client.Client, error) { + scheme := clientscheme.Scheme + + // Setup Scheme for all resources + if err := apis.AddToScheme(scheme); err != nil { + return nil, err + } + + c := fake. + NewClientBuilder(). + WithScheme(scheme). + WithIndex( + &corev1.Pod{}, + "status.phase", + func(obj controller.Object) []string { + pod, _ := obj.(*corev1.Pod) + return []string{string(pod.Status.Phase)} + }, + ). + WithRuntimeObjects(initObjs...). + WithStatusSubresource(&v1.IntegrationKit{}). + Build() + + camelClientset := fakecamelclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return strings.Contains(gvk.Group, "camel") + })...) + clientset := fakeclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return !strings.Contains(gvk.Group, "camel") && !strings.Contains(gvk.Group, "knative") + })...) + replicasCount := make(map[string]int32) + fakescaleclient := fakescale.FakeScaleClient{} + fakescaleclient.AddReactor("update", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.UpdateAction) + + //nolint:forcetypeassert + obj := action.GetObject().(*autoscalingv1.Scale) + + replicas := obj.Spec.Replicas + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), obj.GetName()) + replicasCount[key] = replicas + return true, &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: obj.Name, + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicas, + }, + }, nil + }) + fakescaleclient.AddReactor("get", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.GetAction) + + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), action.GetName()) + obj := &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: action.GetName(), + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicasCount[key], + }, + } + return true, obj, nil + }) + + return &FakeClient{ + Client: c, + Interface: clientset, + camel: camelClientset, + scales: &fakescaleclient, + enabledKnativeServing: true, + enabledKnativeEventing: true, + }, nil +} + +func filterObjects(scheme *runtime.Scheme, input []runtime.Object, filter func(gvk schema.GroupVersionKind) bool) []runtime.Object { + var res []runtime.Object + for _, obj := range input { + kinds, _, _ := scheme.ObjectKinds(obj) + for _, k := range kinds { + if filter(k) { + res = append(res, obj) + break + } + } + } + return res +} + +// FakeClient ---. +type FakeClient struct { + controller.Client + kubernetes.Interface + camel *fakecamelclientset.Clientset + scales *fakescale.FakeScaleClient + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (c *FakeClient) Intercept(intercept *interceptor.Funcs) { + //nolint:forcetypeassert + cw := c.Client.(controller.WithWatch) + c.Client = interceptor.NewClient(cw, *intercept) +} + +func (c *FakeClient) AddReactor(verb, resource string, reaction testing.ReactionFunc) { + c.camel.AddReactor(verb, resource, reaction) +} + +func (c *FakeClient) CamelV1() camelv1.CamelV1Interface { + return c.camel.CamelV1() +} + +// GetScheme ---. +func (c *FakeClient) GetScheme() *runtime.Scheme { + return clientscheme.Scheme +} + +func (c *FakeClient) GetConfig() *rest.Config { + return &rest.Config{} +} + +func (c *FakeClient) GetCurrentNamespace(kubeConfig string) (string, error) { + return "", nil +} + +// Patch mimicks patch for server-side apply and simply creates the obj. +func (c *FakeClient) Patch(ctx context.Context, obj controller.Object, patch controller.Patch, opts ...controller.PatchOption) error { + if err := c.Create(ctx, obj); err != nil { + // Create fails if object already exists. Try to update it. + return c.Update(ctx, obj) + } + return nil +} + +func (c *FakeClient) DisableAPIGroupDiscovery(group string) { + c.disabledGroups = append(c.disabledGroups, group) +} + +func (c *FakeClient) EnableOpenshiftDiscovery() { + c.enabledOpenshift = true +} + +func (c *FakeClient) DisableKnativeServing() { + c.enabledKnativeServing = false +} + +func (c *FakeClient) DisableKnativeEventing() { + c.enabledKnativeEventing = false +} + +func (c *FakeClient) AuthorizationV1() authorizationv1.AuthorizationV1Interface { + return &FakeAuthorization{ + AuthorizationV1Interface: c.Interface.AuthorizationV1(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + } +} + +func (c *FakeClient) Discovery() discovery.DiscoveryInterface { + return &FakeDiscovery{ + DiscoveryInterface: c.Interface.Discovery(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + enabledKnativeServing: c.enabledKnativeServing, + enabledKnativeEventing: c.enabledKnativeEventing, + } +} + +func (c *FakeClient) ServerOrClientSideApplier() client.ServerOrClientSideApplier { + return client.ServerOrClientSideApplier{ + Client: c, + } +} + +func (c *FakeClient) ScalesClient() (scale.ScalesGetter, error) { + return c.scales, nil +} + +type FakeAuthorization struct { + authorizationv1.AuthorizationV1Interface + disabledGroups []string + enabledOpenshift bool +} + +func (f *FakeAuthorization) SelfSubjectRulesReviews() authorizationv1.SelfSubjectRulesReviewInterface { + return f.AuthorizationV1Interface.SelfSubjectRulesReviews() +} + +type FakeDiscovery struct { + discovery.DiscoveryInterface + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (f *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) { + // Normalize the fake discovery to behave like the real implementation when checking for openshift + if groupVersion == "image.openshift.io/v1" { + if f.enabledOpenshift { + return &metav1.APIResourceList{ + GroupVersion: "image.openshift.io/v1", + }, nil + } else { + return nil, k8serrors.NewNotFound(schema.GroupResource{ + Group: "image.openshift.io", + }, "") + } + } + + // used to verify if Knative Serving is installed + if f.enabledKnativeServing { + if groupVersion == "serving.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "serving.knative.dev/v1", + }, nil + } + } + + // used to verify if Knative Eventing is installed + if f.enabledKnativeEventing { + if groupVersion == "eventing.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "eventing.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1beta1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1beta1", + }, nil + } + } + + return f.DiscoveryInterface.ServerResourcesForGroupVersion(groupVersion) +} diff --git a/addons/vault/hashicorp/client_test.go b/addons/vault/hashicorp/client_test.go new file mode 100644 index 0000000000..93c956a356 --- /dev/null +++ b/addons/vault/hashicorp/client_test.go @@ -0,0 +1,299 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// IMPORTANT: this is a clone of pkg/internal. As the addons will be moved into pkg, we are using this utility here temporarily only! + +package hashicorp + +import ( + "context" + "fmt" + "strings" + + "github.com/apache/camel-k/v2/pkg/apis" + v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/client" + fakecamelclientset "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/fake" + camelv1 "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/typed/camel/v1" + "github.com/apache/camel-k/v2/pkg/util" + autoscalingv1 "k8s.io/api/autoscaling/v1" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" + "k8s.io/client-go/kubernetes" + fakeclientset "k8s.io/client-go/kubernetes/fake" + clientscheme "k8s.io/client-go/kubernetes/scheme" + authorizationv1 "k8s.io/client-go/kubernetes/typed/authorization/v1" + "k8s.io/client-go/rest" + "k8s.io/client-go/scale" + fakescale "k8s.io/client-go/scale/fake" + "k8s.io/client-go/testing" + controller "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// newFakeClient ---. +func newFakeClient(initObjs ...runtime.Object) (client.Client, error) { + scheme := clientscheme.Scheme + + // Setup Scheme for all resources + if err := apis.AddToScheme(scheme); err != nil { + return nil, err + } + + c := fake. + NewClientBuilder(). + WithScheme(scheme). + WithIndex( + &corev1.Pod{}, + "status.phase", + func(obj controller.Object) []string { + pod, _ := obj.(*corev1.Pod) + return []string{string(pod.Status.Phase)} + }, + ). + WithRuntimeObjects(initObjs...). + WithStatusSubresource(&v1.IntegrationKit{}). + Build() + + camelClientset := fakecamelclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return strings.Contains(gvk.Group, "camel") + })...) + clientset := fakeclientset.NewSimpleClientset(filterObjects(scheme, initObjs, func(gvk schema.GroupVersionKind) bool { + return !strings.Contains(gvk.Group, "camel") && !strings.Contains(gvk.Group, "knative") + })...) + replicasCount := make(map[string]int32) + fakescaleclient := fakescale.FakeScaleClient{} + fakescaleclient.AddReactor("update", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.UpdateAction) + + //nolint:forcetypeassert + obj := action.GetObject().(*autoscalingv1.Scale) + + replicas := obj.Spec.Replicas + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), obj.GetName()) + replicasCount[key] = replicas + return true, &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: obj.Name, + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicas, + }, + }, nil + }) + fakescaleclient.AddReactor("get", "*", func(rawAction testing.Action) (bool, runtime.Object, error) { + //nolint:forcetypeassert + action := rawAction.(testing.GetAction) + + key := fmt.Sprintf("%s:%s:%s/%s", action.GetResource().Group, action.GetResource().Resource, action.GetNamespace(), action.GetName()) + obj := &autoscalingv1.Scale{ + ObjectMeta: metav1.ObjectMeta{ + Name: action.GetName(), + Namespace: action.GetNamespace(), + }, + Spec: autoscalingv1.ScaleSpec{ + Replicas: replicasCount[key], + }, + } + return true, obj, nil + }) + + return &FakeClient{ + Client: c, + Interface: clientset, + camel: camelClientset, + scales: &fakescaleclient, + enabledKnativeServing: true, + enabledKnativeEventing: true, + }, nil +} + +func filterObjects(scheme *runtime.Scheme, input []runtime.Object, filter func(gvk schema.GroupVersionKind) bool) []runtime.Object { + var res []runtime.Object + for _, obj := range input { + kinds, _, _ := scheme.ObjectKinds(obj) + for _, k := range kinds { + if filter(k) { + res = append(res, obj) + break + } + } + } + return res +} + +// FakeClient ---. +type FakeClient struct { + controller.Client + kubernetes.Interface + camel *fakecamelclientset.Clientset + scales *fakescale.FakeScaleClient + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (c *FakeClient) Intercept(intercept *interceptor.Funcs) { + //nolint:forcetypeassert + cw := c.Client.(controller.WithWatch) + c.Client = interceptor.NewClient(cw, *intercept) +} + +func (c *FakeClient) AddReactor(verb, resource string, reaction testing.ReactionFunc) { + c.camel.AddReactor(verb, resource, reaction) +} + +func (c *FakeClient) CamelV1() camelv1.CamelV1Interface { + return c.camel.CamelV1() +} + +// GetScheme ---. +func (c *FakeClient) GetScheme() *runtime.Scheme { + return clientscheme.Scheme +} + +func (c *FakeClient) GetConfig() *rest.Config { + return &rest.Config{} +} + +func (c *FakeClient) GetCurrentNamespace(kubeConfig string) (string, error) { + return "", nil +} + +// Patch mimicks patch for server-side apply and simply creates the obj. +func (c *FakeClient) Patch(ctx context.Context, obj controller.Object, patch controller.Patch, opts ...controller.PatchOption) error { + if err := c.Create(ctx, obj); err != nil { + // Create fails if object already exists. Try to update it. + return c.Update(ctx, obj) + } + return nil +} + +func (c *FakeClient) DisableAPIGroupDiscovery(group string) { + c.disabledGroups = append(c.disabledGroups, group) +} + +func (c *FakeClient) EnableOpenshiftDiscovery() { + c.enabledOpenshift = true +} + +func (c *FakeClient) DisableKnativeServing() { + c.enabledKnativeServing = false +} + +func (c *FakeClient) DisableKnativeEventing() { + c.enabledKnativeEventing = false +} + +func (c *FakeClient) AuthorizationV1() authorizationv1.AuthorizationV1Interface { + return &FakeAuthorization{ + AuthorizationV1Interface: c.Interface.AuthorizationV1(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + } +} + +func (c *FakeClient) Discovery() discovery.DiscoveryInterface { + return &FakeDiscovery{ + DiscoveryInterface: c.Interface.Discovery(), + disabledGroups: c.disabledGroups, + enabledOpenshift: c.enabledOpenshift, + enabledKnativeServing: c.enabledKnativeServing, + enabledKnativeEventing: c.enabledKnativeEventing, + } +} + +func (c *FakeClient) ServerOrClientSideApplier() client.ServerOrClientSideApplier { + return client.ServerOrClientSideApplier{ + Client: c, + } +} + +func (c *FakeClient) ScalesClient() (scale.ScalesGetter, error) { + return c.scales, nil +} + +type FakeAuthorization struct { + authorizationv1.AuthorizationV1Interface + disabledGroups []string + enabledOpenshift bool +} + +func (f *FakeAuthorization) SelfSubjectRulesReviews() authorizationv1.SelfSubjectRulesReviewInterface { + return f.AuthorizationV1Interface.SelfSubjectRulesReviews() +} + +type FakeDiscovery struct { + discovery.DiscoveryInterface + disabledGroups []string + enabledOpenshift bool + enabledKnativeServing bool + enabledKnativeEventing bool +} + +func (f *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) { + // Normalize the fake discovery to behave like the real implementation when checking for openshift + if groupVersion == "image.openshift.io/v1" { + if f.enabledOpenshift { + return &metav1.APIResourceList{ + GroupVersion: "image.openshift.io/v1", + }, nil + } else { + return nil, k8serrors.NewNotFound(schema.GroupResource{ + Group: "image.openshift.io", + }, "") + } + } + + // used to verify if Knative Serving is installed + if f.enabledKnativeServing { + if groupVersion == "serving.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "serving.knative.dev/v1", + }, nil + } + } + + // used to verify if Knative Eventing is installed + if f.enabledKnativeEventing { + if groupVersion == "eventing.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "eventing.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1", + }, nil + } + if groupVersion == "messaging.knative.dev/v1beta1" && !util.StringSliceExists(f.disabledGroups, groupVersion) { + return &metav1.APIResourceList{ + GroupVersion: "messaging.knative.dev/v1beta1", + }, nil + } + } + + return f.DiscoveryInterface.ServerResourcesForGroupVersion(groupVersion) +} diff --git a/addons/vault/hashicorp/hashicorp_vault_test.go b/addons/vault/hashicorp/hashicorp_vault_test.go index a5d74d91f5..f9415f64b7 100644 --- a/addons/vault/hashicorp/hashicorp_vault_test.go +++ b/addons/vault/hashicorp/hashicorp_vault_test.go @@ -20,7 +20,6 @@ package hashicorp import ( "testing" - "github.com/apache/camel-k/v2/pkg/util/test" corev1 "k8s.io/api/core/v1" "k8s.io/utils/ptr" @@ -133,7 +132,7 @@ func createEnvironment(t *testing.T, catalogGen func() (*camel.RuntimeCatalog, e t.Helper() catalog, err := catalogGen() - client, _ := test.NewFakeClient(objects...) + client, _ := newFakeClient(objects...) require.NoError(t, err) e := trait.Environment{ diff --git a/e2e/advanced/maven_http_proxy_test.go b/e2e/advanced/maven_http_proxy_test.go index 625a6bebbc..b19385513f 100644 --- a/e2e/advanced/maven_http_proxy_test.go +++ b/e2e/advanced/maven_http_proxy_test.go @@ -31,11 +31,11 @@ import ( "encoding/pem" "fmt" "math/big" + math_rand "math/rand" "strings" "testing" "time" - "github.com/apache/camel-k/v2/pkg/util" "github.com/apache/camel-k/v2/pkg/util/envvar" . "github.com/onsi/gomega" @@ -60,7 +60,7 @@ func TestMavenProxy(t *testing.T) { WithNewTestNamespace(t, func(ctx context.Context, g *WithT, ns string) { hostname := fmt.Sprintf("%s.%s.svc", "proxy", ns) // Generate the TLS certificate - serialNumber := big.NewInt(util.RandomInt63()) + serialNumber := big.NewInt(math_rand.NewSource(time.Now().UTC().UnixNano()).Int63()) cert := &x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ diff --git a/e2e/common/traits/route_test.go b/e2e/common/traits/route_test.go index b39d01831e..5921bbe717 100644 --- a/e2e/common/traits/route_test.go +++ b/e2e/common/traits/route_test.go @@ -33,6 +33,7 @@ import ( "encoding/pem" "fmt" "math/big" + math_rand "math/rand" "net/http" "testing" "time" @@ -43,7 +44,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" . "github.com/apache/camel-k/v2/e2e/support" - "github.com/apache/camel-k/v2/pkg/util" "github.com/apache/camel-k/v2/pkg/util/openshift" ) @@ -262,7 +262,7 @@ func createSecret(t *testing.T, ctx context.Context, ns string) (corev1.Secret, } func generateSampleKeyAndCertificate(t *testing.T, ctx context.Context, ns string) keyCertificatePair { - serialNumber := big.NewInt(util.RandomInt63()) + serialNumber := big.NewInt(math_rand.NewSource(time.Now().UTC().UnixNano()).Int63()) domainName, err := ClusterDomainName(t, ctx) if err != nil { fmt.Printf("Error retrieving cluster domain object, then the http client request will skip TLS validation: %s\n", err) diff --git a/e2e/install/olm/olm_install_test.go b/e2e/install/olm/olm_install_test.go index a8d4a239ec..ab49c54d39 100644 --- a/e2e/install/olm/olm_install_test.go +++ b/e2e/install/olm/olm_install_test.go @@ -73,7 +73,7 @@ func TestOLMInstallation(t *testing.T) { Should(Equal(olm.CSVPhaseSucceeded)) // Check the operator pod is running g.Eventually(OperatorPodPhase(t, ctx, ns), TestTimeoutMedium).Should(Equal(corev1.PodRunning)) - g.Eventually(OperatorImage(t, ctx, ns), TestTimeoutShort).Should(Equal(defaults.OperatorImage())) + g.Eventually(OperatorImage(t, ctx, ns), TestTimeoutShort).Should(Equal(operatorImage())) integrationPlatform := v1.NewIntegrationPlatform(ns, "camel-k") integrationPlatform.Spec.Build.Registry = v1.RegistrySpec{ @@ -112,3 +112,17 @@ func TestOLMInstallation(t *testing.T) { g.Eventually(CRDs(t)).Should(BeNil()) }) } + +func operatorImage() string { + return envOrDefault(fmt.Sprintf("%s:%s", defaults.ImageName, defaults.Version), "KAMEL_OPERATOR_IMAGE", "KAMEL_K_TEST_OPERATOR_CURRENT_IMAGE") +} + +func envOrDefault(def string, envs ...string) string { + for i := range envs { + if val := os.Getenv(envs[i]); val != "" { + return val + } + } + + return def +} diff --git a/e2e/support/test_nexus_hooks.go b/e2e/support/test_nexus_hooks.go deleted file mode 100644 index 83dbde5753..0000000000 --- a/e2e/support/test_nexus_hooks.go +++ /dev/null @@ -1,68 +0,0 @@ -//go:build integration -// +build integration - -// To enable compilation of this file in Goland, go to "Settings -> Go -> Vendoring & Build Tags -> Custom Tags" and add "integration" - -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package support - -import ( - "fmt" - "os" - - corev1 "k8s.io/api/core/v1" - - ctrl "sigs.k8s.io/controller-runtime/pkg/client" -) - -const ( - nexusNamespace = "nexus" - nexusService = "nexus" - nexusMavenMirror = "http://nexus.nexus/repository/maven-public/@id=nexus@mirrorOf=central" -) - -func init() { - // Nexus repository mirror is disabled by default for E2E testing - nexus := os.Getenv("TEST_ENABLE_NEXUS") - if nexus == "true" { - svcChecked := false - svcExists := true - KamelHooks = append(KamelHooks, func(args []string) []string { - if len(args) > 0 && args[0] == "install" { - // Enable mirror only if nexus service exists - if !svcChecked { - svc := corev1.Service{} - key := ctrl.ObjectKey{ - Namespace: nexusNamespace, - Name: nexusService, - } - - if err := TestClient(nil).Get(TestContext(), key, &svc); err != nil { - svcExists = false - } - svcChecked = true - } - if svcExists { - args = append(args, fmt.Sprintf("--maven-repository=%s", nexusMavenMirror)) - } - } - return args - }) - } -} diff --git a/e2e/support/test_staging_hooks.go b/e2e/support/test_staging_hooks.go deleted file mode 100644 index fdcbc049f0..0000000000 --- a/e2e/support/test_staging_hooks.go +++ /dev/null @@ -1,54 +0,0 @@ -//go:build integration -// +build integration - -// To enable compilation of this file in Goland, go to "Settings -> Go -> Vendoring & Build Tags -> Custom Tags" and add "integration" - -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package support - -import ( - "fmt" - "os" - - "github.com/apache/camel-k/v2/pkg/util" -) - -func init() { - // Apply env vars for the test operator image to args if present - imageName := os.Getenv("CAMEL_K_TEST_IMAGE_NAME") - imageVersion := os.Getenv("CAMEL_K_TEST_IMAGE_VERSION") - if imageName != "" || imageVersion != "" { - if imageName == "" { - imageName = TestImageName - } - if imageVersion == "" { - imageVersion = TestImageVersion - } - KamelHooks = append(KamelHooks, func(args []string) []string { - if len(args) > 0 && args[0] == "install" { - // Prefer explicit args from test over env - if !util.StringSliceExists(args, "--operator-image") && !util.StringContainsPrefix(args, "--operator-image=") { - args = append(args, fmt.Sprintf("--operator-image=%s:%s", imageName, imageVersion)) - } - } - return args - }) - } - -} diff --git a/e2e/support/test_support.go b/e2e/support/test_support.go index 5922f19072..d713df020e 100644 --- a/e2e/support/test_support.go +++ b/e2e/support/test_support.go @@ -1942,7 +1942,7 @@ func PlatformByName(t *testing.T, ctx context.Context, ns string, name string) f func IntegrationProfileByName(t *testing.T, ctx context.Context, ns string, name string) func() *v1.IntegrationProfile { return func() *v1.IntegrationProfile { - lst := v1.NewIntegrationProfileList() + lst := newIntegrationProfileList() if err := TestClient(t).List(ctx, &lst, ctrl.InNamespace(ns)); err != nil { failTest(t, err) } @@ -1955,6 +1955,16 @@ func IntegrationProfileByName(t *testing.T, ctx context.Context, ns string, name } } +// newIntegrationProfileList --. +func newIntegrationProfileList() v1.IntegrationProfileList { + return v1.IntegrationProfileList{ + TypeMeta: metav1.TypeMeta{ + APIVersion: v1.SchemeGroupVersion.String(), + Kind: v1.IntegrationProfileKind, + }, + } +} + func CamelCatalog(t *testing.T, ctx context.Context, ns, name string) func() *v1.CamelCatalog { return func() *v1.CamelCatalog { cat := v1.CamelCatalog{} @@ -1973,7 +1983,7 @@ func CamelCatalog(t *testing.T, ctx context.Context, ns, name string) func() *v1 func IntegrationProfile(t *testing.T, ctx context.Context, ns string) func() *v1.IntegrationProfile { return func() *v1.IntegrationProfile { - lst := v1.NewIntegrationProfileList() + lst := newIntegrationProfileList() if err := TestClient(t).List(ctx, &lst, ctrl.InNamespace(ns)); err != nil { failTest(t, err) } diff --git a/e2e/support/util/temp_file.go b/e2e/support/util/temp_file.go index fc795518b5..3d255a9778 100644 --- a/e2e/support/util/temp_file.go +++ b/e2e/support/util/temp_file.go @@ -21,6 +21,7 @@ limitations under the License. package util import ( + "io/fs" "os" "path/filepath" "strings" @@ -49,7 +50,7 @@ func MakeTempCopyDir(t *testing.T, dirName string) string { _, simpleName := filepath.Split(dirName) tmpDir := MakeTempDir(t) tmpDirName := filepath.Join(tmpDir, simpleName) - if err := util.CopyDir(dirName, tmpDirName); err != nil { + if err := copyDir(dirName, tmpDirName); err != nil { t.Error(err) t.FailNow() } @@ -83,3 +84,75 @@ func MakeTempDir(t *testing.T) string { } return tmpDir } + +func copyDir(src, dst string) error { + entries, err := os.ReadDir(src) + if err != nil { + return err + } + + for _, entry := range entries { + srcEntry := filepath.Join(src, entry.Name()) + dstEntry := filepath.Join(dst, entry.Name()) + realEntry := entry + if entry.Type() == os.ModeSymlink { + realPath, err := filepath.EvalSymlinks(srcEntry) + if err != nil { + return err + } + realInfo, err := os.Stat(realPath) + if err != nil { + return err + } + srcEntry = realPath + realEntry = fs.FileInfoToDirEntry(realInfo) + } + if realEntry.IsDir() { + if err := CopyDir(srcEntry, dstEntry); err != nil { + return err + } + } else { + if _, err := util.CopyFile(srcEntry, dstEntry); err != nil { + return err + } + } + } + + return nil +} + +func CopyDir(src, dst string) error { + entries, err := os.ReadDir(src) + if err != nil { + return err + } + + for _, entry := range entries { + srcEntry := filepath.Join(src, entry.Name()) + dstEntry := filepath.Join(dst, entry.Name()) + realEntry := entry + if entry.Type() == os.ModeSymlink { + realPath, err := filepath.EvalSymlinks(srcEntry) + if err != nil { + return err + } + realInfo, err := os.Stat(realPath) + if err != nil { + return err + } + srcEntry = realPath + realEntry = fs.FileInfoToDirEntry(realInfo) + } + if realEntry.IsDir() { + if err := CopyDir(srcEntry, dstEntry); err != nil { + return err + } + } else { + if _, err := util.CopyFile(srcEntry, dstEntry); err != nil { + return err + } + } + } + + return nil +} diff --git a/pkg/apis/camel/v1/build_types_support.go b/pkg/apis/camel/v1/build_types_support.go index 1c01cd5d52..0294989026 100644 --- a/pkg/apis/camel/v1/build_types_support.go +++ b/pkg/apis/camel/v1/build_types_support.go @@ -37,15 +37,6 @@ func NewBuild(namespace string, name string) *Build { } } -func NewBuildList() BuildList { - return BuildList{ - TypeMeta: metav1.TypeMeta{ - APIVersion: SchemeGroupVersion.String(), - Kind: BuildKind, - }, - } -} - // BuilderPodNamespace returns the namespace of the operator in charge to reconcile this Build. func (build *Build) BuilderPodNamespace() string { for _, t := range build.Spec.Tasks { diff --git a/pkg/apis/camel/v1/integrationprofile_types_support.go b/pkg/apis/camel/v1/integrationprofile_types_support.go index 76c5e88d4f..6ae13b9946 100644 --- a/pkg/apis/camel/v1/integrationprofile_types_support.go +++ b/pkg/apis/camel/v1/integrationprofile_types_support.go @@ -22,16 +22,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// NewIntegrationProfileList --. -func NewIntegrationProfileList() IntegrationProfileList { - return IntegrationProfileList{ - TypeMeta: metav1.TypeMeta{ - APIVersion: SchemeGroupVersion.String(), - Kind: IntegrationProfileKind, - }, - } -} - // NewIntegrationProfile --. func NewIntegrationProfile(namespace string, name string) IntegrationProfile { return IntegrationProfile{ diff --git a/pkg/apis/duck/strimzi/v1beta2/register.go b/pkg/apis/duck/strimzi/v1beta2/register.go index 506c02d3fc..c1d51588a2 100644 --- a/pkg/apis/duck/strimzi/v1beta2/register.go +++ b/pkg/apis/duck/strimzi/v1beta2/register.go @@ -34,11 +34,6 @@ var ( AddToScheme = SchemeBuilder.AddToScheme ) -// Resource takes an unqualified resource and returns a Group qualified GroupResource. -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, diff --git a/pkg/base/root.go b/pkg/base/root.go deleted file mode 100644 index 0ebf1e7339..0000000000 --- a/pkg/base/root.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package base - -import ( - "os" - "path/filepath" -) - -var GoModDirectory string - -func FileExists(name string) bool { - stat, err := os.Stat(name) - if err != nil { - if os.IsNotExist(err) { - return false - } - } - - return !stat.IsDir() -} - -func init() { - // Save the original directory the process started in. - wd, err := os.Getwd() - if err != nil { - panic(err) - } - initialDir, err := filepath.Abs(wd) - if err != nil { - panic(err) - } - - // Find the module dir.. - current := "" - for next := initialDir; current != next; next = filepath.Dir(current) { - current = next - if FileExists(filepath.Join(current, "go.mod")) && FileExists(filepath.Join(current, "go.sum")) { - GoModDirectory = current - - break - } - } - - if GoModDirectory == "" { - panic("could not find the root module directory") - } -} diff --git a/pkg/util/cancellable/cancellable.go b/pkg/builder/builder_support_test.go similarity index 80% rename from pkg/util/cancellable/cancellable.go rename to pkg/builder/builder_support_test.go index 86d335b16b..d09a36d5a0 100644 --- a/pkg/util/cancellable/cancellable.go +++ b/pkg/builder/builder_support_test.go @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package cancellable +package builder import "context" @@ -26,13 +26,13 @@ type Context interface { Cancel() } -// NewContext returns an empty cancelable Context. -func NewContext() Context { - return NewContextWithParent(context.TODO()) +// newContext returns an empty cancelable Context. +func newContext() Context { + return newContextWithParent(context.TODO()) } -// NewContextWithParent returns an empty cancelable Context with a parent. -func NewContextWithParent(parent context.Context) Context { +// newContextWithParent returns an empty cancelable Context with a parent. +func newContextWithParent(parent context.Context) Context { c, cc := context.WithCancel(parent) return &cancellableContext{ diff --git a/pkg/builder/builder_test.go b/pkg/builder/builder_test.go index dd12778634..adcc070e74 100644 --- a/pkg/builder/builder_test.go +++ b/pkg/builder/builder_test.go @@ -25,8 +25,7 @@ import ( "github.com/stretchr/testify/require" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/cancellable" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" ) type errorTestSteps struct { @@ -35,7 +34,7 @@ type errorTestSteps struct { } func TestBuilderFailure(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) b := New(c) @@ -69,14 +68,14 @@ func TestBuilderFailure(t *testing.T) { }, } - ctx := cancellable.NewContext() + ctx := newContext() status := b.Build(build).TaskByName("builder").Do(ctx) assert.Equal(t, v1.BuildPhaseFailed, status.Phase) assert.Equal(t, "an error", status.Error) } func TestS2IPublishingFailure(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) b := New(c) build := &v1.Build{ @@ -99,7 +98,7 @@ func TestS2IPublishingFailure(t *testing.T) { }, } - ctx := cancellable.NewContext() + ctx := newContext() status := b.Build(build).TaskByName("s2i").Do(ctx) assert.Equal(t, v1.BuildPhaseFailed, status.Phase) assert.NotEmpty(t, status.Error) @@ -108,7 +107,7 @@ func TestS2IPublishingFailure(t *testing.T) { } func TestJibPublishingFailure(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) b := New(c) build := &v1.Build{ @@ -131,7 +130,7 @@ func TestJibPublishingFailure(t *testing.T) { }, } - ctx := cancellable.NewContext() + ctx := newContext() status := b.Build(build).TaskByName("jib").Do(ctx) assert.Equal(t, v1.BuildPhaseFailed, status.Phase) assert.NotEmpty(t, status.Error) @@ -140,7 +139,7 @@ func TestJibPublishingFailure(t *testing.T) { } func TestSpectrumPublishingFailure(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) b := New(c) build := &v1.Build{ @@ -163,7 +162,7 @@ func TestSpectrumPublishingFailure(t *testing.T) { }, } - ctx := cancellable.NewContext() + ctx := newContext() status := b.Build(build).TaskByName("spectrum").Do(ctx) assert.Equal(t, v1.BuildPhaseFailed, status.Phase) assert.NotEmpty(t, status.Error) diff --git a/pkg/builder/image_test.go b/pkg/builder/image_test.go index 51c3b786cc..b16d24a909 100644 --- a/pkg/builder/image_test.go +++ b/pkg/builder/image_test.go @@ -26,17 +26,16 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" - "github.com/apache/camel-k/v2/pkg/util/cancellable" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestListPublishedImages(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := test.NewFakeClient( + c, err := internal.NewFakeClient( &v1.IntegrationKit{ TypeMeta: metav1.TypeMeta{ APIVersion: v1.SchemeGroupVersion.String(), @@ -87,7 +86,7 @@ func TestListPublishedImages(t *testing.T) { i, err := listPublishedImages(&builderContext{ Client: c, Catalog: catalog, - C: cancellable.NewContext(), + C: newContext(), }) require.NoError(t, err) diff --git a/pkg/builder/project_test.go b/pkg/builder/project_test.go index 53e378962d..1a50dfdd29 100644 --- a/pkg/builder/project_test.go +++ b/pkg/builder/project_test.go @@ -30,10 +30,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/maven" - "github.com/apache/camel-k/v2/pkg/util/test" ) const customSettings = ` @@ -197,7 +197,7 @@ func TestMavenSettingsFromConfigMap(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := test.NewFakeClient( + c, err := internal.NewFakeClient( &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", @@ -246,7 +246,7 @@ func TestMavenSettingsWithSettingsSecurityFromConfigMap(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := test.NewFakeClient( + c, err := internal.NewFakeClient( &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", @@ -317,7 +317,7 @@ func TestMavenSettingsFromSecret(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := test.NewFakeClient( + c, err := internal.NewFakeClient( &corev1.Secret{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", @@ -366,7 +366,7 @@ func TestMavenSettingsWithSettingsSecurityFromSecret(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := test.NewFakeClient( + c, err := internal.NewFakeClient( &corev1.Secret{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", diff --git a/pkg/builder/quarkus_test.go b/pkg/builder/quarkus_test.go index a302ef1a6c..42db8bdfc9 100644 --- a/pkg/builder/quarkus_test.go +++ b/pkg/builder/quarkus_test.go @@ -28,9 +28,9 @@ import ( "github.com/apache/camel-k/v2/pkg/util/boolean" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/defaults" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -53,7 +53,7 @@ func TestGenerateQuarkusProjectCommon(t *testing.T) { } func TestLoadCamelQuarkusCatalogMissing(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) builderContext := builderContext{ Client: c, @@ -77,7 +77,7 @@ func TestLoadCamelQuarkusCatalogOk(t *testing.T) { Provider: "Quarkus", Dependencies: make([]v1.MavenArtifact, 0), } - c, err := test.NewFakeClient(&v1.CamelCatalog{ + c, err := internal.NewFakeClient(&v1.CamelCatalog{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: "my-fake-catalog", @@ -231,7 +231,7 @@ func TestBuildQuarkusRunner(t *testing.T) { require.NoError(t, err) defaultCatalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := test.NewFakeClient(&v1.CamelCatalog{ + c, err := internal.NewFakeClient(&v1.CamelCatalog{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: "camel-catalog-" + defaults.DefaultRuntimeVersion, diff --git a/pkg/cmd/bind_test.go b/pkg/cmd/bind_test.go index b348657b23..450f6aca39 100644 --- a/pkg/cmd/bind_test.go +++ b/pkg/cmd/bind_test.go @@ -22,8 +22,8 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/platform" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -36,7 +36,7 @@ func initializeBindCmdOptions(t *testing.T) (*bindCmdOptions, *cobra.Command, Ro t.Helper() defaultIntegrationPlatform := v1.NewIntegrationPlatform("default", platform.DefaultPlatformName) - fakeClient, _ := test.NewFakeClient(&defaultIntegrationPlatform) + fakeClient, _ := internal.NewFakeClient(&defaultIntegrationPlatform) options, rootCmd := kamelTestPreAddCommandInitWithClient(fakeClient) bindCmdOptions := addTestBindCmd(*options, rootCmd) @@ -48,14 +48,14 @@ func initializeBindCmdOptions(t *testing.T) (*bindCmdOptions, *cobra.Command, Ro func addTestBindCmd(options RootCmdOptions, rootCmd *cobra.Command) *bindCmdOptions { // add a testing version of bind Command bindCmd, bindOptions := newCmdBind(&options) - bindCmd.Args = test.ArbitraryArgs + bindCmd.Args = ArbitraryArgs rootCmd.AddCommand(bindCmd) return bindOptions } func TestBindOutputJSON(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "json") + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "json") assert.Equal(t, "json", buildCmdOptions.OutputFormat) require.NoError(t, err) @@ -64,7 +64,7 @@ func TestBindOutputJSON(t *testing.T) { func TestBindOutputYAML(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml") + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml") assert.Equal(t, "yaml", buildCmdOptions.OutputFormat) require.NoError(t, err) @@ -86,7 +86,7 @@ status: {} func TestBindOutputUnknownFormat(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, _ := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "fail") + output, _ := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "fail") assert.Equal(t, "fail", buildCmdOptions.OutputFormat) assert.Equal(t, "invalid output format option 'fail', should be one of: yaml|json\n", output) @@ -94,7 +94,7 @@ func TestBindOutputUnknownFormat(t *testing.T) { func TestBindErrorHandlerDLCKamelet(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", "--error-handler", "sink:my-kamelet", "-p", "error-handler.my-prop=value") assert.Equal(t, "yaml", buildCmdOptions.OutputFormat) @@ -126,7 +126,7 @@ status: {} func TestBindErrorHandlerNone(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", "--error-handler", "none") assert.Equal(t, "yaml", buildCmdOptions.OutputFormat) @@ -151,7 +151,7 @@ status: {} func TestBindErrorHandlerLog(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", "--error-handler", "log") assert.Equal(t, "yaml", buildCmdOptions.OutputFormat) @@ -176,7 +176,7 @@ status: {} func TestBindTraits(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", "-t", "mount.configs=configmap:my-cm", "-c", "my-service-binding") assert.Equal(t, "yaml", buildCmdOptions.OutputFormat) @@ -201,7 +201,7 @@ status: {} func TestBindTraitsArray(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", "-t", "camel.properties=a=1", "-t", "camel.properties=b=2") assert.Equal(t, "yaml", buildCmdOptions.OutputFormat) @@ -225,7 +225,7 @@ status: {} func TestBindSteps(t *testing.T) { buildCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", + output, err := ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml", "--step", "dst:step1", "--step", "src:step2", "-p", "step-1.var1=my-step1-var1", "-p", "step-1.var2=my-step1-var2", "-p", "step-2.var1=my-step2-var1", "-p", "step-2.var2=my-step2-var2") @@ -259,7 +259,7 @@ status: {} func TestBindServiceAccountName(t *testing.T) { _, bindCmd, _ := initializeBindCmdOptions(t) - output, err := test.ExecuteCommand(bindCmd, cmdBind, "timer:foo", "log:bar", + output, err := ExecuteCommand(bindCmd, cmdBind, "timer:foo", "log:bar", "-o", "yaml", "--service-account", "my-service-account") @@ -274,6 +274,6 @@ func TestBindOutputWithoutKubernetesCluster(t *testing.T) { bindCmdOptions, bindCmd, _ := initializeBindCmdOptions(t) bindCmdOptions._client = nil // remove the default fake client which can bypass this test bindCmdOptions.KubeConfig = tmpFile.Name() - _, err = test.ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml") + _, err = ExecuteCommand(bindCmd, cmdBind, "my:src", "my:dst", "-o", "yaml") require.NoError(t, err) } diff --git a/pkg/cmd/builder_test.go b/pkg/cmd/builder_test.go index 4f5ee39e30..3ef4af77eb 100644 --- a/pkg/cmd/builder_test.go +++ b/pkg/cmd/builder_test.go @@ -20,7 +20,6 @@ package cmd import ( "testing" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -48,27 +47,27 @@ func addTestBuilderCmd(options RootCmdOptions, rootCmd *cobra.Command) *builderC builderCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - builderCmd.Args = test.ArbitraryArgs + builderCmd.Args = ArbitraryArgs rootCmd.AddCommand(builderCmd) return builderOptions } func TestBuilderNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeBuilderCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdBuilder, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, cmdBuilder, "--nonExistingFlag") require.Error(t, err) } func TestBuilderBuildNameFlag(t *testing.T) { builderCmdOptions, rootCmd, _ := initializeBuilderCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdBuilder, "--build-name", "someBuild") + _, err := ExecuteCommand(rootCmd, cmdBuilder, "--build-name", "someBuild") require.NoError(t, err) assert.Equal(t, "someBuild", builderCmdOptions.BuildName) } func TestBuilderTaskNameFlag(t *testing.T) { builderCmdOptions, rootCmd, _ := initializeBuilderCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdBuilder, "--task-name", "someTask") + _, err := ExecuteCommand(rootCmd, cmdBuilder, "--task-name", "someTask") require.NoError(t, err) assert.Equal(t, "someTask", builderCmdOptions.TaskName) } diff --git a/pkg/util/test/cmd.go b/pkg/cmd/cmd_support_test.go similarity index 99% rename from pkg/util/test/cmd.go rename to pkg/cmd/cmd_support_test.go index cb8f1f150c..65a3530c36 100644 --- a/pkg/util/test/cmd.go +++ b/pkg/cmd/cmd_support_test.go @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package test +package cmd import ( "bytes" diff --git a/pkg/cmd/config_test.go b/pkg/cmd/config_test.go index 606e27ed29..2fad505484 100644 --- a/pkg/cmd/config_test.go +++ b/pkg/cmd/config_test.go @@ -24,7 +24,6 @@ import ( "strings" "testing" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -51,48 +50,48 @@ func addTestConfigCmd(options RootCmdOptions, rootCmd *cobra.Command, mock bool) return nil } } - configCmd.Args = test.ArbitraryArgs + configCmd.Args = ArbitraryArgs rootCmd.AddCommand(configCmd) return configOptions } func TestConfigNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeConfigCmdOptions(t, true) - _, err := test.ExecuteCommand(rootCmd, cmdConfig, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, cmdConfig, "--nonExistingFlag") require.Error(t, err) } func TestConfigDefaultNamespaceFlag(t *testing.T) { configCmdOptions, rootCmd, _ := initializeConfigCmdOptions(t, true) - _, err := test.ExecuteCommand(rootCmd, cmdConfig, "--default-namespace", "foo") + _, err := ExecuteCommand(rootCmd, cmdConfig, "--default-namespace", "foo") require.NoError(t, err) assert.Equal(t, "foo", configCmdOptions.DefaultNamespace) } func TestConfigListFlag(t *testing.T) { _, rootCmd, _ := initializeConfigCmdOptions(t, false) - output, err := test.ExecuteCommand(rootCmd, cmdConfig, "--list") + output, err := ExecuteCommand(rootCmd, cmdConfig, "--list") require.NoError(t, err) assert.True(t, strings.Contains(output, "No settings"), "The output is unexpected: "+output) } func TestConfigFolderFlagToUsed(t *testing.T) { _, rootCmd, _ := initializeConfigCmdOptions(t, false) - output, err := test.ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "used") + output, err := ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "used") require.NoError(t, err) assert.True(t, strings.Contains(output, fmt.Sprintf(" %s", DefaultConfigLocation)), "The output is unexpected: "+output) } func TestConfigFolderFlagToSub(t *testing.T) { _, rootCmd, _ := initializeConfigCmdOptions(t, false) - output, err := test.ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "sub") + output, err := ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "sub") require.NoError(t, err) assert.True(t, strings.Contains(output, filepath.FromSlash(fmt.Sprintf(".kamel/%s", DefaultConfigLocation))), "The output is unexpected: "+output) } func TestConfigFolderFlagToHome(t *testing.T) { _, rootCmd, _ := initializeConfigCmdOptions(t, false) - output, err := test.ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "home") + output, err := ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "home") require.NoError(t, err) assert.True(t, strings.Contains(output, filepath.FromSlash(fmt.Sprintf(".kamel/%s", DefaultConfigLocation))), "The output is unexpected: "+output) } @@ -101,7 +100,7 @@ func TestConfigFolderFlagToEnv(t *testing.T) { os.Setenv("KAMEL_CONFIG_PATH", "/foo/bar") t.Cleanup(func() { os.Unsetenv("KAMEL_CONFIG_PATH") }) _, rootCmd, _ := initializeConfigCmdOptions(t, false) - output, err := test.ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "env") + output, err := ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "env") require.NoError(t, err) assert.True(t, strings.Contains(output, filepath.FromSlash(fmt.Sprintf("foo/bar/%s", DefaultConfigLocation))), "The output is unexpected: "+output) } @@ -114,7 +113,7 @@ func TestConfigFolderFlagToEnvWithConfigName(t *testing.T) { os.Unsetenv("KAMEL_CONFIG_PATH") }) _, rootCmd, _ := initializeConfigCmdOptions(t, false) - output, err := test.ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "env") + output, err := ExecuteCommand(rootCmd, cmdConfig, "--list", "--folder", "env") require.NoError(t, err) assert.True(t, strings.Contains(output, filepath.FromSlash("/foo/bar/config.yaml")), "The output is unexpected: "+output) } @@ -124,15 +123,15 @@ func TestConfigDefaultNamespace(t *testing.T) { assert.True(t, os.IsNotExist(err), "No file at "+DefaultConfigLocation+" was expected") _, rootCmd, _ := initializeConfigCmdOptions(t, false) t.Cleanup(func() { os.Remove(DefaultConfigLocation) }) - _, err = test.ExecuteCommand(rootCmd, cmdConfig, "--default-namespace", "foo") + _, err = ExecuteCommand(rootCmd, cmdConfig, "--default-namespace", "foo") require.NoError(t, err) _, err = os.Stat(DefaultConfigLocation) require.NoError(t, err, "A file at "+DefaultConfigLocation+" was expected") - output, err := test.ExecuteCommand(rootCmd, cmdConfig, "--list") + output, err := ExecuteCommand(rootCmd, cmdConfig, "--list") require.NoError(t, err) assert.True(t, strings.Contains(output, "foo"), "The output is unexpected: "+output) _, rootCmd, _ = initializeInstallCmdOptions(t) - _, err = test.ExecuteCommand(rootCmd, cmdInstall) + _, err = ExecuteCommand(rootCmd, cmdInstall) require.NoError(t, err) // Check default namespace is set assert.Equal(t, "foo", rootCmd.Flag("namespace").Value.String()) diff --git a/pkg/cmd/debug_test.go b/pkg/cmd/debug_test.go index abd7957bf4..15be396723 100644 --- a/pkg/cmd/debug_test.go +++ b/pkg/cmd/debug_test.go @@ -21,7 +21,7 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -35,7 +35,7 @@ const cmdDebug = "debug" // nolint: unparam func initializeDebugCmdOptions(t *testing.T, initObjs ...runtime.Object) (*cobra.Command, *debugCmdOptions) { t.Helper() - fakeClient, err := test.NewFakeClient(initObjs...) + fakeClient, err := internal.NewFakeClient(initObjs...) require.NoError(t, err) options, rootCmd := kamelTestPreAddCommandInitWithClient(fakeClient) options.Namespace = "default" @@ -47,7 +47,7 @@ func initializeDebugCmdOptions(t *testing.T, initObjs ...runtime.Object) (*cobra func addTestDebugCmd(options RootCmdOptions, rootCmd *cobra.Command) *debugCmdOptions { debugCmd, debugOptions := newCmdDebug(&options) - debugCmd.Args = test.ArbitraryArgs + debugCmd.Args = ArbitraryArgs rootCmd.AddCommand(debugCmd) return debugOptions } diff --git a/pkg/cmd/delete_test.go b/pkg/cmd/delete_test.go index 5388c034e7..806386b4fe 100644 --- a/pkg/cmd/delete_test.go +++ b/pkg/cmd/delete_test.go @@ -20,7 +20,6 @@ package cmd import ( "testing" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -48,20 +47,20 @@ func addTestDeleteCmd(options RootCmdOptions, rootCmd *cobra.Command) *deleteCmd deleteCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - deleteCmd.Args = test.ArbitraryArgs + deleteCmd.Args = ArbitraryArgs rootCmd.AddCommand(deleteCmd) return deleteOptions } func TestDeleteNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeDeleteCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdDelete, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, cmdDelete, "--nonExistingFlag") require.Error(t, err) } func TestDeleteAllFlag(t *testing.T) { deleteCmdOptions, rootCmd, _ := initializeDeleteCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdDelete, "--all") + _, err := ExecuteCommand(rootCmd, cmdDelete, "--all") require.NoError(t, err) assert.True(t, deleteCmdOptions.DeleteAll) } diff --git a/pkg/cmd/install_test.go b/pkg/cmd/install_test.go index ba6d4d6045..aebe875584 100644 --- a/pkg/cmd/install_test.go +++ b/pkg/cmd/install_test.go @@ -25,7 +25,6 @@ import ( "github.com/stretchr/testify/require" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" ) const cmdInstall = "install" @@ -50,14 +49,14 @@ func addTestInstallCmd(options RootCmdOptions, rootCmd *cobra.Command) *installC installCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - installCmd.Args = test.ArbitraryArgs + installCmd.Args = ArbitraryArgs rootCmd.AddCommand(installCmd) return installOptions } func TestInstallNoFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall) + _, err := ExecuteCommand(rootCmd, cmdInstall) require.NoError(t, err) // Check default expected values assert.False(t, installCmdOptions.Wait) @@ -83,97 +82,97 @@ func TestInstallNoFlag(t *testing.T) { func TestInstallNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--nonExistingFlag") require.Error(t, err) } func TestInstallBaseImageFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--base-image", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--base-image", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.BaseImage) } func TestInstallBuildPublishStrategyFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--build-publish-strategy", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--build-publish-strategy", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.BuildPublishStrategy) } func TestInstallBuildStrategyFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--build-strategy", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--build-strategy", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.BuildStrategy) } func TestInstallBuildOrderStrategyFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--build-order-strategy", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--build-order-strategy", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.BuildOrderStrategy) } func TestInstallBuildTimeoutFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--build-timeout", "10") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--build-timeout", "10") require.NoError(t, err) assert.Equal(t, "10", installCmdOptions.BuildTimeout) } func TestInstallClusterSetupFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--cluster-setup") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--cluster-setup") require.NoError(t, err) assert.True(t, installCmdOptions.ClusterSetupOnly) } func TestInstallClusterTypeFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--cluster-type", "Kubernetes") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--cluster-type", "Kubernetes") require.NoError(t, err) assert.Equal(t, "Kubernetes", installCmdOptions.ClusterType) } func TestInstallExampleFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--example") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--example") require.NoError(t, err) assert.True(t, installCmdOptions.ExampleSetup) } func TestInstallForceFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--force") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--force") require.NoError(t, err) assert.True(t, installCmdOptions.Force) } func TestInstallGlobalFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--global") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--global") require.NoError(t, err) assert.True(t, installCmdOptions.Global) } func TestInstallHealthFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--health-port", "7777") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--health-port", "7777") require.NoError(t, err) assert.Equal(t, int32(7777), installCmdOptions.HealthPort) } func TestInstallLocalRepositoryFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--maven-local-repository", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--maven-local-repository", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.MavenLocalRepository) } func TestInstallMavenRepositoryFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, + _, err := ExecuteCommand(rootCmd, cmdInstall, "--maven-repository", "someString1", "--maven-repository", "someString2") require.NoError(t, err) @@ -183,14 +182,14 @@ func TestInstallMavenRepositoryFlag(t *testing.T) { func TestInstallMavenSettingsFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--maven-settings", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--maven-settings", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.MavenSettings) } func TestInstallMonitoringFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, + _, err := ExecuteCommand(rootCmd, cmdInstall, "--monitoring", "--monitoring-port", "7777") require.NoError(t, err) @@ -200,14 +199,14 @@ func TestInstallMonitoringFlag(t *testing.T) { func TestInstallOlmFalseFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--olm=false") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--olm=false") require.NoError(t, err) assert.False(t, installCmdOptions.Olm) } func TestInstallOlmTrueNonDefaultFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--olm", + _, err := ExecuteCommand(rootCmd, cmdInstall, "--olm", "--olm-channel", "olmChannel", "--olm-global-namespace", "olmGlobalNamespace", "--olm-operator-name", "olmOperatorName", @@ -228,28 +227,28 @@ func TestInstallOlmTrueNonDefaultFlag(t *testing.T) { func TestInstallOperatorImageFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--operator-image", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--operator-image", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.OperatorImage) } func TestInstallOperatorImagePullPolicyFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--operator-image-pull-policy", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--operator-image-pull-policy", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.OperatorImagePullPolicy) } func TestInstallOutputFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--output", "yaml") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--output", "yaml") require.NoError(t, err) assert.Equal(t, "yaml", installCmdOptions.OutputFormat) } func TestInstallPropertyFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, + _, err := ExecuteCommand(rootCmd, cmdInstall, "--maven-property", "someString1", "--maven-property", "someString2") require.NoError(t, err) @@ -259,7 +258,7 @@ func TestInstallPropertyFlag(t *testing.T) { func TestInstallRegistryFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, + _, err := ExecuteCommand(rootCmd, cmdInstall, "--registry", "registry", "--organization", "organization", "--registry-insecure", @@ -273,7 +272,7 @@ func TestInstallRegistryFlag(t *testing.T) { func TestInstallRegistryWithAuthFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, + _, err := ExecuteCommand(rootCmd, cmdInstall, "--registry-auth-password", "authPassword", "--registry-auth-server", "authServer", "--registry-auth-username", "authUsername") @@ -285,56 +284,56 @@ func TestInstallRegistryWithAuthFlag(t *testing.T) { func TestInstallRuntimeVersionFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--runtime-version", "1.3.0") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--runtime-version", "1.3.0") require.NoError(t, err) assert.Equal(t, "1.3.0", installCmdOptions.RuntimeVersion) } func TestInstallSaveFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--save") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--save") require.NoError(t, err) assert.True(t, installCmdOptions.Save) } func TestInstallSkipClusterSetupFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--skip-cluster-setup") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--skip-cluster-setup") require.NoError(t, err) assert.True(t, installCmdOptions.SkipClusterSetup) } func TestInstallSkipOperatorSetupFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--skip-operator-setup") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--skip-operator-setup") require.NoError(t, err) assert.True(t, installCmdOptions.SkipOperatorSetup) } func TestInstallSkipRegistrySetupFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--skip-registry-setup") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--skip-registry-setup") require.NoError(t, err) assert.True(t, installCmdOptions.SkipRegistrySetup) } func TestInstallSkipDefaultKameletsSetupFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--skip-default-kamelets-setup") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--skip-default-kamelets-setup") require.NoError(t, err) assert.True(t, installCmdOptions.SkipDefaultKameletsSetup) } func TestInstallTraitProfileFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--trait-profile", "someString") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--trait-profile", "someString") require.NoError(t, err) assert.Equal(t, "someString", installCmdOptions.TraitProfile) } func TestInstallWaitFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--wait") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--wait") require.NoError(t, err) assert.True(t, installCmdOptions.Wait) } @@ -380,7 +379,7 @@ func TestDecodeMavenSettings(t *testing.T) { func TestInstallTolerationFlag(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, + _, err := ExecuteCommand(rootCmd, cmdInstall, "--toleration", "key1=value1:NoSchedule", "--toleration", "key2=value2:NoExecute") require.NoError(t, err) @@ -390,7 +389,7 @@ func TestInstallTolerationFlag(t *testing.T) { func TestInstallMavenExtension(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, + _, err := ExecuteCommand(rootCmd, cmdInstall, "--maven-extension", "fi.yle.tools:aws-maven:1.4.2") require.NoError(t, err) assert.Equal(t, "fi.yle.tools:aws-maven:1.4.2", installCmdOptions.MavenExtensions[0]) @@ -398,63 +397,63 @@ func TestInstallMavenExtension(t *testing.T) { func TestInstallInfoLogging(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall) + _, err := ExecuteCommand(rootCmd, cmdInstall) require.NoError(t, err) assert.Equal(t, "info", installCmdOptions.LogLevel) } func TestInstallInfoLogging1(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "-z", "0") + _, err := ExecuteCommand(rootCmd, cmdInstall, "-z", "0") require.NoError(t, err) assert.Equal(t, "0", installCmdOptions.LogLevel) } func TestInstallInfoLogging2(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--log-level", "0") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--log-level", "0") require.NoError(t, err) assert.Equal(t, "0", installCmdOptions.LogLevel) } func TestInstallInfoLogging3(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "-z", "info") + _, err := ExecuteCommand(rootCmd, cmdInstall, "-z", "info") require.NoError(t, err) assert.Equal(t, "info", installCmdOptions.LogLevel) } func TestInstallInfoLogging4(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--log-level", "info") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--log-level", "info") require.NoError(t, err) assert.Equal(t, "info", installCmdOptions.LogLevel) } func TestInstallDebugLogging1(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "-z", "1") + _, err := ExecuteCommand(rootCmd, cmdInstall, "-z", "1") require.NoError(t, err) assert.Equal(t, "1", installCmdOptions.LogLevel) } func TestInstallDebugLogging2(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--log-level", "1") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--log-level", "1") require.NoError(t, err) assert.Equal(t, "1", installCmdOptions.LogLevel) } func TestInstallDebugLogging3(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "-z", "debug") + _, err := ExecuteCommand(rootCmd, cmdInstall, "-z", "debug") require.NoError(t, err) assert.Equal(t, "debug", installCmdOptions.LogLevel) } func TestInstallDebugLogging4(t *testing.T) { installCmdOptions, rootCmd, _ := initializeInstallCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdInstall, "--log-level", "debug") + _, err := ExecuteCommand(rootCmd, cmdInstall, "--log-level", "debug") require.NoError(t, err) assert.Equal(t, "debug", installCmdOptions.LogLevel) } diff --git a/pkg/cmd/kamelet_add_repo_test.go b/pkg/cmd/kamelet_add_repo_test.go index f2f2aa6f0d..faa663dc76 100644 --- a/pkg/cmd/kamelet_add_repo_test.go +++ b/pkg/cmd/kamelet_add_repo_test.go @@ -24,7 +24,6 @@ import ( "github.com/stretchr/testify/require" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" ) const cmdKameletAddRepo = "add-repo" @@ -49,20 +48,20 @@ func addTestKameletAddRepoCmd(options RootCmdOptions, rootCmd *cobra.Command) *k kameletAddRepoCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - kameletAddRepoCmd.Args = test.ArbitraryArgs + kameletAddRepoCmd.Args = ArbitraryArgs rootCmd.AddCommand(kameletAddRepoCmd) return kameletAddRepoOptions } func TestKameletAddRepoNoFlag(t *testing.T) { _, rootCmd, _ := initializeKameletAddRepoCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdKameletAddRepo, "foo") + _, err := ExecuteCommand(rootCmd, cmdKameletAddRepo, "foo") require.NoError(t, err) } func TestKameletAddRepoNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeKameletAddRepoCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdKameletAddRepo, "--nonExistingFlag", "foo") + _, err := ExecuteCommand(rootCmd, cmdKameletAddRepo, "--nonExistingFlag", "foo") require.Error(t, err) } diff --git a/pkg/cmd/kamelet_remove_repo_test.go b/pkg/cmd/kamelet_remove_repo_test.go index 8b0d06acf7..10957ef6ad 100644 --- a/pkg/cmd/kamelet_remove_repo_test.go +++ b/pkg/cmd/kamelet_remove_repo_test.go @@ -25,7 +25,6 @@ import ( "github.com/stretchr/testify/require" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" ) const cmdKameletRemoveRepo = "remove-repo" @@ -50,20 +49,20 @@ func addTestKameletRemoveRepoCmd(options RootCmdOptions, rootCmd *cobra.Command) kameletRemoveRepoCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - kameletRemoveRepoCmd.Args = test.ArbitraryArgs + kameletRemoveRepoCmd.Args = ArbitraryArgs rootCmd.AddCommand(kameletRemoveRepoCmd) return kameletRemoveRepoOptions } func TestKameletRemoveRepoNoFlag(t *testing.T) { _, rootCmd, _ := initializeKameletRemoveRepoCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdKameletRemoveRepo, "foo") + _, err := ExecuteCommand(rootCmd, cmdKameletRemoveRepo, "foo") require.NoError(t, err) } func TestKameletRemoveRepoNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeKameletRemoveRepoCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdKameletRemoveRepo, "--nonExistingFlag", "foo") + _, err := ExecuteCommand(rootCmd, cmdKameletRemoveRepo, "--nonExistingFlag", "foo") require.Error(t, err) } diff --git a/pkg/cmd/kit_create_test.go b/pkg/cmd/kit_create_test.go index 520dda50a0..2aa1d43cfa 100644 --- a/pkg/cmd/kit_create_test.go +++ b/pkg/cmd/kit_create_test.go @@ -20,7 +20,6 @@ package cmd import ( "testing" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -48,20 +47,20 @@ func addTestKitCreateCmd(options RootCmdOptions, rootCmd *cobra.Command) *kitCre kitCreateCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - kitCreateCmd.Args = test.ArbitraryArgs + kitCreateCmd.Args = ArbitraryArgs rootCmd.AddCommand(kitCreateCmd) return kitCreateOptions } func TestKitCreateNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, subCmdKit, "--nonExistingFlag") require.Error(t, err) } func TestKitCreateConfigMapFlag(t *testing.T) { kitCreateCmdOptions, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, + _, err := ExecuteCommand(rootCmd, subCmdKit, "--configmap", "someString1", "--configmap", "someString2") require.NoError(t, err) @@ -72,7 +71,7 @@ func TestKitCreateConfigMapFlag(t *testing.T) { func TestKitCreateDependencyFlag(t *testing.T) { kitCreateCmdOptions, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, + _, err := ExecuteCommand(rootCmd, subCmdKit, "--dependency", "someString1", "--dependency", "someString2") require.NoError(t, err) @@ -83,14 +82,14 @@ func TestKitCreateDependencyFlag(t *testing.T) { func TestKitCreateImageFlag(t *testing.T) { kitCreateCmdOptions, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, "--image", "someString") + _, err := ExecuteCommand(rootCmd, subCmdKit, "--image", "someString") require.NoError(t, err) assert.Equal(t, "someString", kitCreateCmdOptions.Image) } func TestKitCreatePropertyFlag(t *testing.T) { kitCreateCmdOptions, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, + _, err := ExecuteCommand(rootCmd, subCmdKit, "--property", "someString1", "--property", "someString2") require.NoError(t, err) @@ -101,7 +100,7 @@ func TestKitCreatePropertyFlag(t *testing.T) { func TestKitCreateRepositoryFlag(t *testing.T) { kitCreateCmdOptions, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, + _, err := ExecuteCommand(rootCmd, subCmdKit, "--repository", "someString1", "--repository", "someString2") require.NoError(t, err) @@ -112,7 +111,7 @@ func TestKitCreateRepositoryFlag(t *testing.T) { func TestKitCreateSecretFlag(t *testing.T) { kitCreateCmdOptions, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, + _, err := ExecuteCommand(rootCmd, subCmdKit, "--secret", "someString1", "--secret", "someString2") require.NoError(t, err) @@ -123,7 +122,7 @@ func TestKitCreateSecretFlag(t *testing.T) { func TestKitCreateTraitFlag(t *testing.T) { kitCreateCmdOptions, rootCmd, _ := initializeKitCreateCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, subCmdKit, + _, err := ExecuteCommand(rootCmd, subCmdKit, "--trait", "someString1", "--trait", "someString2") require.NoError(t, err) diff --git a/pkg/cmd/log_test.go b/pkg/cmd/log_test.go index 2046f640ad..2cb93d0cfa 100644 --- a/pkg/cmd/log_test.go +++ b/pkg/cmd/log_test.go @@ -19,8 +19,6 @@ package cmd import ( "testing" - - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestLogsAlias(t *testing.T) { @@ -30,7 +28,7 @@ func TestLogsAlias(t *testing.T) { kamelTestPostAddCommandInit(t, rootCommand, options) - _, err := test.ExecuteCommand(rootCommand, "logs") + _, err := ExecuteCommand(rootCommand, "logs") // in case of error we expect this to be the log default message if err != nil && err.Error() != "log expects an integration name argument" { diff --git a/pkg/cmd/operator_test.go b/pkg/cmd/operator_test.go index 6ffd29f50c..c45df0982f 100644 --- a/pkg/cmd/operator_test.go +++ b/pkg/cmd/operator_test.go @@ -20,7 +20,6 @@ package cmd import ( "testing" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" @@ -50,14 +49,14 @@ func addTestOperatorCmd(options RootCmdOptions, rootCmd *cobra.Command) *operato operatorCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - operatorCmd.Args = test.ArbitraryArgs + operatorCmd.Args = ArbitraryArgs rootCmd.AddCommand(operatorCmd) return operatorOptions } func TestOperatorNoFlag(t *testing.T) { operatorCmdOptions, rootCmd, _ := initializeOperatorCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdOperator) + _, err := ExecuteCommand(rootCmd, cmdOperator) require.NoError(t, err) // Check default expected values assert.Equal(t, int32(8081), operatorCmdOptions.HealthPort) @@ -66,20 +65,20 @@ func TestOperatorNoFlag(t *testing.T) { func TestOperatorNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeOperatorCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdOperator, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, cmdOperator, "--nonExistingFlag") require.Error(t, err) } func TestOperatorHealthPortFlag(t *testing.T) { operatorCmdOptions, rootCmd, _ := initializeOperatorCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdOperator, "--health-port", "7171") + _, err := ExecuteCommand(rootCmd, cmdOperator, "--health-port", "7171") require.NoError(t, err) assert.Equal(t, int32(7171), operatorCmdOptions.HealthPort) } func TestOperatorMonitoringPortFlag(t *testing.T) { operatorCmdOptions, rootCmd, _ := initializeOperatorCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdOperator, "--monitoring-port", "7172") + _, err := ExecuteCommand(rootCmd, cmdOperator, "--monitoring-port", "7172") require.NoError(t, err) assert.Equal(t, int32(7172), operatorCmdOptions.MonitoringPort) } diff --git a/pkg/cmd/promote_test.go b/pkg/cmd/promote_test.go index f1b4be58bc..03a942f994 100644 --- a/pkg/cmd/promote_test.go +++ b/pkg/cmd/promote_test.go @@ -23,9 +23,9 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/platform" "github.com/apache/camel-k/v2/pkg/util/defaults" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -39,7 +39,7 @@ const cmdPromote = "promote" // nolint: unparam func initializePromoteCmdOptions(t *testing.T, initObjs ...runtime.Object) (*promoteCmdOptions, *cobra.Command, RootCmdOptions) { t.Helper() - fakeClient, err := test.NewFakeClient(initObjs...) + fakeClient, err := internal.NewFakeClient(initObjs...) require.NoError(t, err) options, rootCmd := kamelTestPreAddCommandInitWithClient(fakeClient) options.Namespace = "default" @@ -51,7 +51,7 @@ func initializePromoteCmdOptions(t *testing.T, initObjs ...runtime.Object) (*pro func addTestPromoteCmd(options RootCmdOptions, rootCmd *cobra.Command) *promoteCmdOptions { promoteCmd, promoteOptions := newCmdPromote(&options) - promoteCmd.Args = test.ArbitraryArgs + promoteCmd.Args = ArbitraryArgs rootCmd.AddCommand(promoteCmd) return promoteOptions } @@ -70,7 +70,7 @@ func TestIntegrationNotCompatible(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) _, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - _, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-n", "default") + _, err := ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-n", "default") require.Error(t, err) assert.Equal(t, fmt.Sprintf("could not verify operators compatibility: source (%s) and destination (0.0.1) Camel K operator versions are not compatible", defaults.Version), @@ -92,7 +92,7 @@ func TestIntegrationDryRun(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) promoteCmdOptions, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 @@ -148,7 +148,7 @@ func TestPipeDryRun(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) promoteCmdOptions, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultKB, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 @@ -201,7 +201,7 @@ func TestIntegrationWithMetadataDryRun(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) promoteCmdOptions, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 @@ -248,7 +248,7 @@ func TestPipeWithMetadataDryRun(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) promoteCmdOptions, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultKB, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 @@ -285,7 +285,7 @@ func TestItImageOnly(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) _, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-i", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-i", "-n", "default") require.NoError(t, err) assert.Equal(t, "my-special-image\n", output) } @@ -305,7 +305,7 @@ func TestPipeImageOnly(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) _, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultKB, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-i", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-i", "-n", "default") require.NoError(t, err) assert.Equal(t, "my-special-image\n", output) } @@ -325,7 +325,7 @@ func TestIntegrationToOperatorId(t *testing.T) { // Verify default (missing) operator Id promoteCmdOptions, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "-x", "my-prod-operator", "-o", "yaml", "--to", "prod") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "-x", "my-prod-operator", "-o", "yaml", "--to", "prod") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 @@ -351,7 +351,7 @@ status: {} "camel.apache.org/operator.id": "camel-k", } promoteCmdOptions, promoteCmd, _ = initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err = test.ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "-x", "my-prod-operator", "-o", "yaml", "--to", "prod") + output, err = ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "-x", "my-prod-operator", "-o", "yaml", "--to", "prod") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 @@ -395,7 +395,7 @@ func TestIntegrationWithSavedTraitsDryRun(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) promoteCmdOptions, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-it-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 @@ -440,7 +440,7 @@ func TestPipeWithSavedTraitsDryRun(t *testing.T) { dstCatalog := createTestCamelCatalog(dstPlatform) promoteCmdOptions, promoteCmd, _ := initializePromoteCmdOptions(t, &srcPlatform, &dstPlatform, &defaultKB, &defaultIntegration, &defaultKit, &srcCatalog, &dstCatalog) - output, err := test.ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") + output, err := ExecuteCommand(promoteCmd, cmdPromote, "my-kb-test", "--to", "prod-namespace", "-o", "yaml", "-n", "default") assert.Equal(t, "yaml", promoteCmdOptions.OutputFormat) require.NoError(t, err) assert.Equal(t, `apiVersion: camel.apache.org/v1 diff --git a/pkg/cmd/rebuild_test.go b/pkg/cmd/rebuild_test.go index 5d91422990..4b6c97cba1 100644 --- a/pkg/cmd/rebuild_test.go +++ b/pkg/cmd/rebuild_test.go @@ -20,7 +20,6 @@ package cmd import ( "testing" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -48,20 +47,20 @@ func addTestRebuildCmd(options RootCmdOptions, rootCmd *cobra.Command) *rebuildC rebuildCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - rebuildCmd.Args = test.ArbitraryArgs + rebuildCmd.Args = ArbitraryArgs rootCmd.AddCommand(rebuildCmd) return rebuildOptions } func TestRebuildNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeRebuildCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRebuild, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, cmdRebuild, "--nonExistingFlag") require.Error(t, err) } func TestRebuildAllFlag(t *testing.T) { rebuildCmdOptions, rootCmd, _ := initializeRebuildCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRebuild, "--all") + _, err := ExecuteCommand(rootCmd, cmdRebuild, "--all") require.NoError(t, err) assert.True(t, rebuildCmdOptions.RebuildAll) } diff --git a/pkg/cmd/root_test.go b/pkg/cmd/root_test.go index 40cbead6ac..00fdde40f9 100644 --- a/pkg/cmd/root_test.go +++ b/pkg/cmd/root_test.go @@ -24,7 +24,7 @@ import ( "testing" "github.com/apache/camel-k/v2/pkg/client" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -45,12 +45,12 @@ func kamelTestPreAddCommandInitWithClient(client client.Client) (*RootCmdOptions _client: client, } rootCmd := kamelPreAddCommandInit(&options) - rootCmd.Run = test.EmptyRun + rootCmd.Run = EmptyRun return &options, rootCmd } func kamelTestPreAddCommandInit() (*RootCmdOptions, *cobra.Command) { - fakeClient, _ := test.NewFakeClient() + fakeClient, _ := internal.NewFakeClient() return kamelTestPreAddCommandInitWithClient(fakeClient) } @@ -63,7 +63,7 @@ func TestLoadFromEnvVar(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) defer teardown(t, runCmdOptions.Flags) - _, err := test.ExecuteCommand(rootCmd, "run", "route.java") + _, err := ExecuteCommand(rootCmd, "run", "route.java") if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -83,7 +83,7 @@ func TestLoadFromFile(t *testing.T) { runCmdOptions.Flags.SetConfigType("properties") readViperConfigFromBytes(t, runCmdOptions.Flags, propertiesFile) - _, err := test.ExecuteCommand(rootCmd, "run", "route.java") + _, err := ExecuteCommand(rootCmd, "run", "route.java") if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -107,7 +107,7 @@ func TestPrecedenceEnvVarOverFile(t *testing.T) { viper.SetConfigType("properties") readViperConfigFromBytes(t, runCmdOptions.Flags, propertiesFile) - _, err := test.ExecuteCommand(rootCmd, "run", "route.java") + _, err := ExecuteCommand(rootCmd, "run", "route.java") if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -131,7 +131,7 @@ func TestPrecedenceCommandLineOverEverythingElse(t *testing.T) { viper.SetConfigType("properties") readViperConfigFromBytes(t, runCmdOptions.Flags, propertiesFile) - _, err := test.ExecuteCommand(rootCmd, "run", "route.java", "--env", "VAR3=commandLine") + _, err := ExecuteCommand(rootCmd, "run", "route.java", "--env", "VAR3=commandLine") if err != nil { t.Fatalf("Unexpected error: %v", err) } diff --git a/pkg/cmd/run_test.go b/pkg/cmd/run_test.go index dfee3e71cc..2a4087058c 100644 --- a/pkg/cmd/run_test.go +++ b/pkg/cmd/run_test.go @@ -27,10 +27,10 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/platform" "github.com/apache/camel-k/v2/pkg/trait" "github.com/apache/camel-k/v2/pkg/util/defaults" - "github.com/apache/camel-k/v2/pkg/util/test" "k8s.io/utils/ptr" "github.com/spf13/cobra" @@ -71,7 +71,7 @@ func initializeRunCmdOptionsWithOutput(t *testing.T) (*runCmdOptions, *cobra.Com defaultIntegrationPlatform := v1.NewIntegrationPlatform("default", platform.DefaultPlatformName) c := v1.NewCamelCatalog(defaultIntegrationPlatform.Namespace, defaults.DefaultRuntimeVersion) c.Spec = v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Provider: defaultIntegrationPlatform.Status.Build.RuntimeProvider, Version: defaultIntegrationPlatform.Status.Build.RuntimeVersion}} - fakeClient, _ := test.NewFakeClient(&defaultIntegrationPlatform, &c) + fakeClient, _ := internal.NewFakeClient(&defaultIntegrationPlatform, &c) options, rootCmd := kamelTestPreAddCommandInitWithClient(fakeClient) runCmdOptions := addTestRunCmdWithOutput(*options, rootCmd) @@ -89,7 +89,7 @@ func addTestRunCmd(options RootCmdOptions, rootCmd *cobra.Command) *runCmdOption runCmd.PostRunE = func(c *cobra.Command, args []string) error { return nil } - runCmd.Args = test.ArbitraryArgs + runCmd.Args = ArbitraryArgs rootCmd.AddCommand(runCmd) return runOptions } @@ -97,14 +97,14 @@ func addTestRunCmd(options RootCmdOptions, rootCmd *cobra.Command) *runCmdOption func addTestRunCmdWithOutput(options RootCmdOptions, rootCmd *cobra.Command) *runCmdOptions { // add a testing version of run Command with output runCmd, runOptions := newCmdRun(&options) - runCmd.Args = test.ArbitraryArgs + runCmd.Args = ArbitraryArgs rootCmd.AddCommand(runCmd) return runOptions } func TestRunNoFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, integrationSource) require.NoError(t, err) // Check default expected values assert.False(t, runCmdOptions.Wait) @@ -118,20 +118,20 @@ func TestRunNoFlag(t *testing.T) { func TestRunNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--nonExistingFlag", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--nonExistingFlag", integrationSource) require.Error(t, err) } func TestRunCompressionFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--compression", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--compression", integrationSource) require.NoError(t, err) assert.True(t, runCmdOptions.Compression) } func TestRunDependencyFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--dependency", "dependency1", "--dependency", "dependency2", "--dependency", "dependency3", @@ -145,14 +145,14 @@ func TestRunDependencyFlag(t *testing.T) { func TestRunDevFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--dev", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--dev", integrationSource) require.NoError(t, err) assert.True(t, runCmdOptions.Dev) } func TestRunDevModeOutputFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--dev", "-o", "yaml", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--dev", "-o", "yaml", integrationSource) assert.True(t, runCmdOptions.Dev) assert.Equal(t, "yaml", runCmdOptions.OutputFormat) require.Error(t, err) @@ -162,7 +162,7 @@ func TestRunDevModeOutputFlag(t *testing.T) { func TestRunEnvFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--env", "env1", "--env", "env2", integrationSource) @@ -174,14 +174,14 @@ func TestRunEnvFlag(t *testing.T) { func TestRunKitFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--kit", "myKit", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--kit", "myKit", integrationSource) require.NoError(t, err) assert.Equal(t, "myKit", runCmdOptions.IntegrationKit) } func TestRunLabelFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--label", "label1=l1", "--label", "label2=l2", "--label", "label3=l3", @@ -195,20 +195,20 @@ func TestRunLabelFlag(t *testing.T) { func TestRunLabelWrongFormatFlag(t *testing.T) { _, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--label", "label1", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--label", "label1", integrationSource) require.Error(t, err) } func TestRunLogsFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--logs", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--logs", integrationSource) require.NoError(t, err) assert.True(t, runCmdOptions.Logs) } func TestRunMavenRepositoryFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--maven-repository", "repo1", "--maven-repository", "repo2", "--maven-repository", "repo3", @@ -222,14 +222,14 @@ func TestRunMavenRepositoryFlag(t *testing.T) { func TestRunNameFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--name", "myIntegration", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--name", "myIntegration", integrationSource) require.NoError(t, err) assert.Equal(t, "myIntegration", runCmdOptions.IntegrationName) } func TestRunOpenApiFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--open-api", "configmap:oapi2", integrationSource) require.NoError(t, err) @@ -239,7 +239,7 @@ func TestRunOpenApiFlag(t *testing.T) { func TestRunOpenApiInvalidFlag(t *testing.T) { _, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--open-api", "secret:oapi1", "--open-api", "oapi2", integrationSource) @@ -248,21 +248,21 @@ func TestRunOpenApiInvalidFlag(t *testing.T) { func TestRunOutputFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "-o", "yaml", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "-o", "yaml", integrationSource) require.NoError(t, err) assert.Equal(t, "yaml", runCmdOptions.OutputFormat) } func TestRunProfileFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--profile", "myProfile", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--profile", "myProfile", integrationSource) require.NoError(t, err) assert.Equal(t, "myProfile", runCmdOptions.Profile) } func TestRunPropertyFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--property", "property1", "--property", "property2", "--property", "property3", @@ -377,7 +377,7 @@ func TestRunProperty(t *testing.T) { func TestRunResourceFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--resource", "res1", "--resource", "res2", integrationSource) @@ -389,14 +389,14 @@ func TestRunResourceFlag(t *testing.T) { func TestRunSaveFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--save", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--save", integrationSource) require.NoError(t, err) assert.True(t, runCmdOptions.Save) } func TestRunSourceFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--source", "source1", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--source", "source1", integrationSource) require.NoError(t, err) assert.Len(t, runCmdOptions.Sources, 1) assert.Equal(t, "source1", runCmdOptions.Sources[0]) @@ -404,14 +404,14 @@ func TestRunSourceFlag(t *testing.T) { func TestRunSyncFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--sync", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--sync", integrationSource) require.NoError(t, err) assert.True(t, runCmdOptions.Sync) } func TestRunExistingTraitFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--trait", "jvm.enabled", "--trait", "logging.enabled", integrationSource) @@ -423,7 +423,7 @@ func TestRunExistingTraitFlag(t *testing.T) { func TestRunMissingTraitFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--trait", "bogus.missing", integrationSource) require.Error(t, err) @@ -434,7 +434,7 @@ func TestRunMissingTraitFlag(t *testing.T) { func TestConfigureTraits(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, "run", + _, err := ExecuteCommand(rootCmd, "run", "--trait", "affinity.pod-affinity=false", "--trait", "environment.container-meta=false", "--trait", "prometheus.pod-monitor=false", @@ -472,14 +472,14 @@ func assertTraitConfiguration(t *testing.T, trait interface{}, expected interfac func TestRunUseFlowsFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, "--use-flows=false", integrationSource) + _, err := ExecuteCommand(rootCmd, cmdRun, "--use-flows=false", integrationSource) require.NoError(t, err) assert.False(t, runCmdOptions.UseFlows) } func TestRunVolumeFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "-v", "pvcname:/container1/path", "-v", "pvcname:/container2/path", integrationSource) @@ -491,7 +491,7 @@ func TestRunVolumeFlag(t *testing.T) { func TestRunVolumeFlagWrongPVCFormat(t *testing.T) { _, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "-v", "pvcname", "-v", "pvcname/container2/path", integrationSource) @@ -500,7 +500,7 @@ func TestRunVolumeFlagWrongPVCFormat(t *testing.T) { func TestRunBuildPropertyFlag(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdRun, + _, err := ExecuteCommand(rootCmd, cmdRun, "--build-property", "build-prop1=val1", "--build-property", "build-prop2=val2", integrationSource) @@ -591,7 +591,7 @@ func TestOutputYaml(t *testing.T) { fileName := filepath.Base(tmpFile.Name()) runCmdOptions, runCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml") + output, err := ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml") assert.Equal(t, "yaml", runCmdOptions.OutputFormat) require.NoError(t, err) @@ -625,7 +625,7 @@ func TestTrait(t *testing.T) { fileName := filepath.Base(tmpFile.Name()) runCmdOptions, runCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml", "-t", "mount.configs=configmap:my-cm") + output, err := ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml", "-t", "mount.configs=configmap:my-cm") assert.Equal(t, "yaml", runCmdOptions.OutputFormat) require.NoError(t, err) @@ -661,7 +661,7 @@ func TestMissingTrait(t *testing.T) { require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(TestSrcContent), 0o400)) runCmdOptions, runCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml", "-t", "bogus.fail=i-must-fail") + output, err := ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml", "-t", "bogus.fail=i-must-fail") assert.Equal(t, "yaml", runCmdOptions.OutputFormat) assert.Equal(t, "Error: trait bogus does not exist in catalog\n", output) require.Error(t, err) @@ -711,7 +711,7 @@ func TestIntegrationServiceAccountName(t *testing.T) { require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(TestSrcContent), 0o400)) _, runCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml", "--service-account", "my-service-account") + output, err := ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml", "--service-account", "my-service-account") require.NoError(t, err) assert.Contains(t, output, "serviceAccountName: my-service-account") @@ -739,7 +739,7 @@ func TestFileProperties(t *testing.T) { assert.Nil(t, tmpFile.Close()) require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(TestSrcContent), 0o400)) _, runCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), + output, err := ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-p", "file:"+tmpFile1.Name(), "-o", "yaml", ) @@ -769,7 +769,7 @@ func TestPropertyShouldNotExpand(t *testing.T) { assert.Nil(t, tmpFile.Close()) require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(TestSrcContent), 0o400)) _, runCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), + output, err := ExecuteCommand(runCmd, cmdRun, tmpFile.Name(), "-o", "yaml", "-p", "runtimeProp=${value}", "--build-property", "buildProp=${value}", @@ -793,19 +793,19 @@ func TestRunOutput(t *testing.T) { require.NoError(t, os.WriteFile(tmpFile1.Name(), []byte(yamlIntegration), 0o400)) _, rootCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(rootCmd, cmdRun, tmpFile1.Name()) + output, err := ExecuteCommand(rootCmd, cmdRun, tmpFile1.Name()) _, fileName := filepath.Split(tmpFile1.Name()) integrationName := strings.TrimSuffix(fileName, filepath.Ext(fileName)) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" created\n", integrationName), output) - output, err = test.ExecuteCommand(rootCmd, cmdRun, tmpFile1.Name()) + output, err = ExecuteCommand(rootCmd, cmdRun, tmpFile1.Name()) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" unchanged\n", integrationName), output) require.NoError(t, os.WriteFile(tmpFile1.Name(), []byte(strings.Replace(yamlIntegration, "Hello", "Hi", 1)), 0o400)) assert.Nil(t, tmpFile1.Sync()) - output, err = test.ExecuteCommand(rootCmd, cmdRun, tmpFile1.Name()) + output, err = ExecuteCommand(rootCmd, cmdRun, tmpFile1.Name()) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" updated\n", integrationName), output) } @@ -840,7 +840,7 @@ func TestRunGlob(t *testing.T) { file := fmt.Sprintf("%s%c%s*", dir, os.PathSeparator, "camel-k-*") // = dir/camel-k-* - output, err := test.ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) + output, err := ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" created\n", integrationName), output) } @@ -875,7 +875,7 @@ func TestRunGlobAllFiles(t *testing.T) { file := fmt.Sprintf("%s%c*", dir, os.PathSeparator) // = dir/* - output, err := test.ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) + output, err := ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" created\n", integrationName), output) } @@ -902,11 +902,11 @@ func TestRunGlobChange(t *testing.T) { file := fmt.Sprintf("%s%c%s", dir, os.PathSeparator, "camel-k-*") - output, err := test.ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) + output, err := ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" created\n", integrationName), output) - output, err = test.ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) + output, err = ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" unchanged\n", integrationName), output) @@ -918,7 +918,7 @@ func TestRunGlobChange(t *testing.T) { assert.Nil(t, tmpFile2.Sync()) require.NoError(t, os.WriteFile(tmpFile2.Name(), []byte(yamlIntegration), 0o400)) - output, err = test.ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) + output, err = ExecuteCommand(rootCmd, cmdRun, "--name", integrationName, file) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Integration \"%s\" updated\n", integrationName), output) } @@ -930,13 +930,13 @@ func TestRunOutputWithoutKubernetesCluster(t *testing.T) { runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) runCmdOptions._client = nil // remove the default fake client which can bypass this test runCmdOptions.KubeConfig = tmpFile.Name() - _, err = test.ExecuteCommand(rootCmd, cmdRun, "-o", "yaml", integrationSource) + _, err = ExecuteCommand(rootCmd, cmdRun, "-o", "yaml", integrationSource) require.NoError(t, err) } func TestSelfManagedBuildIntegration(t *testing.T) { runCmdOptions, runCmd, _ := initializeRunCmdOptionsWithOutput(t) - output, err := test.ExecuteCommand(runCmd, cmdRun, "--image", "docker.io/my-org/my-app:1.0.0", "-o", "yaml", "-t", "mount.configs=configmap:my-cm") + output, err := ExecuteCommand(runCmd, cmdRun, "--image", "docker.io/my-org/my-app:1.0.0", "-o", "yaml", "-t", "mount.configs=configmap:my-cm") assert.Equal(t, "yaml", runCmdOptions.OutputFormat) require.NoError(t, err) diff --git a/pkg/cmd/source/content.go b/pkg/cmd/source/content.go index 57f3fc8771..fc15451f89 100644 --- a/pkg/cmd/source/content.go +++ b/pkg/cmd/source/content.go @@ -24,9 +24,7 @@ import ( "net/http" "net/url" "regexp" - "strings" - "github.com/apache/camel-k/v2/pkg/util" "github.com/apache/camel-k/v2/pkg/util/gzip" ) @@ -37,50 +35,6 @@ const ( Kilobyte = 1 << 10 ) -func LoadRawContent(ctx context.Context, source string) ([]byte, string, error) { - var content []byte - var err error - - ok, err := IsLocalAndFileExists(source) - if err != nil { - return nil, "", err - } - - if ok { - content, err = util.ReadFile(source) - } else { - var u *url.URL - u, err = url.Parse(source) - if err != nil { - return nil, "", err - } - - switch u.Scheme { - case "github": - content, err = loadContentGitHub(ctx, u) - case "http": - content, err = loadContentHTTP(ctx, u) - case "https": - content, err = loadContentHTTP(ctx, u) - default: - return nil, "", fmt.Errorf("missing file or unsupported scheme %s", u.Scheme) - } - } - - if err != nil { - return nil, "", err - } - - contentType := http.DetectContentType(content) - return content, contentType, nil -} - -func IsBinary(contentType string) bool { - // According the http.DetectContentType method - // also json and other "text" application mime types would be reported as text - return !strings.HasPrefix(contentType, "text") -} - func CompressToString(content []byte) (string, error) { bytes, err := gzip.CompressBase64(content) if err != nil { @@ -90,20 +44,6 @@ func CompressToString(content []byte) (string, error) { return string(bytes), nil } -func LoadTextContent(ctx context.Context, source string, base64Compression bool) (string, string, bool, error) { - content, contentType, err := LoadRawContent(ctx, source) - if err != nil { - return "", "", false, err - } - - if base64Compression { - base64Compressed, err := CompressToString(content) - return base64Compressed, contentType, true, err - } - - return string(content), contentType, false, nil -} - func loadContentHTTP(ctx context.Context, u fmt.Stringer) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { diff --git a/pkg/cmd/source/content_test.go b/pkg/cmd/source/content_test.go index 051245cff2..510e6f9435 100644 --- a/pkg/cmd/source/content_test.go +++ b/pkg/cmd/source/content_test.go @@ -23,86 +23,12 @@ import ( "net/http" "net/http/httptest" "net/url" - "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestRawContentFileMissing(t *testing.T) { - _, _, err := LoadRawContent(context.Background(), "dsadas") - require.Error(t, err) -} - -func TestRawBinaryContentType(t *testing.T) { - var tmpFile *os.File - var err error - if tmpFile, err = os.CreateTemp("", "camel-k-*.json"); err != nil { - t.Error(err) - } - require.NoError(t, tmpFile.Close()) - require.NoError(t, os.WriteFile(tmpFile.Name(), []byte{1, 2, 3, 4, 5, 6}, 0o400)) - - data, contentType, err := LoadRawContent(context.Background(), tmpFile.Name()) - require.NoError(t, err) - assert.Equal(t, []byte{1, 2, 3, 4, 5, 6}, data) - assert.True(t, IsBinary(contentType)) -} - -func TestRawApplicationContentType(t *testing.T) { - var tmpFile *os.File - var err error - if tmpFile, err = os.CreateTemp("", "camel-k-*.json"); err != nil { - t.Error(err) - } - require.NoError(t, tmpFile.Close()) - require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(`{"hello":"world"}`), 0o400)) - - data, contentType, err := LoadRawContent(context.Background(), tmpFile.Name()) - require.NoError(t, err) - assert.Equal(t, `{"hello":"world"}`, string(data)) - assert.False(t, IsBinary(contentType)) -} - -func TestTextContentType(t *testing.T) { - var tmpFile *os.File - var err error - if tmpFile, err = os.CreateTemp("", "camel-k-*.json"); err != nil { - t.Error(err) - } - require.NoError(t, tmpFile.Close()) - require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(`{"hello":"world"}`), 0o400)) - - data, contentType, compressed, err := LoadTextContent(context.Background(), tmpFile.Name(), false) - require.NoError(t, err) - assert.Equal(t, `{"hello":"world"}`, data) - assert.False(t, IsBinary(contentType)) - assert.False(t, compressed) -} - -func TestTextCompressed(t *testing.T) { - var tmpFile *os.File - var err error - if tmpFile, err = os.CreateTemp("", "camel-k-*.json"); err != nil { - t.Error(err) - } - assert.Nil(t, tmpFile.Close()) - require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(`{"hello":"world"}`), 0o400)) - - data, contentType, compressed, err := LoadTextContent(context.Background(), tmpFile.Name(), true) - require.NoError(t, err) - assert.NotEqual(t, `{"hello":"world"}`, data) - assert.False(t, IsBinary(contentType)) - assert.True(t, compressed) -} - -func TestIsBinary(t *testing.T) { - assert.True(t, IsBinary("image/jpeg")) - assert.True(t, IsBinary("application/zip")) - assert.False(t, IsBinary("text/plain")) -} - func TestContentHttp(t *testing.T) { expected := "the content" svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/cmd/uninstall_test.go b/pkg/cmd/uninstall_test.go index 6c20d90b27..8ab6f6ec5e 100644 --- a/pkg/cmd/uninstall_test.go +++ b/pkg/cmd/uninstall_test.go @@ -23,7 +23,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" ) @@ -33,7 +32,7 @@ func addTestUninstallCmd(options *RootCmdOptions, rootCmd *cobra.Command) *unins uninstallCmd.RunE = func(c *cobra.Command, args []string) error { return nil } - uninstallCmd.Args = test.ArbitraryArgs + uninstallCmd.Args = ArbitraryArgs rootCmd.AddCommand(uninstallCmd) return installOptions } @@ -45,7 +44,7 @@ func TestUninstallOlmFlags(t *testing.T) { kamelTestPostAddCommandInit(t, cmd, options) - _, err := test.ExecuteCommand(cmd, "uninstall", "--olm=false", "--olm-operator-name", "my-operator") + _, err := ExecuteCommand(cmd, "uninstall", "--olm=false", "--olm-operator-name", "my-operator") require.NoError(t, err) assert.False(t, uninstallCmdOptions.OlmEnabled) assert.Equal(t, "my-operator", uninstallCmdOptions.OlmOptions.OperatorName) @@ -58,7 +57,7 @@ func TestUninstallSkipFlags(t *testing.T) { kamelTestPostAddCommandInit(t, cmd, options) - _, err := test.ExecuteCommand(cmd, "uninstall", "--skip-crd", "--skip-cluster-roles", "--skip-integration-platform", "--skip-integration-profile") + _, err := ExecuteCommand(cmd, "uninstall", "--skip-crd", "--skip-cluster-roles", "--skip-integration-platform", "--skip-integration-profile") require.NoError(t, err) assert.True(t, uninstallCmdOptions.SkipCrd) assert.True(t, uninstallCmdOptions.SkipClusterRoles) @@ -73,7 +72,7 @@ func TestUninstallAllFlag(t *testing.T) { kamelTestPostAddCommandInit(t, cmd, options) - _, err := test.ExecuteCommand(cmd, "uninstall", "--all") + _, err := ExecuteCommand(cmd, "uninstall", "--all") require.NoError(t, err) assert.True(t, uninstallCmdOptions.SkipCrd) assert.True(t, uninstallCmdOptions.SkipClusterRoles) diff --git a/pkg/cmd/version_test.go b/pkg/cmd/version_test.go index dfd33a54b8..7e3cad3216 100644 --- a/pkg/cmd/version_test.go +++ b/pkg/cmd/version_test.go @@ -22,11 +22,11 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/platform" "k8s.io/apimachinery/pkg/runtime" "github.com/apache/camel-k/v2/pkg/util/defaults" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -38,7 +38,7 @@ const cmdVersion = "version" func initializeVersionCmdOptions(t *testing.T, initObjs ...runtime.Object) (*versionCmdOptions, *cobra.Command, RootCmdOptions) { t.Helper() - fakeClient, err := test.NewFakeClient(initObjs...) + fakeClient, err := internal.NewFakeClient(initObjs...) require.NoError(t, err) options, rootCmd := kamelTestPreAddCommandInitWithClient(fakeClient) versionCmdOptions := addTestVersionCmd(*options, rootCmd) @@ -50,34 +50,34 @@ func initializeVersionCmdOptions(t *testing.T, initObjs ...runtime.Object) (*ver func addTestVersionCmd(options RootCmdOptions, rootCmd *cobra.Command) *versionCmdOptions { // add a testing version of version Command versionCmd, versionOptions := newCmdVersion(&options) - versionCmd.Args = test.ArbitraryArgs + versionCmd.Args = ArbitraryArgs rootCmd.AddCommand(versionCmd) return versionOptions } func TestVersionNonExistingFlag(t *testing.T) { _, rootCmd, _ := initializeVersionCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdVersion, "--nonExistingFlag") + _, err := ExecuteCommand(rootCmd, cmdVersion, "--nonExistingFlag") require.Error(t, err) } func TestVersionClient(t *testing.T) { _, rootCmd, _ := initializeVersionCmdOptions(t) - output, err := test.ExecuteCommand(rootCmd, cmdVersion) + output, err := ExecuteCommand(rootCmd, cmdVersion) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Camel K Client %s\n", defaults.Version), output) } func TestVersionOperatorFlag(t *testing.T) { versionCmdOptions, rootCmd, _ := initializeVersionCmdOptions(t) - _, err := test.ExecuteCommand(rootCmd, cmdVersion, "--operator") + _, err := ExecuteCommand(rootCmd, cmdVersion, "--operator") require.NoError(t, err) assert.True(t, versionCmdOptions.Operator) } func TestVersionClientVerbose(t *testing.T) { versionCmdOptions, rootCmd, _ := initializeVersionCmdOptions(t) - output, err := test.ExecuteCommand(rootCmd, cmdVersion, "-v") + output, err := ExecuteCommand(rootCmd, cmdVersion, "-v") require.NoError(t, err) assert.True(t, versionCmdOptions.Verbose) assert.Equal(t, fmt.Sprintf("Camel K Client %s\nGit Commit: %s\n", defaults.Version, defaults.GitCommit), output) @@ -98,7 +98,7 @@ func TestOperatorVersionVerbose(t *testing.T) { } versionCmdOptions, rootCmd, _ := initializeVersionCmdOptions(t, &platform, &catalog) - output, err := test.ExecuteCommand(rootCmd, cmdVersion, "-v", "--operator") + output, err := ExecuteCommand(rootCmd, cmdVersion, "-v", "--operator") require.NoError(t, err) assert.True(t, versionCmdOptions.Verbose) assert.Contains(t, output, fmt.Sprintf("Camel K Operator %s\n", defaults.Version)) diff --git a/pkg/controller/build/build_monitor_test.go b/pkg/controller/build/build_monitor_test.go index d6b9b1b8f3..cb9d66c0d6 100644 --- a/pkg/controller/build/build_monitor_test.go +++ b/pkg/controller/build/build_monitor_test.go @@ -23,8 +23,8 @@ import ( "time" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -154,7 +154,7 @@ func TestMonitorSequentialBuilds(t *testing.T) { initObjs = append(initObjs, build) } - c, err := test.NewFakeClient(initObjs...) + c, err := internal.NewFakeClient(initObjs...) require.NoError(t, err) @@ -182,7 +182,7 @@ func TestMonitorSequentialBuilds(t *testing.T) { } func TestAllowBuildRequeue(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) @@ -366,7 +366,7 @@ func TestMonitorFIFOBuilds(t *testing.T) { initObjs = append(initObjs, build) } - c, err := test.NewFakeClient(initObjs...) + c, err := internal.NewFakeClient(initObjs...) require.NoError(t, err) @@ -606,7 +606,7 @@ func TestMonitorDependencyMatchingBuilds(t *testing.T) { initObjs = append(initObjs, build) } - c, err := test.NewFakeClient(initObjs...) + c, err := internal.NewFakeClient(initObjs...) require.NoError(t, err) diff --git a/pkg/controller/build/build_pod_test.go b/pkg/controller/build/build_pod_test.go index d2bc045876..7a41d3923c 100644 --- a/pkg/controller/build/build_pod_test.go +++ b/pkg/controller/build/build_pod_test.go @@ -22,7 +22,7 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -31,7 +31,7 @@ import ( func TestNewBuildPodConfiguration(t *testing.T) { ctx := context.TODO() - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) build := v1.Build{ diff --git a/pkg/controller/integration/build_kit_test.go b/pkg/controller/integration/build_kit_test.go index 1278a6423c..06500aa446 100644 --- a/pkg/controller/integration/build_kit_test.go +++ b/pkg/controller/integration/build_kit_test.go @@ -22,11 +22,11 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/digest" "github.com/apache/camel-k/v2/pkg/util/kubernetes" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -49,7 +49,7 @@ func TestCamelBuildKitDigestChanged(t *testing.T) { Digest: "NonMatchingDigest", }, } - c, err := test.NewFakeClient(it) + c, err := internal.NewFakeClient(it) require.NoError(t, err) a := buildKitAction{} @@ -104,7 +104,7 @@ func TestCamelBuildKitKitSetOnIntegration(t *testing.T) { hash, err := digest.ComputeForIntegration(it, nil, nil) require.NoError(t, err) it.Status.Digest = hash - c, err := test.NewFakeClient(it, ik) + c, err := internal.NewFakeClient(it, ik) require.NoError(t, err) a := buildKitAction{} @@ -120,7 +120,7 @@ func TestCamelBuildKitKitSetOnIntegration(t *testing.T) { // Move IntegrationKit phase to ready status it.Status.Phase = v1.IntegrationPhaseBuildingKit ik.Status.Phase = v1.IntegrationKitPhaseReady - c, err = test.NewFakeClient(it, ik) + c, err = internal.NewFakeClient(it, ik) require.NoError(t, err) a.InjectClient(c) handledIt, err = a.Handle(context.TODO(), it) @@ -130,7 +130,7 @@ func TestCamelBuildKitKitSetOnIntegration(t *testing.T) { // Move IntegrationKit phase to ready status it.Status.Phase = v1.IntegrationPhaseBuildingKit ik.Status.Phase = v1.IntegrationKitPhaseError - c, err = test.NewFakeClient(it, ik) + c, err = internal.NewFakeClient(it, ik) require.NoError(t, err) a.InjectClient(c) handledIt, err = a.Handle(context.TODO(), it) @@ -139,7 +139,7 @@ func TestCamelBuildKitKitSetOnIntegration(t *testing.T) { // Remove IntegrationKit it.Status.Phase = v1.IntegrationPhaseBuildingKit - c, err = test.NewFakeClient(it) + c, err = internal.NewFakeClient(it) require.NoError(t, err) a.InjectClient(c) handledIt, err = a.Handle(context.TODO(), it) @@ -220,7 +220,7 @@ func TestCamelBuildKitKitLookupExistingKit(t *testing.T) { hash, err := digest.ComputeForIntegration(it, nil, nil) require.NoError(t, err) it.Status.Digest = hash - c, err := test.NewFakeClient(it, ik, ip, catalog) + c, err := internal.NewFakeClient(it, ik, ip, catalog) require.NoError(t, err) a := buildKitAction{} @@ -237,7 +237,7 @@ func TestCamelBuildKitKitLookupExistingKit(t *testing.T) { // Found a matching kit (ready) it.Status.Phase = v1.IntegrationPhaseBuildingKit ik.Status.Phase = v1.IntegrationKitPhaseReady - c, err = test.NewFakeClient(it, ik, ip, catalog) + c, err = internal.NewFakeClient(it, ik, ip, catalog) require.NoError(t, err) a.InjectClient(c) handledIt, err = a.Handle(context.TODO(), it) @@ -249,7 +249,7 @@ func TestCamelBuildKitKitLookupExistingKit(t *testing.T) { // Found a matching kit (error) it.Status.Phase = v1.IntegrationPhaseBuildingKit ik.Status.Phase = v1.IntegrationKitPhaseError - c, err = test.NewFakeClient(it, ik, ip, catalog) + c, err = internal.NewFakeClient(it, ik, ip, catalog) require.NoError(t, err) a.InjectClient(c) handledIt, err = a.Handle(context.TODO(), it) @@ -333,7 +333,7 @@ func TestCamelBuildKitKitLookupNoMatchingKits(t *testing.T) { hash, err := digest.ComputeForIntegration(it, nil, nil) require.NoError(t, err) it.Status.Digest = hash - c, err := test.NewFakeClient(it, ik, ip, catalog) + c, err := internal.NewFakeClient(it, ik, ip, catalog) require.NoError(t, err) a := buildKitAction{} diff --git a/pkg/controller/integration/initialize_test.go b/pkg/controller/integration/initialize_test.go index f9d323f332..e956ae447b 100644 --- a/pkg/controller/integration/initialize_test.go +++ b/pkg/controller/integration/initialize_test.go @@ -27,8 +27,8 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -52,7 +52,7 @@ func TestCamelImportDeployment(t *testing.T) { Phase: v1.IntegrationPhaseInitialization, }, } - c, err := test.NewFakeClient(importedIt) + c, err := internal.NewFakeClient(importedIt) require.NoError(t, err) a := initializeAction{} @@ -92,7 +92,7 @@ func TestCamelImportCronJob(t *testing.T) { Phase: v1.IntegrationPhaseInitialization, }, } - c, err := test.NewFakeClient(importedIt) + c, err := internal.NewFakeClient(importedIt) require.NoError(t, err) a := initializeAction{} @@ -132,7 +132,7 @@ func TestCamelImportKnativeService(t *testing.T) { Phase: v1.IntegrationPhaseInitialization, }, } - c, err := test.NewFakeClient(importedIt) + c, err := internal.NewFakeClient(importedIt) require.NoError(t, err) a := initializeAction{} @@ -172,7 +172,7 @@ func TestCamelImportUnsupportedKind(t *testing.T) { Phase: v1.IntegrationPhaseInitialization, }, } - c, err := test.NewFakeClient(importedIt) + c, err := internal.NewFakeClient(importedIt) require.NoError(t, err) a := initializeAction{} diff --git a/pkg/controller/integration/kits_test.go b/pkg/controller/integration/kits_test.go index 9f10855263..a501e1a8c8 100644 --- a/pkg/controller/integration/kits_test.go +++ b/pkg/controller/integration/kits_test.go @@ -28,14 +28,14 @@ import ( "github.com/apache/camel-k/v2/pkg/client" "github.com/apache/camel-k/v2/pkg/trait" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestLookupKitForIntegration_DiscardKitsInError(t *testing.T) { - c, err := test.NewFakeClient( + c, err := internal.NewFakeClient( &v1.IntegrationPlatform{ TypeMeta: metav1.TypeMeta{ APIVersion: v1.SchemeGroupVersion.String(), @@ -118,7 +118,7 @@ func TestLookupKitForIntegration_DiscardKitsInError(t *testing.T) { } func TestLookupKitForIntegration_DiscardKitsWithIncompatibleTraits(t *testing.T) { - c, err := test.NewFakeClient( + c, err := internal.NewFakeClient( &v1.IntegrationPlatform{ TypeMeta: metav1.TypeMeta{ APIVersion: v1.SchemeGroupVersion.String(), @@ -280,7 +280,7 @@ func TestHasMatchingTraits_KitNoTraitShouldNotBePicked(t *testing.T) { }, } - c, err := test.NewFakeClient(integration, kit) + c, err := internal.NewFakeClient(integration, kit) require.NoError(t, err) ok, err := integrationAndKitHaveSameTraits(c, integration, kit) @@ -330,7 +330,7 @@ func TestHasMatchingTraits_KitSameTraitShouldBePicked(t *testing.T) { }, }, } - c, err := test.NewFakeClient(integration, kit) + c, err := internal.NewFakeClient(integration, kit) require.NoError(t, err) ok, err := integrationAndKitHaveSameTraits(c, integration, kit) require.NoError(t, err) diff --git a/pkg/controller/integration/monitor.go b/pkg/controller/integration/monitor.go index f7f4f72a40..6d425de86d 100644 --- a/pkg/controller/integration/monitor.go +++ b/pkg/controller/integration/monitor.go @@ -21,7 +21,6 @@ import ( "context" "errors" "fmt" - "math" "reflect" "strconv" "strings" @@ -41,6 +40,7 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/client" "github.com/apache/camel-k/v2/pkg/trait" + "github.com/apache/camel-k/v2/pkg/util" "github.com/apache/camel-k/v2/pkg/util/digest" "github.com/apache/camel-k/v2/pkg/util/kubernetes" utilResource "github.com/apache/camel-k/v2/pkg/util/resource" @@ -235,7 +235,7 @@ func (action *monitorAction) monitorPods(ctx context.Context, environment *trait nonTerminatingPods++ } podCount := len(pendingPods.Items) + nonTerminatingPods - replicas, err := IToInt32(podCount) + replicas, err := util.IToInt32(podCount) if err != nil { return nil, err } @@ -254,15 +254,6 @@ func (action *monitorAction) monitorPods(ctx context.Context, environment *trait return integration, nil } -func IToInt32(x int) (*int32, error) { - if x < math.MinInt32 || x > math.MaxInt32 { - return nil, fmt.Errorf("integer overflow casting to int32 type") - } - casted := int32(x) - - return &casted, nil -} - func isInInitializationFailed(status v1.IntegrationStatus) bool { if status.Phase != v1.IntegrationPhaseError { return false @@ -381,7 +372,6 @@ func getIntegrationSecretAndConfigmapResourceVersions(ctx context.Context, clien type controller interface { checkReadyCondition(ctx context.Context) (bool, error) - getPodSpec() corev1.PodSpec updateReadyCondition(readyPods int32) bool hasTemplateIntegrationLabel() bool getControllerName() string diff --git a/pkg/controller/integration/monitor_cronjob.go b/pkg/controller/integration/monitor_cronjob.go index 189c060cc9..7edd1d08e5 100644 --- a/pkg/controller/integration/monitor_cronjob.go +++ b/pkg/controller/integration/monitor_cronjob.go @@ -77,10 +77,6 @@ func (c *cronJobController) checkReadyCondition(ctx context.Context) (bool, erro return false, nil } -func (c *cronJobController) getPodSpec() corev1.PodSpec { - return c.obj.Spec.JobTemplate.Spec.Template.Spec -} - func (c *cronJobController) updateReadyCondition(readyPods int32) bool { switch { case c.obj.Status.LastScheduleTime == nil: diff --git a/pkg/controller/integration/monitor_deployment.go b/pkg/controller/integration/monitor_deployment.go index 45e3038cd5..e5f68f69fb 100644 --- a/pkg/controller/integration/monitor_deployment.go +++ b/pkg/controller/integration/monitor_deployment.go @@ -55,10 +55,6 @@ func (c *deploymentController) checkReadyCondition(ctx context.Context) (bool, e return false, nil } -func (c *deploymentController) getPodSpec() corev1.PodSpec { - return c.obj.Spec.Template.Spec -} - func (c *deploymentController) updateReadyCondition(readyPods int32) bool { replicas := int32(1) if r := c.integration.Spec.Replicas; r != nil { diff --git a/pkg/controller/integration/monitor_knative.go b/pkg/controller/integration/monitor_knative.go index 1dfe04d251..b8540617d7 100644 --- a/pkg/controller/integration/monitor_knative.go +++ b/pkg/controller/integration/monitor_knative.go @@ -48,10 +48,6 @@ func (c *knativeServiceController) checkReadyCondition(ctx context.Context) (boo return false, nil } -func (c *knativeServiceController) getPodSpec() corev1.PodSpec { - return c.obj.Spec.Template.Spec.PodSpec -} - func (c *knativeServiceController) updateReadyCondition(readyPods int32) bool { ready := kubernetes.GetKnativeServiceCondition(*c.obj, servingv1.ServiceConditionReady) if ready.IsTrue() { diff --git a/pkg/controller/integration/monitor_synthetic_test.go b/pkg/controller/integration/monitor_synthetic_test.go index d9893c378c..697379fc17 100644 --- a/pkg/controller/integration/monitor_synthetic_test.go +++ b/pkg/controller/integration/monitor_synthetic_test.go @@ -31,8 +31,8 @@ import ( "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "knative.dev/pkg/apis" @@ -58,7 +58,7 @@ func TestMonitorSyntheticIntegrationImportingKindUnavailable(t *testing.T) { Phase: v1.IntegrationPhaseRunning, }, } - c, err := test.NewFakeClient(importedIt) + c, err := internal.NewFakeClient(importedIt) require.NoError(t, err) a := monitorSyntheticAction{} @@ -116,7 +116,7 @@ func TestMonitorSyntheticIntegrationCannotMonitorPods(t *testing.T) { }, }, } - c, err := test.NewFakeClient(importedIt, deploy) + c, err := internal.NewFakeClient(importedIt, deploy) require.NoError(t, err) a := monitorSyntheticAction{} @@ -228,7 +228,7 @@ func TestMonitorSyntheticIntegrationDeployment(t *testing.T) { }, }, } - c, err := test.NewFakeClient(importedIt, deploy, pod) + c, err := internal.NewFakeClient(importedIt, deploy, pod) require.NoError(t, err) a := monitorSyntheticAction{} @@ -247,7 +247,7 @@ func TestMonitorSyntheticIntegrationDeployment(t *testing.T) { // Remove label from deployment deploy.Labels = nil - c, err = test.NewFakeClient(importedIt, deploy) + c, err = internal.NewFakeClient(importedIt, deploy) require.NoError(t, err) a.InjectClient(c) handledIt, err = a.Handle(context.TODO(), importedIt) @@ -348,7 +348,7 @@ func TestMonitorSyntheticIntegrationCronJob(t *testing.T) { }, }, } - c, err := test.NewFakeClient(importedIt, cron, pod) + c, err := internal.NewFakeClient(importedIt, cron, pod) require.NoError(t, err) a := monitorSyntheticAction{} @@ -469,7 +469,7 @@ func TestMonitorSyntheticIntegrationKnativeService(t *testing.T) { }, }, } - c, err := test.NewFakeClient(importedIt, ksvc, pod) + c, err := internal.NewFakeClient(importedIt, ksvc, pod) require.NoError(t, err) a := monitorSyntheticAction{} diff --git a/pkg/controller/integration/monitor_test.go b/pkg/controller/integration/monitor_test.go index 1f430037d2..6d192d857e 100644 --- a/pkg/controller/integration/monitor_test.go +++ b/pkg/controller/integration/monitor_test.go @@ -34,14 +34,14 @@ import ( "github.com/apache/camel-k/v2/pkg/util/digest" "github.com/apache/camel-k/v2/pkg/util/kubernetes" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGetIntegrationSecretAndConfigmapResourceVersions(t *testing.T) { - cm := kubernetes.NewConfigMap("default", "cm-test", "test.txt", "test.txt", "xyz", nil) + cm := newConfigMap("default", "cm-test", "test.txt", "test.txt", "xyz", nil) sec := &corev1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", @@ -74,7 +74,7 @@ func TestGetIntegrationSecretAndConfigmapResourceVersions(t *testing.T) { }, }, } - c, err := test.NewFakeClient(cm, sec) + c, err := internal.NewFakeClient(cm, sec) assert.Nil(t, err) // Default hot reload (false) configmaps, secrets := getIntegrationSecretAndConfigmapResourceVersions(context.TODO(), c, it) @@ -233,7 +233,7 @@ func TestMonitorIntegrationWhilePlatformRecreating(t *testing.T) { }, }, } - c, err := test.NewFakeClient(catalog, platform, it, kit, pod) + c, err := internal.NewFakeClient(catalog, platform, it, kit, pod) require.NoError(t, err) a := monitorAction{} @@ -343,7 +343,7 @@ func TestMonitorIntegrationPlatformNil(t *testing.T) { }, }, } - c, err := test.NewFakeClient(catalog, it, kit, pod) + c, err := internal.NewFakeClient(catalog, it, kit, pod) require.NoError(t, err) a := monitorAction{} @@ -486,6 +486,38 @@ func nominalEnvironment() (client.Client, *v1.Integration, error) { }, }, } - c, err := test.NewFakeClient(catalog, platform, it, kit, pod) + c, err := internal.NewFakeClient(catalog, platform, it, kit, pod) return c, it, err } + +// newConfigMap will create a ConfigMap. +func newConfigMap(namespace, cmName, originalFilename string, generatedKey string, + textData string, binaryData []byte) *corev1.ConfigMap { + immutable := true + cm := corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{ + Kind: "ConfigMap", + APIVersion: "v1", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: cmName, + Namespace: namespace, + Labels: map[string]string{ + kubernetes.ConfigMapOriginalFileNameLabel: originalFilename, + kubernetes.ConfigMapAutogenLabel: "true", + }, + }, + Immutable: &immutable, + } + if textData != "" { + cm.Data = map[string]string{ + generatedKey: textData, + } + } + if binaryData != nil { + cm.BinaryData = map[string][]byte{ + generatedKey: binaryData, + } + } + return &cm +} diff --git a/pkg/controller/integrationplatform/create_test.go b/pkg/controller/integrationplatform/create_test.go index 0124a81db0..e288765822 100644 --- a/pkg/controller/integrationplatform/create_test.go +++ b/pkg/controller/integrationplatform/create_test.go @@ -26,12 +26,12 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/platform" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/log" "github.com/apache/camel-k/v2/pkg/util/maven" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -52,7 +52,7 @@ func TestCreate(t *testing.T) { }, }, } - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) h := NewCreateAction() @@ -96,7 +96,7 @@ func TestCatalogAlreadyPresent(t *testing.T) { "camel.version": "4.4.0", } - c, err := test.NewFakeClient(&ip, &catalog) + c, err := internal.NewFakeClient(&ip, &catalog) require.NoError(t, err) action := NewCreateAction() @@ -131,7 +131,7 @@ func TestCreateNewCatalog(t *testing.T) { maven.DefaultMavenRepositories += ",https://repository.apache.org/content/repositories/snapshots-group@snapshots@id=apache-snapshots" } - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) // use local Maven executable in tests @@ -141,7 +141,7 @@ func TestCreateNewCatalog(t *testing.T) { t.Setenv("MAVEN_CMD", "mvn") } - fakeClient := c.(*test.FakeClient) //nolint + fakeClient := c.(*internal.FakeClient) //nolint fakeClient.AddReactor("create", "*", func(action k8stesting.Action) (bool, runtime.Object, error) { createAction := action.(k8stesting.CreateAction) //nolint @@ -191,7 +191,7 @@ func TestCreateNewCatalog(t *testing.T) { }, } // Refresh client with changed IP - c, err = test.NewFakeClient(&ip) + c, err = internal.NewFakeClient(&ip) require.NoError(t, err) action.InjectClient(c) answer, err = action.Handle(context.TODO(), &ip) @@ -208,7 +208,7 @@ func TestCreateCatalogError(t *testing.T) { ip.Namespace = "ns" ip.Name = "ck" ip.Spec.Build.RuntimeVersion = "0.0.0" - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) // use local Maven executable in tests @@ -218,7 +218,7 @@ func TestCreateCatalogError(t *testing.T) { t.Setenv("MAVEN_CMD", "mvn") } - fakeClient := c.(*test.FakeClient) //nolint + fakeClient := c.(*internal.FakeClient) //nolint fakeClient.AddReactor("create", "*", func(action k8stesting.Action) (bool, runtime.Object, error) { createAction := action.(k8stesting.CreateAction) //nolint diff --git a/pkg/controller/integrationplatform/initialize_test.go b/pkg/controller/integrationplatform/initialize_test.go index 14a66deeb3..1ad5bcf6ce 100644 --- a/pkg/controller/integrationplatform/initialize_test.go +++ b/pkg/controller/integrationplatform/initialize_test.go @@ -26,10 +26,10 @@ import ( "github.com/stretchr/testify/require" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/platform" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -37,7 +37,7 @@ func TestDefaultRuntimeSpec(t *testing.T) { ip := v1.IntegrationPlatform{} ip.Namespace = "ns" ip.Name = "ck" - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) h := NewInitializeAction() @@ -61,7 +61,7 @@ func TestUserRuntimeSpec(t *testing.T) { RuntimeProvider: "MyProvider", }, } - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) h := NewInitializeAction() @@ -79,7 +79,7 @@ func TestDefaultTimeouts(t *testing.T) { ip := v1.IntegrationPlatform{} ip.Namespace = "ns" ip.Name = "ck" - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) require.NoError(t, platform.ConfigureDefaults(context.TODO(), c, &ip, false)) @@ -103,7 +103,7 @@ func TestMavenComputedFromBuildTimeouts(t *testing.T) { ip.Spec.Build.Timeout = &metav1.Duration{ Duration: timeout, } - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) h := NewInitializeAction() @@ -125,7 +125,7 @@ func TestTruncatedTimeouts(t *testing.T) { ip.Spec.Build.Timeout = &metav1.Duration{ Duration: bt, } - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) h := NewInitializeAction() diff --git a/pkg/controller/integrationplatform/kamelets_test.go b/pkg/controller/integrationplatform/kamelets_test.go index 0bf31c0c28..fdbb416e07 100644 --- a/pkg/controller/integrationplatform/kamelets_test.go +++ b/pkg/controller/integrationplatform/kamelets_test.go @@ -28,9 +28,9 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -99,7 +99,7 @@ spec: } func TestPrepareKameletsPermissions(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() assert.NoError(t, err) err = prepareKameletsPermissions(context.TODO(), c, "camel-k") assert.NoError(t, err) diff --git a/pkg/controller/integrationplatform/monitor_test.go b/pkg/controller/integrationplatform/monitor_test.go index ddbcc1bdf6..5fb49092a2 100644 --- a/pkg/controller/integrationplatform/monitor_test.go +++ b/pkg/controller/integrationplatform/monitor_test.go @@ -24,9 +24,9 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -38,7 +38,7 @@ func TestCanHandlePhaseReadyOrError(t *testing.T) { ip.Namespace = "ns" ip.Name = "ck" ip.Status.Phase = v1.IntegrationPlatformPhaseReady - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) action := NewMonitorAction() @@ -74,7 +74,7 @@ func TestMonitorReady(t *testing.T) { ip.Status.Build.RuntimeProvider = v1.RuntimeProviderQuarkus ip.Status.Build.Registry.Address = "1.2.3.4" ip.Status.Phase = v1.IntegrationPlatformPhaseReady - c, err := test.NewFakeClient(&ip, &catalog) + c, err := internal.NewFakeClient(&ip, &catalog) require.NoError(t, err) action := NewMonitorAction() @@ -100,7 +100,7 @@ func TestMonitorDriftRuntime(t *testing.T) { ip.Status.Build.RuntimeProvider = v1.RuntimeProviderQuarkus ip.Status.Build.Registry.Address = "1.2.3.4" ip.Status.Phase = v1.IntegrationPlatformPhaseReady - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) action := NewMonitorAction() @@ -129,7 +129,7 @@ func TestMonitorDriftDefault(t *testing.T) { ip.Status.Build.RuntimeProvider = v1.RuntimeProviderQuarkus ip.Status.Build.Registry.Address = "1.2.3.4" ip.Status.Phase = v1.IntegrationPlatformPhaseReady - c, err := test.NewFakeClient(&ip, &catalog) + c, err := internal.NewFakeClient(&ip, &catalog) require.NoError(t, err) action := NewMonitorAction() @@ -181,7 +181,7 @@ func TestMonitorDriftConfiguration(t *testing.T) { } ip.Namespace = "ns" ip.Name = "ck" - c, err := test.NewFakeClient(&ip, &catalog) + c, err := internal.NewFakeClient(&ip, &catalog) require.NoError(t, err) action := NewMonitorAction() @@ -213,7 +213,7 @@ func TestMonitorMissingRegistryError(t *testing.T) { ip.Spec.Build.RuntimeProvider = v1.RuntimeProviderQuarkus ip.Status.Build.RuntimeVersion = "1.2.3" ip.Status.Build.RuntimeProvider = v1.RuntimeProviderQuarkus - c, err := test.NewFakeClient(&ip, &catalog) + c, err := internal.NewFakeClient(&ip, &catalog) require.NoError(t, err) action := NewMonitorAction() @@ -236,7 +236,7 @@ func TestMonitorMissingCatalogError(t *testing.T) { ip.Name = "ck" ip.Status.Build.RuntimeVersion = defaults.DefaultRuntimeVersion ip.Status.Build.RuntimeProvider = v1.RuntimeProviderQuarkus - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) action := NewMonitorAction() diff --git a/pkg/controller/pipe/initialize_test.go b/pkg/controller/pipe/initialize_test.go index 6367399e08..a6637adfae 100644 --- a/pkg/controller/pipe/initialize_test.go +++ b/pkg/controller/pipe/initialize_test.go @@ -30,8 +30,8 @@ import ( "github.com/apache/camel-k/v2/pkg/util/kubernetes" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ctrl "sigs.k8s.io/controller-runtime/pkg/client" @@ -48,7 +48,7 @@ func TestNewPipeError(t *testing.T) { Name: "my-pipe", }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewInitializeAction() @@ -86,7 +86,7 @@ func TestNewPipeCamelURIBinding(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewInitializeAction() @@ -187,7 +187,7 @@ func TestNewPipe(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe, &source, &sink) + c, err := internal.NewFakeClient(pipe, &source, &sink) require.NoError(t, err) a := NewInitializeAction() @@ -264,7 +264,7 @@ func TestNewPipeUnsupportedRef(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewInitializeAction() @@ -304,7 +304,7 @@ func TestNewPipeKnativeURIBinding(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewInitializeAction() @@ -357,7 +357,7 @@ func TestNewPipeKnativeRefBinding(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewInitializeAction() @@ -408,7 +408,7 @@ func TestNewPipeStrimziKafkaTopicBinding(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewInitializeAction() @@ -460,7 +460,7 @@ func TestNewPipeStrimziKafkaBinding(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewInitializeAction() diff --git a/pkg/controller/pipe/integration_test.go b/pkg/controller/pipe/integration_test.go index d41a232f07..d5756003fd 100644 --- a/pkg/controller/pipe/integration_test.go +++ b/pkg/controller/pipe/integration_test.go @@ -22,7 +22,7 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -30,7 +30,7 @@ import ( ) func TestCreateIntegrationForPipe(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) pipe := nominalPipe("my-pipe") @@ -55,7 +55,7 @@ func TestCreateIntegrationForPipe(t *testing.T) { } func TestCreateIntegrationForPipeWithSinkErrorHandler(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) pipe := nominalPipe("my-error-handler-pipe") @@ -80,7 +80,7 @@ func TestCreateIntegrationForPipeWithSinkErrorHandler(t *testing.T) { } func TestCreateIntegrationForPipeWithLogErrorHandler(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) pipe := nominalPipe("my-error-handler-pipe") @@ -105,7 +105,7 @@ func TestCreateIntegrationForPipeWithLogErrorHandler(t *testing.T) { } func TestCreateIntegrationForPipeDataType(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) pipe := nominalPipe("my-pipe-data-type") @@ -122,7 +122,7 @@ func TestCreateIntegrationForPipeDataType(t *testing.T) { } func TestCreateIntegrationForPipeDataTypeOverridden(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) pipe := nominalPipe("my-pipe-data-type") @@ -189,7 +189,7 @@ func expectedNominalRouteWithDataType(name string) string { } func TestExtractTraitAnnotations(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) annotations := map[string]string{ "my-personal-annotation": "hello", @@ -216,7 +216,7 @@ func TestExtractTraitAnnotations(t *testing.T) { } func TestExtractTraitAnnotationsError(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) annotations := map[string]string{ "my-personal-annotation": "hello", @@ -230,7 +230,7 @@ func TestExtractTraitAnnotationsError(t *testing.T) { } func TestExtractTraitAnnotationsEmpty(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) annotations := map[string]string{ "my-personal-annotation": "hello", @@ -242,7 +242,7 @@ func TestExtractTraitAnnotationsEmpty(t *testing.T) { } func TestCreateIntegrationTraitsForPipeWithTraitAnnotations(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) pipe := nominalPipe("my-pipe") diff --git a/pkg/controller/pipe/monitor_test.go b/pkg/controller/pipe/monitor_test.go index fc6b37baf4..543a918f91 100644 --- a/pkg/controller/pipe/monitor_test.go +++ b/pkg/controller/pipe/monitor_test.go @@ -28,8 +28,8 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/util/log" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -69,7 +69,7 @@ func TestPipeIntegrationSpecChanged(t *testing.T) { Phase: v1.IntegrationPhaseRunning, }, } - c, err := test.NewFakeClient(pipe, it) + c, err := internal.NewFakeClient(pipe, it) require.NoError(t, err) a := NewMonitorAction() @@ -106,7 +106,7 @@ func TestPipeIntegrationReady(t *testing.T) { }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) // We calculate the integration the same way it does the operator // as we don't expect it to change in this test. @@ -114,7 +114,7 @@ func TestPipeIntegrationReady(t *testing.T) { it.Status.Phase = v1.IntegrationPhaseRunning it.Status.SetCondition(v1.IntegrationConditionReady, corev1.ConditionTrue, "Running", "Running") require.NoError(t, err) - c, err = test.NewFakeClient(pipe, it) + c, err = internal.NewFakeClient(pipe, it) require.NoError(t, err) a := NewMonitorAction() @@ -151,14 +151,14 @@ func TestPipeIntegrationUnknown(t *testing.T) { }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) // We calculate the integration the same way it does the operator // as we don't expect it to change in this test. it, err := CreateIntegrationFor(context.TODO(), c, pipe) it.Status.Phase = v1.IntegrationPhaseRunning require.NoError(t, err) - c, err = test.NewFakeClient(pipe, it) + c, err = internal.NewFakeClient(pipe, it) require.NoError(t, err) a := NewMonitorAction() @@ -195,7 +195,7 @@ func TestPipeIntegrationError(t *testing.T) { }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) // We calculate the integration the same way it does the operator // as we don't expect it to change in this test. @@ -203,7 +203,7 @@ func TestPipeIntegrationError(t *testing.T) { it.Status.Phase = v1.IntegrationPhaseError it.Status.SetCondition(v1.IntegrationConditionReady, corev1.ConditionFalse, "ErrorReason", "Error message") require.NoError(t, err) - c, err = test.NewFakeClient(pipe, it) + c, err = internal.NewFakeClient(pipe, it) require.NoError(t, err) a := NewMonitorAction() @@ -233,7 +233,7 @@ func TestPipeIntegrationErrorFromPipeErrorPhase(t *testing.T) { }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewMonitorAction() @@ -271,7 +271,7 @@ func TestPipeIntegrationCreatingFromPipeErrorPhase(t *testing.T) { }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) a := NewMonitorAction() @@ -307,14 +307,14 @@ func TestPipeIntegrationCreatingFromPipeCreatingPhase(t *testing.T) { }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) // We calculate the integration the same way it does the operator // as we don't expect it to change in this test. it, err := CreateIntegrationFor(context.TODO(), c, pipe) require.NoError(t, err) it.Status.Phase = v1.IntegrationPhaseBuildingKit - c, err = test.NewFakeClient(pipe, it) + c, err = internal.NewFakeClient(pipe, it) require.NoError(t, err) a := NewMonitorAction() @@ -355,14 +355,14 @@ func TestPipeIntegrationPipeTraitAnnotations(t *testing.T) { }, } - c, err := test.NewFakeClient(pipe) + c, err := internal.NewFakeClient(pipe) require.NoError(t, err) // We calculate the integration the same way it does the operator // as we don't expect it to change in this test. it, err := CreateIntegrationFor(context.TODO(), c, pipe) require.NoError(t, err) it.Status.Phase = v1.IntegrationPhaseBuildingKit - c, err = test.NewFakeClient(pipe, it) + c, err = internal.NewFakeClient(pipe, it) require.NoError(t, err) a := NewMonitorAction() diff --git a/pkg/install/common.go b/pkg/install/common.go index 1c0b715a8d..78892ad6ea 100644 --- a/pkg/install/common.go +++ b/pkg/install/common.go @@ -61,11 +61,6 @@ var RemoveIngressRoleCustomizer = func(object ctrl.Object) ctrl.Object { return object } -// Resources installs named resources from the project resource directory. -func Resources(ctx context.Context, c client.Client, namespace string, force bool, customizer ResourceCustomizer, names ...string) error { - return ResourcesOrCollect(ctx, c, namespace, nil, force, customizer, names...) -} - func ResourcesOrCollect(ctx context.Context, c client.Client, namespace string, collection *kubernetes.Collection, force bool, customizer ResourceCustomizer, names ...string) error { for _, name := range names { diff --git a/pkg/util/test/client.go b/pkg/internal/client.go similarity index 99% rename from pkg/util/test/client.go rename to pkg/internal/client.go index a608fef360..4efd62b371 100644 --- a/pkg/util/test/client.go +++ b/pkg/internal/client.go @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package test +package internal import ( "context" diff --git a/pkg/platform/defaults_test.go b/pkg/platform/defaults_test.go index 4a5c7ee5d2..f73d0f60dd 100644 --- a/pkg/platform/defaults_test.go +++ b/pkg/platform/defaults_test.go @@ -28,8 +28,8 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/defaults" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestIntegrationPlatformDefaults(t *testing.T) { @@ -40,7 +40,7 @@ func TestIntegrationPlatformDefaults(t *testing.T) { }, } - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) err = ConfigureDefaults(context.TODO(), c, &ip, false) @@ -90,7 +90,7 @@ func TestApplyGlobalPlatformSpec(t *testing.T) { }, } - c, err := test.NewFakeClient(&global) + c, err := internal.NewFakeClient(&global) require.NoError(t, err) err = ConfigureDefaults(context.TODO(), c, &global, false) @@ -137,7 +137,7 @@ func TestPlatformS2IhUpdateOverrideLocalPlatformSpec(t *testing.T) { }, } - c, err := test.NewFakeClient(&global) + c, err := internal.NewFakeClient(&global) require.NoError(t, err) err = ConfigureDefaults(context.TODO(), c, &global, false) @@ -177,7 +177,7 @@ func TestPlatformS2IUpdateDefaultLocalPlatformSpec(t *testing.T) { }, } - c, err := test.NewFakeClient(&global) + c, err := internal.NewFakeClient(&global) require.NoError(t, err) err = ConfigureDefaults(context.TODO(), c, &global, false) @@ -236,7 +236,7 @@ func TestRetainLocalPlatformSpec(t *testing.T) { }, } - c, err := test.NewFakeClient(&global) + c, err := internal.NewFakeClient(&global) require.NoError(t, err) err = ConfigureDefaults(context.TODO(), c, &global, false) diff --git a/pkg/platform/profile_test.go b/pkg/platform/profile_test.go index 15a90fec0c..8ae42bd55b 100644 --- a/pkg/platform/profile_test.go +++ b/pkg/platform/profile_test.go @@ -28,7 +28,7 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" ) func TestFindIntegrationProfile(t *testing.T) { @@ -41,7 +41,7 @@ func TestFindIntegrationProfile(t *testing.T) { profile.ResyncStatusFullConfig() - c, err := test.NewFakeClient(&profile) + c, err := internal.NewFakeClient(&profile) require.NoError(t, err) integration := v1.Integration{ @@ -72,7 +72,7 @@ func TestFindIntegrationProfileWithNamespace(t *testing.T) { profile.ResyncStatusFullConfig() - c, err := test.NewFakeClient(&profile) + c, err := internal.NewFakeClient(&profile) require.NoError(t, err) integration := v1.Integration{ @@ -104,7 +104,7 @@ func TestFindIntegrationProfileInOperatorNamespace(t *testing.T) { profile.ResyncStatusFullConfig() - c, err := test.NewFakeClient(&profile) + c, err := internal.NewFakeClient(&profile) require.NoError(t, err) t.Setenv(operatorNamespaceEnvVariable, "operator-namespace") @@ -163,7 +163,7 @@ func TestApplyIntegrationProfile(t *testing.T) { profile.ResyncStatusFullConfig() - c, err := test.NewFakeClient(&profile) + c, err := internal.NewFakeClient(&profile) require.NoError(t, err) ip := v1.IntegrationPlatform{ @@ -251,7 +251,7 @@ func TestApplyIntegrationProfileAndRetainPlatformSpec(t *testing.T) { profile.ResyncStatusFullConfig() - c, err := test.NewFakeClient(&profile) + c, err := internal.NewFakeClient(&profile) require.NoError(t, err) ip := v1.IntegrationPlatform{ diff --git a/pkg/platform/resources.go b/pkg/platform/resources.go deleted file mode 100644 index a75f5019dd..0000000000 --- a/pkg/platform/resources.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package platform - -import "strings" - -// DefaultKits --. -var DefaultKits = []string{ - "platform-integration-kit-jvm.yaml", - "platform-integration-kit-groovy.yaml", - "platform-integration-kit-kotlin.yaml", -} - -// KnativeKits --. -var KnativeKits = []string{ - "platform-integration-kit-knative.yaml", -} - -// GetKits --. -func GetKits() []string { - return append(DefaultKits, KnativeKits...) -} - -// GetKitsNames --. -func GetKitsNames() []string { - ctxs := GetKits() - names := make([]string, 0, len(ctxs)) - - for _, r := range ctxs { - r = strings.TrimPrefix(r, "platform-integration-kit-") - r = strings.TrimSuffix(r, ".yaml") - - names = append(names, r) - } - - return names -} diff --git a/pkg/resources/resources_support.go b/pkg/resources/resources_support.go index 605d24f4f4..d3cb82fab1 100644 --- a/pkg/resources/resources_support.go +++ b/pkg/resources/resources_support.go @@ -83,14 +83,6 @@ func TemplateResource(name string, params interface{}) (string, error) { return buf.String(), nil } -// DirExists tells if a directory exists and can be listed for files. -func DirExists(dirName string) bool { - if _, err := resources.Open(dirName); err != nil { - return false - } - return true -} - // WithPrefix lists all file names that begins with the give path prefix // If pathPrefix is a path of directories then be sure to end it with a '/'. func WithPrefix(pathPrefix string) ([]string, error) { diff --git a/pkg/trait/builder_test.go b/pkg/trait/builder_test.go index 0ba9166938..c5c96265e0 100644 --- a/pkg/trait/builder_test.go +++ b/pkg/trait/builder_test.go @@ -29,10 +29,10 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestBuilderTraitNotAppliedBecauseOfNilKit(t *testing.T) { @@ -129,7 +129,7 @@ func createBuilderTestEnv(cluster v1.IntegrationPlatformCluster, strategy v1.Int Name: "my-kit", }, } - client, _ := test.NewFakeClient(itk) + client, _ := internal.NewFakeClient(itk) res := &Environment{ Ctx: context.TODO(), CamelCatalog: c, diff --git a/pkg/trait/camel_test.go b/pkg/trait/camel_test.go index a7d20d25cd..d76053911b 100644 --- a/pkg/trait/camel_test.go +++ b/pkg/trait/camel_test.go @@ -30,8 +30,8 @@ import ( "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -114,7 +114,7 @@ func TestApplyCamelTraitWithoutEnvironmentCatalogAndUnmatchableVersionFails(t *t } func createNominalCamelTest(withSources bool) (*camelTrait, *Environment) { - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() trait, _ := newCamelTrait().(*camelTrait) var sources []v1.SourceSpec diff --git a/pkg/trait/container_probes_test.go b/pkg/trait/container_probes_test.go index 0d17162a3b..52ae1f9c98 100644 --- a/pkg/trait/container_probes_test.go +++ b/pkg/trait/container_probes_test.go @@ -28,9 +28,9 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func newTestProbesEnv(t *testing.T, integration *v1.Integration) Environment { @@ -40,7 +40,7 @@ func newTestProbesEnv(t *testing.T, integration *v1.Integration) Environment { require.NoError(t, err) assert.NotNil(t, catalog) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) return Environment{ diff --git a/pkg/trait/container_test.go b/pkg/trait/container_test.go index ff52d6e8b5..7673a9471b 100644 --- a/pkg/trait/container_test.go +++ b/pkg/trait/container_test.go @@ -34,16 +34,16 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestContainerWithDefaults(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -118,11 +118,11 @@ func TestContainerWithOpenshift(t *testing.T) { }, } - client, _ := test.NewFakeClient(constrainedIntNamespace) + client, _ := internal.NewFakeClient(constrainedIntNamespace) traitCatalog := NewCatalog(nil) // enable openshift - fakeClient := client.(*test.FakeClient) //nolint + fakeClient := client.(*internal.FakeClient) //nolint fakeClient.EnableOpenshiftDiscovery() environment := Environment{ @@ -190,7 +190,7 @@ func TestContainerWithCustomName(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ CamelCatalog: catalog, @@ -259,7 +259,7 @@ func TestContainerWithCustomImage(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -325,7 +325,7 @@ func TestContainerWithCustomImageAndIntegrationKit(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -385,7 +385,7 @@ func TestContainerWithImagePullPolicy(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -434,7 +434,7 @@ func TestDeploymentContainerPorts(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -500,7 +500,7 @@ func TestKnativeServiceContainerPorts(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -679,7 +679,7 @@ func TestUserDefaultResources(t *testing.T) { func createSettingContextEnvironment(t *testing.T, profile v1.TraitProfile) *Environment { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ CamelCatalog: catalog, diff --git a/pkg/trait/cron_test.go b/pkg/trait/cron_test.go index f797a126d9..d440f7386b 100644 --- a/pkg/trait/cron_test.go +++ b/pkg/trait/cron_test.go @@ -34,10 +34,10 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestCronFromURI(t *testing.T) { @@ -229,7 +229,7 @@ func TestCronDeps(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -283,7 +283,7 @@ func TestCronDeps(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -305,7 +305,7 @@ func TestCronMultipleScheduleFallback(t *testing.T) { catalog, err := camel.DefaultCatalog() assert.Nil(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -366,7 +366,7 @@ func TestCronMultipleScheduleFallback(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") assert.Nil(t, err) tc := NewCatalog(c) @@ -386,7 +386,7 @@ func TestCronDepsFallback(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -444,7 +444,7 @@ func TestCronDepsFallback(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -468,7 +468,7 @@ func TestCronWithActiveDeadline(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -521,7 +521,7 @@ func TestCronWithActiveDeadline(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -557,7 +557,7 @@ func TestCronWithBackoffLimit(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -610,7 +610,7 @@ func TestCronWithBackoffLimit(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -648,7 +648,7 @@ func TestCronWithTimeZone(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) timeZone := "America/Sao_Paulo" @@ -703,7 +703,7 @@ func TestCronWithTimeZone(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -736,7 +736,7 @@ func TestCronAuto(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -784,7 +784,7 @@ func TestCronAuto(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -805,7 +805,7 @@ func TestCronRuntimeTriggerReplacement(t *testing.T) { catalog, err := camel.DefaultCatalog() assert.Nil(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -857,7 +857,7 @@ func TestCronRuntimeTriggerReplacement(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") assert.Nil(t, err) tc := NewCatalog(c) diff --git a/pkg/trait/deployment_test.go b/pkg/trait/deployment_test.go index 28c2a598f2..1eb97fd639 100644 --- a/pkg/trait/deployment_test.go +++ b/pkg/trait/deployment_test.go @@ -29,9 +29,9 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestConfigureDeploymentTraitWhileIntegrationIsRunningDoesSucceed(t *testing.T) { @@ -252,7 +252,7 @@ func TestApplyDeploymentTraitWitRollingUpdateStrategy(t *testing.T) { func createNominalDeploymentTest() (*deploymentTrait, *Environment) { trait, _ := newDeploymentTrait().(*deploymentTrait) - trait.Client, _ = test.NewFakeClient(&appsv1.Deployment{ + trait.Client, _ = internal.NewFakeClient(&appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "integration-name", Namespace: "namespace", @@ -280,7 +280,7 @@ func createNominalDeploymentTest() (*deploymentTrait, *Environment) { }) // disable the knative service api - fakeClient := trait.Client.(*test.FakeClient) //nolint + fakeClient := trait.Client.(*internal.FakeClient) //nolint fakeClient.DisableAPIGroupDiscovery("serving.knative.dev/v1") replicas := int32(3) diff --git a/pkg/trait/environment_test.go b/pkg/trait/environment_test.go index d7ffdf0c84..b8214d66ab 100644 --- a/pkg/trait/environment_test.go +++ b/pkg/trait/environment_test.go @@ -31,9 +31,9 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestDefaultEnvironment(t *testing.T) { @@ -242,7 +242,7 @@ func NewEnvironmentTestCatalog() *Catalog { } func mockEnvironment(catalog *camel.RuntimeCatalog) Environment { - fakeClient, _ := test.NewFakeClient() + fakeClient, _ := internal.NewFakeClient() return Environment{ CamelCatalog: catalog, Catalog: NewCatalog(nil), diff --git a/pkg/trait/gc_test.go b/pkg/trait/gc_test.go index 15a654f5a8..a82646c996 100644 --- a/pkg/trait/gc_test.go +++ b/pkg/trait/gc_test.go @@ -23,10 +23,10 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/apache/camel-k/v2/pkg/internal" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -101,7 +101,7 @@ func TestGetDefaultMinimalGarbageCollectableTypes(t *testing.T) { gcTrait, environment := createNominalGCTest() environment.Integration.Generation = 2 - gcTrait.Client, _ = test.NewFakeClient() + gcTrait.Client, _ = internal.NewFakeClient() environment.Client = gcTrait.Client deletableTypes, err := gcTrait.getDeletableTypes(environment) @@ -116,12 +116,12 @@ func TestGarbageCollectResources(t *testing.T) { deployment := getIntegrationDeployment(environment.Integration) deployment.Labels[v1.IntegrationGenerationLabel] = "1" - gcTrait.Client, _ = test.NewFakeClient(deployment) + gcTrait.Client, _ = internal.NewFakeClient(deployment) environment.Client = gcTrait.Client resourceDeleted := false - fakeClient := gcTrait.Client.(*test.FakeClient) //nolint + fakeClient := gcTrait.Client.(*internal.FakeClient) //nolint fakeClient.Intercept(&interceptor.Funcs{ Delete: func(ctx context.Context, client ctrl.WithWatch, obj ctrl.Object, opts ...ctrl.DeleteOption) error { assert.Equal(t, environment.Integration.Name, obj.GetName()) @@ -141,12 +141,12 @@ func TestGarbageCollectPreserveResourcesWithSameGeneration(t *testing.T) { environment.Integration.Generation = 2 deployment := getIntegrationDeployment(environment.Integration) - gcTrait.Client, _ = test.NewFakeClient(deployment) + gcTrait.Client, _ = internal.NewFakeClient(deployment) environment.Client = gcTrait.Client resourceDeleted := false - fakeClient := gcTrait.Client.(*test.FakeClient) //nolint + fakeClient := gcTrait.Client.(*internal.FakeClient) //nolint fakeClient.Intercept(&interceptor.Funcs{ Delete: func(ctx context.Context, client ctrl.WithWatch, obj ctrl.Object, opts ...ctrl.DeleteOption) error { resourceDeleted = true @@ -172,12 +172,12 @@ func TestGarbageCollectPreserveResourcesOwnerReferenceMismatch(t *testing.T) { Name: "other-integration-owner", }, } - gcTrait.Client, _ = test.NewFakeClient(deployment) + gcTrait.Client, _ = internal.NewFakeClient(deployment) environment.Client = gcTrait.Client resourceDeleted := false - fakeClient := gcTrait.Client.(*test.FakeClient) //nolint + fakeClient := gcTrait.Client.(*internal.FakeClient) //nolint fakeClient.Intercept(&interceptor.Funcs{ Delete: func(ctx context.Context, client ctrl.WithWatch, obj ctrl.Object, opts ...ctrl.DeleteOption) error { resourceDeleted = true @@ -195,7 +195,7 @@ func TestGarbageCollectKnativeServiceResources(t *testing.T) { environment.Integration.Generation = 2 environment.Integration.Spec.Profile = v1.TraitProfileKnative - gcTrait.Client, _ = test.NewFakeClient(&servingv1.Service{ + gcTrait.Client, _ = internal.NewFakeClient(&servingv1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: environment.Integration.Name, Namespace: environment.Integration.Namespace, @@ -216,7 +216,7 @@ func TestGarbageCollectKnativeServiceResources(t *testing.T) { environment.Client = gcTrait.Client resourceDeleted := false - fakeClient := gcTrait.Client.(*test.FakeClient) //nolint + fakeClient := gcTrait.Client.(*internal.FakeClient) //nolint fakeClient.Intercept(&interceptor.Funcs{ Delete: func(ctx context.Context, client ctrl.WithWatch, obj ctrl.Object, opts ...ctrl.DeleteOption) error { assert.Equal(t, environment.Integration.Name, obj.GetName()) @@ -237,7 +237,7 @@ func TestGarbageCollectKnativeTriggerResources(t *testing.T) { environment.Integration.Generation = 2 environment.Integration.Spec.Profile = v1.TraitProfileKnative - gcTrait.Client, _ = test.NewFakeClient(&eventingv1.Trigger{ + gcTrait.Client, _ = internal.NewFakeClient(&eventingv1.Trigger{ ObjectMeta: metav1.ObjectMeta{ Name: environment.Integration.Name, Namespace: environment.Integration.Namespace, @@ -258,7 +258,7 @@ func TestGarbageCollectKnativeTriggerResources(t *testing.T) { environment.Client = gcTrait.Client resourceDeleted := false - fakeClient := gcTrait.Client.(*test.FakeClient) //nolint + fakeClient := gcTrait.Client.(*internal.FakeClient) //nolint fakeClient.Intercept(&interceptor.Funcs{ Delete: func(ctx context.Context, client ctrl.WithWatch, obj ctrl.Object, opts ...ctrl.DeleteOption) error { assert.Equal(t, environment.Integration.Name, obj.GetName()) diff --git a/pkg/trait/health_test.go b/pkg/trait/health_test.go index c9092ef6b4..a11d0662b9 100644 --- a/pkg/trait/health_test.go +++ b/pkg/trait/health_test.go @@ -30,16 +30,16 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestHealthTrait(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ diff --git a/pkg/trait/istio_test.go b/pkg/trait/istio_test.go index 13d2369e23..39c05cf213 100644 --- a/pkg/trait/istio_test.go +++ b/pkg/trait/istio_test.go @@ -32,15 +32,15 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func NewIstioTestEnv(t *testing.T, d *appsv1.Deployment, s *serving.Service, enabled bool) Environment { t.Helper() - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() catalog, err := camel.DefaultCatalog() require.NoError(t, err) diff --git a/pkg/trait/jvm_test.go b/pkg/trait/jvm_test.go index 8365c80df3..76dd8e9d8a 100644 --- a/pkg/trait/jvm_test.go +++ b/pkg/trait/jvm_test.go @@ -24,9 +24,9 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" @@ -592,7 +592,7 @@ func TestApplyJvmTraitHttpProxyArgs(t *testing.T) { func createNominalJvmTest(kitType string) (*jvmTrait, *Environment) { catalog, _ := camel.DefaultCatalog() - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() trait, _ := newJvmTrait().(*jvmTrait) trait.PrintCommand = ptr.To(false) trait.Client = client diff --git a/pkg/trait/kamelets_test.go b/pkg/trait/kamelets_test.go index 2b43d40afa..ef6820f4ea 100644 --- a/pkg/trait/kamelets_test.go +++ b/pkg/trait/kamelets_test.go @@ -24,9 +24,9 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -574,7 +574,7 @@ func TestKameletConditionTrue(t *testing.T) { func createKameletsTestEnvironment(flow string, objects ...runtime.Object) (*kameletsTrait, *Environment) { catalog, _ := camel.DefaultCatalog() - client, _ := test.NewFakeClient(objects...) + client, _ := internal.NewFakeClient(objects...) trait, _ := newKameletsTrait().(*kameletsTrait) trait.Client = client diff --git a/pkg/trait/knative_service_test.go b/pkg/trait/knative_service_test.go index 80cf2628cb..51ba739ded 100644 --- a/pkg/trait/knative_service_test.go +++ b/pkg/trait/knative_service_test.go @@ -34,11 +34,12 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" + "github.com/apache/camel-k/v2/pkg/util/envvar" "github.com/apache/camel-k/v2/pkg/util/gzip" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) const ( @@ -50,7 +51,7 @@ func TestKnativeService(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("platform-http:test").log("hello")`)) @@ -185,15 +186,24 @@ func TestKnativeService(t *testing.T) { assert.Equal(t, "file:/etc/camel/sources/routes.js", environment.ApplicationProperties["camel.k.sources[0].location"]) assert.Equal(t, "js", environment.ApplicationProperties["camel.k.sources[0].language"]) assert.Equal(t, boolean.TrueString, environment.ApplicationProperties["camel.k.sources[0].compressed"]) - test.EnvVarHasValue(t, spec.Containers[0].Env, "CAMEL_K_CONF", filepath.FromSlash("/etc/camel/application.properties")) - test.EnvVarHasValue(t, spec.Containers[0].Env, "CAMEL_K_CONF_D", filepath.FromSlash("/etc/camel/conf.d")) + envVarHasValue(t, spec.Containers[0].Env, "CAMEL_K_CONF", filepath.FromSlash("/etc/camel/application.properties")) + envVarHasValue(t, spec.Containers[0].Env, "CAMEL_K_CONF_D", filepath.FromSlash("/etc/camel/conf.d")) +} + +// envVarHasValue --. +func envVarHasValue(t *testing.T, env []corev1.EnvVar, name string, val string) { + t.Helper() + + ev := envvar.Get(env, name) + assert.NotNil(t, ev) + assert.Equal(t, val, ev.Value) } func TestKnativeServiceWithCustomContainerName(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -277,7 +287,7 @@ func TestKnativeServiceWithRest(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -352,7 +362,7 @@ func TestKnativeServiceNotApplicable(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -424,8 +434,8 @@ func TestKnativeServiceNoServingAvailable(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() - fakeClient := client.(*test.FakeClient) //nolint + client, _ := internal.NewFakeClient() + fakeClient := client.(*internal.FakeClient) //nolint fakeClient.DisableKnativeServing() traitCatalog := NewCatalog(nil) @@ -545,7 +555,7 @@ func createKnativeServiceTestEnvironment(t *testing.T, trait *traitv1.KnativeSer catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := &Environment{ @@ -635,7 +645,7 @@ func TestKnativeServiceAuto(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("platform-http:test").log("hello")`)) diff --git a/pkg/trait/knative_test.go b/pkg/trait/knative_test.go index 7a6ebe49f0..fd7cc917e5 100644 --- a/pkg/trait/knative_test.go +++ b/pkg/trait/knative_test.go @@ -41,16 +41,16 @@ import ( knativeapi "github.com/apache/camel-k/v2/pkg/apis/camel/v1/knative" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" "github.com/apache/camel-k/v2/pkg/client" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/knative" "github.com/apache/camel-k/v2/pkg/util/kubernetes" k8sutils "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestKnativeEnvConfigurationFromTrait(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) catalog, err := camel.DefaultCatalog() require.NoError(t, err) @@ -109,7 +109,7 @@ func TestKnativeEnvConfigurationFromTrait(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -164,7 +164,7 @@ func TestKnativeEnvConfigurationFromTrait(t *testing.T) { } func TestKnativeEnvConfigurationFromSource(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) catalog, err := camel.DefaultCatalog() require.NoError(t, err) @@ -237,7 +237,7 @@ func TestKnativeEnvConfigurationFromSource(t *testing.T) { } environment.Platform.ResyncStatusFullConfig() - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -284,7 +284,7 @@ func TestKnativeTriggerExplicitFilterConfig(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) traitCatalog := NewCatalog(c) @@ -383,7 +383,7 @@ func TestKnativeTriggerExplicitFilterConfigNoEventTypeFilter(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) traitCatalog := NewCatalog(c) @@ -482,7 +482,7 @@ func TestKnativeTriggerDefaultEventTypeFilter(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) traitCatalog := NewCatalog(c) @@ -578,7 +578,7 @@ func TestKnativeTriggerDefaultEventTypeFilterDisabled(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) traitCatalog := NewCatalog(c) @@ -673,7 +673,7 @@ func TestKnativeMultipleTrigger(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) traitCatalog := NewCatalog(c) @@ -810,7 +810,7 @@ func TestKnativeMultipleTriggerAdditionalFilterConfig(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) traitCatalog := NewCatalog(c) @@ -952,7 +952,7 @@ func TestKnativeTriggerNoEventType(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) traitCatalog := NewCatalog(c) @@ -1046,10 +1046,10 @@ func TestKnativeTriggerNoServingAvailable(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) - fakeClient := c.(*test.FakeClient) //nolint + fakeClient := c.(*internal.FakeClient) //nolint fakeClient.DisableKnativeServing() traitCatalog := NewCatalog(c) @@ -1172,7 +1172,7 @@ func TestKnativePlatformHttpConfig(t *testing.T) { t.Run(source.Name, func(t *testing.T) { environment := NewFakeEnvironment(t, source) - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -1218,7 +1218,7 @@ func TestKnativePlatformHttpDependencies(t *testing.T) { environment := NewFakeEnvironment(t, source) environment.Integration.Status.Phase = v1.IntegrationPhaseInitialization - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -1237,7 +1237,7 @@ func TestKnativePlatformHttpDependencies(t *testing.T) { } func TestKnativeEnabled(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) catalog, err := camel.DefaultCatalog() require.NoError(t, err) @@ -1308,7 +1308,7 @@ func TestKnativeEnabled(t *testing.T) { } func TestKnativeNotEnabled(t *testing.T) { - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) catalog, err := camel.DefaultCatalog() require.NoError(t, err) @@ -1379,7 +1379,7 @@ func TestKnativeNotEnabled(t *testing.T) { func NewFakeEnvironment(t *testing.T, source v1.SourceSpec) Environment { t.Helper() - client, _ := NewFakeClient("ns") + client, _ := newFakeClient("ns") catalog, err := camel.DefaultCatalog() require.NoError(t, err) @@ -1441,7 +1441,7 @@ func NewFakeEnvironment(t *testing.T, source v1.SourceSpec) Environment { func NewFakeEnvironmentForSyntheticKit(t *testing.T) Environment { t.Helper() - client, _ := NewFakeClient("ns") + client, _ := newFakeClient("ns") traitCatalog := NewCatalog(nil) environment := Environment{ @@ -1493,7 +1493,7 @@ func NewFakeEnvironmentForSyntheticKit(t *testing.T) Environment { return environment } -func NewFakeClient(namespace string) (client.Client, error) { +func newFakeClient(namespace string) (client.Client, error) { channelSourceURL, err := apis.ParseURL("http://channel-source-1.host/") if err != nil { return nil, err @@ -1515,7 +1515,7 @@ func NewFakeClient(namespace string) (client.Client, error) { return nil, err } - return test.NewFakeClient( + return internal.NewFakeClient( &messaging.Channel{ TypeMeta: metav1.TypeMeta{ Kind: "Channel", @@ -1646,7 +1646,7 @@ func TestKnativeSinkBinding(t *testing.T) { environment := NewFakeEnvironment(t, source) environment.Integration.Status.Phase = v1.IntegrationPhaseDeploying - c, err := NewFakeClient("ns") + c, err := newFakeClient("ns") require.NoError(t, err) tc := NewCatalog(c) @@ -1767,9 +1767,9 @@ func TestRunNonKnativeEndpointWithKnativeNotInstalled(t *testing.T) { } func createEnvironmentMissingEventingCRDs() *Environment { - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() // disable the knative eventing api - fakeClient := client.(*test.FakeClient) //nolint + fakeClient := client.(*internal.FakeClient) //nolint fakeClient.DisableAPIGroupDiscovery("eventing.knative.dev/v1") replicas := int32(3) @@ -1809,7 +1809,7 @@ func createEnvironmentMissingEventingCRDs() *Environment { } func TestKnativeAutoConfiguration(t *testing.T) { - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() replicas := int32(3) catalog, _ := camel.QuarkusCatalog() environment := &Environment{ diff --git a/pkg/trait/logging_test.go b/pkg/trait/logging_test.go index 49a4ec878d..14541e854b 100644 --- a/pkg/trait/logging_test.go +++ b/pkg/trait/logging_test.go @@ -30,17 +30,17 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/envvar" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func createLoggingTestEnv(t *testing.T, color bool, json bool, jsonPrettyPrint bool, logLevel string, logFormat string) *Environment { t.Helper() - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() c, err := camel.DefaultCatalog() if err != nil { panic(err) diff --git a/pkg/trait/mount_test.go b/pkg/trait/mount_test.go index 2adaff9a44..aed0d73710 100644 --- a/pkg/trait/mount_test.go +++ b/pkg/trait/mount_test.go @@ -31,11 +31,11 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/gzip" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestMountVolumesEmpty(t *testing.T) { @@ -244,7 +244,7 @@ func getNominalEnv(t *testing.T, traitCatalog *Catalog) *Environment { Name: "my-pvc", }, } - fakeClient, _ := test.NewFakeClient(&pvc) + fakeClient, _ := internal.NewFakeClient(&pvc) catalog, _ := camel.DefaultCatalog() compressedRoute, _ := gzip.CompressBase64([]byte(`from("platform-http:test").log("hello")`)) @@ -357,7 +357,7 @@ func TestMountVolumesCreateDefaultStorageClass(t *testing.T) { }, }, } - fakeClient, _ := test.NewFakeClient(&sc) + fakeClient, _ := internal.NewFakeClient(&sc) e.Client = fakeClient // Default storage class vol, vm, err := ParseAndCreateVolume(e, "my-pvc:/tmp/my-pvc:10Mi:ReadOnly") @@ -383,7 +383,7 @@ func TestMountVolumesCreateUserStorageClass(t *testing.T) { Name: "my-sc", }, } - fakeClient, _ := test.NewFakeClient(&sc) + fakeClient, _ := internal.NewFakeClient(&sc) e.Client = fakeClient // Default storage class vol, vm, err := ParseAndCreateVolume(e, "my-pvc:/tmp/my-pvc:10Mi:ReadOnly:my-sc") diff --git a/pkg/trait/openapi_test.go b/pkg/trait/openapi_test.go index 85a55a68c1..0cb6d5f133 100644 --- a/pkg/trait/openapi_test.go +++ b/pkg/trait/openapi_test.go @@ -28,12 +28,12 @@ import ( "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" "github.com/apache/camel-k/v2/pkg/util/maven" - "github.com/apache/camel-k/v2/pkg/util/test" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -83,7 +83,7 @@ func TestRestDslTraitApplicability(t *testing.T) { func TestRestDslTraitApplyError(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - fakeClient, _ := test.NewFakeClient() + fakeClient, _ := internal.NewFakeClient() e := &Environment{ CamelCatalog: catalog, @@ -236,10 +236,10 @@ func TestRestDslTraitApplyWorks(t *testing.T) { require.NoError(t, err) content, err := util.EncodeXML(settings) require.NoError(t, err) - cm := kubernetes.NewConfigMap("default", "maven-settings", "settings.xml", "settings.xml", string(content), nil) + cm := newConfigMap("default", "maven-settings", "settings.xml", "settings.xml", string(content), nil) catalog, err := camel.DefaultCatalog() require.NoError(t, err) - fakeClient, _ := test.NewFakeClient(&corev1.ConfigMap{ + fakeClient, _ := internal.NewFakeClient(&corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "my-configmap", Namespace: "default", @@ -325,3 +325,35 @@ func TestRestDslTraitApplyWorks(t *testing.T) { assert.NotNil(t, sourceCm) assert.Contains(t, sourceCm.Data["content"], "get id=\"showPetById\" path=\"/pets/{petId}\"") } + +// newConfigMap will create a ConfigMap. +func newConfigMap(namespace, cmName, originalFilename string, generatedKey string, + textData string, binaryData []byte) *corev1.ConfigMap { + immutable := true + cm := corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{ + Kind: "ConfigMap", + APIVersion: "v1", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: cmName, + Namespace: namespace, + Labels: map[string]string{ + kubernetes.ConfigMapOriginalFileNameLabel: originalFilename, + kubernetes.ConfigMapAutogenLabel: "true", + }, + }, + Immutable: &immutable, + } + if textData != "" { + cm.Data = map[string]string{ + generatedKey: textData, + } + } + if binaryData != nil { + cm.BinaryData = map[string][]byte{ + generatedKey: binaryData, + } + } + return &cm +} diff --git a/pkg/trait/platform_test.go b/pkg/trait/platform_test.go index 0c1e7d8f0d..d0ac5abfd3 100644 --- a/pkg/trait/platform_test.go +++ b/pkg/trait/platform_test.go @@ -24,11 +24,11 @@ import ( "github.com/apache/camel-k/v2/pkg/platform" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/apache/camel-k/v2/pkg/internal" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" ) @@ -64,7 +64,7 @@ func TestPlatformTraitChangeStatus(t *testing.T) { trait.CreateDefault = ptr.To(false) var err error - trait.Client, err = test.NewFakeClient() + trait.Client, err = internal.NewFakeClient() require.NoError(t, err) enabled, condition, err := trait.Configure(&e) @@ -99,7 +99,7 @@ func TestPlatformTraitCreatesDefaultPlatform(t *testing.T) { trait.CreateDefault = ptr.To(true) var err error - trait.Client, err = test.NewFakeClient() + trait.Client, err = internal.NewFakeClient() require.NoError(t, err) enabled, condition, err := trait.Configure(&e) @@ -157,7 +157,7 @@ func TestPlatformTraitExisting(t *testing.T) { var err error existingPlatform := v1.NewIntegrationPlatform("ns1", "existing") existingPlatform.Status.Phase = input.platformPhase - trait.Client, err = test.NewFakeClient(&existingPlatform) + trait.Client, err = internal.NewFakeClient(&existingPlatform) require.NoError(t, err) enabled, condition, err := trait.Configure(&e) diff --git a/pkg/trait/pull_secret_test.go b/pkg/trait/pull_secret_test.go index ffe5e0c447..ddd1a12629 100644 --- a/pkg/trait/pull_secret_test.go +++ b/pkg/trait/pull_secret_test.go @@ -23,7 +23,6 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" @@ -32,6 +31,7 @@ import ( "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -127,7 +127,7 @@ func getEnvironmentAndDeployment(t *testing.T) (*Environment, *appsv1.Deployment var err error e.Ctx = context.TODO() - e.Client, err = test.NewFakeClient(e.Integration, &deployment) + e.Client, err = internal.NewFakeClient(e.Integration, &deployment) require.NoError(t, err) return e, &deployment diff --git a/pkg/trait/quarkus_test.go b/pkg/trait/quarkus_test.go index 8092e3b79b..7852f5ac28 100644 --- a/pkg/trait/quarkus_test.go +++ b/pkg/trait/quarkus_test.go @@ -30,8 +30,8 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/builder" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestConfigureQuarkusTraitBuildSubmitted(t *testing.T) { @@ -106,7 +106,7 @@ func TestQuarkusTraitBuildModeOrder(t *testing.T) { func createNominalQuarkusTest() (*quarkusTrait, *Environment) { trait, _ := newQuarkusTrait().(*quarkusTrait) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() environment := &Environment{ Catalog: NewCatalog(client), diff --git a/pkg/trait/route_test.go b/pkg/trait/route_test.go index 2ab1b31065..5240690888 100644 --- a/pkg/trait/route_test.go +++ b/pkg/trait/route_test.go @@ -33,10 +33,10 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) const ( @@ -111,7 +111,7 @@ func createTestRouteEnvironment(t *testing.T, name string) *Environment { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient( + client, _ := internal.NewFakeClient( &corev1.Secret{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", diff --git a/pkg/trait/security_context_test.go b/pkg/trait/security_context_test.go index b9a49a2436..ac859be3c4 100644 --- a/pkg/trait/security_context_test.go +++ b/pkg/trait/security_context_test.go @@ -30,9 +30,9 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestDefaultPodKubernetesSecurityContextInitializationPhase(t *testing.T) { @@ -149,7 +149,7 @@ func TestUserPodSecurityContext(t *testing.T) { func createPodSettingContextEnvironment(t *testing.T, profile v1.TraitProfile) *Environment { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ CamelCatalog: catalog, @@ -208,11 +208,11 @@ func createOpenshiftPodSettingContextEnvironment(t *testing.T, profile v1.TraitP }, } - client, _ := test.NewFakeClient(constrainedIntNamespace) + client, _ := internal.NewFakeClient(constrainedIntNamespace) traitCatalog := NewCatalog(nil) // enable openshift - fakeClient := client.(*test.FakeClient) //nolint + fakeClient := client.(*internal.FakeClient) //nolint fakeClient.EnableOpenshiftDiscovery() catalog, err := camel.DefaultCatalog() require.NoError(t, err) diff --git a/pkg/trait/service_binding_test.go b/pkg/trait/service_binding_test.go index 545b38b0b7..ee00d87c27 100644 --- a/pkg/trait/service_binding_test.go +++ b/pkg/trait/service_binding_test.go @@ -25,9 +25,9 @@ import ( "github.com/stretchr/testify/require" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" "github.com/apache/camel-k/v2/pkg/util/camel" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestServiceBinding(t *testing.T) { @@ -55,7 +55,7 @@ func TestServiceBinding(t *testing.T) { func createNominalServiceBindingTest() (*serviceBindingTrait, *Environment) { trait, _ := newServiceBindingTrait().(*serviceBindingTrait) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() catalog := NewCatalog(client) c, err := camel.DefaultCatalog() if err != nil { diff --git a/pkg/trait/service_test.go b/pkg/trait/service_test.go index 25c6935c70..87c240f7b3 100644 --- a/pkg/trait/service_test.go +++ b/pkg/trait/service_test.go @@ -30,10 +30,10 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/gzip" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) const ( @@ -45,7 +45,7 @@ func TestServiceWithDefaults(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) @@ -144,7 +144,7 @@ func TestService(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) @@ -249,7 +249,7 @@ func TestServiceWithCustomContainerName(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := Environment{ @@ -328,7 +328,7 @@ func TestServiceWithNodePort(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) @@ -424,7 +424,7 @@ func TestServiceWithKnativeServiceEnabled(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) @@ -518,7 +518,7 @@ func TestServicesWithKnativeProfile(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) @@ -600,7 +600,7 @@ func TestServiceWithKnativeServiceDisabledInIntegrationPlatform(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) @@ -680,7 +680,7 @@ func TestServiceAutoConfiguration(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) @@ -745,7 +745,7 @@ func TestServiceAnnotationsAndLables(t *testing.T) { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) compressedRoute, err := gzip.CompressBase64([]byte(`from("netty-http:test").log("hello")`)) diff --git a/pkg/trait/trait_catalog_test.go b/pkg/trait/trait_catalog_test.go index 3475ae2f0e..d93e8b508f 100644 --- a/pkg/trait/trait_catalog_test.go +++ b/pkg/trait/trait_catalog_test.go @@ -27,10 +27,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestIntegrationExecutedTrait(t *testing.T) { @@ -46,7 +46,7 @@ func TestIntegrationExecutedTrait(t *testing.T) { }, Phase: v1.IntegrationPlatformPhaseReady, } - c, err := test.NewFakeClient(&ip) + c, err := internal.NewFakeClient(&ip) require.NoError(t, err) catalog := NewCatalog(c) env := Environment{ diff --git a/pkg/trait/trait_configure_test.go b/pkg/trait/trait_configure_test.go index 14943906da..a9bfbdf750 100644 --- a/pkg/trait/trait_configure_test.go +++ b/pkg/trait/trait_configure_test.go @@ -213,21 +213,3 @@ func TestTraitSplitConfiguration(t *testing.T) { ot, _ := c.GetTrait("owner").(*ownerTrait) assert.Equal(t, []string{"opt1", "opt2"}, ot.TargetLabels) } - -func TestTraitDecode(t *testing.T) { - trait := traitToMap(t, traitv1.ContainerTrait{ - PlatformBaseTrait: traitv1.PlatformBaseTrait{}, - Name: "test-container", - Port: int32(7071), - Auto: ptr.To(false), - }) - - target, ok := newContainerTrait().(*containerTrait) - require.True(t, ok) - err := decodeTrait(trait, target) - require.NoError(t, err) - - assert.Equal(t, "test-container", target.Name) - assert.Equal(t, int32(7071), target.Port) - assert.False(t, ptr.Deref(target.Auto, true)) -} diff --git a/pkg/trait/test_support.go b/pkg/trait/trait_support_test.go similarity index 98% rename from pkg/trait/test_support.go rename to pkg/trait/trait_support_test.go index 32c14c8dda..fae6bb7954 100644 --- a/pkg/trait/test_support.go +++ b/pkg/trait/trait_support_test.go @@ -135,7 +135,7 @@ func traitToMap(t *testing.T, trait interface{}) map[string]interface{} { return traitMap } -func ToAddonTrait(t *testing.T, config map[string]interface{}) v1.AddonTrait { +func toAddonTrait(t *testing.T, config map[string]interface{}) v1.AddonTrait { t.Helper() data, err := json.Marshal(config) diff --git a/pkg/trait/trait_test.go b/pkg/trait/trait_test.go index 2324dd8cf1..f7b692d368 100644 --- a/pkg/trait/trait_test.go +++ b/pkg/trait/trait_test.go @@ -35,11 +35,11 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/resources" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) const ( @@ -252,7 +252,7 @@ func processTestEnv(t *testing.T, env *Environment) *kubernetes.Collection { func createTestEnv(t *testing.T, cluster v1.IntegrationPlatformCluster, script string) *Environment { t.Helper() - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() catalog, err := camel.DefaultCatalog() require.NoError(t, err) @@ -375,7 +375,7 @@ func testDefaultIntegrationPhaseTraitsSetting(t *testing.T, phase v1.Integration cat.SetAnnotations(platform.Annotations) cat.SetNamespace(platform.Namespace) - client, err := test.NewFakeClient(platform, &cat) + client, err := internal.NewFakeClient(platform, &cat) require.NoError(t, err) env, err := Apply(context.Background(), client, it, nil) require.NoError(t, err) @@ -446,7 +446,7 @@ func TestIntegrationTraitsSetting(t *testing.T) { Name: "my-container-name", }, Addons: map[string]v1.AddonTrait{ - "master": ToAddonTrait(t, map[string]interface{}{ + "master": toAddonTrait(t, map[string]interface{}{ "resourceName": "test-lock", }), }, @@ -486,7 +486,7 @@ func TestIntegrationTraitsSetting(t *testing.T) { cat.SetAnnotations(platform.Annotations) cat.SetNamespace(platform.Namespace) - client, err := test.NewFakeClient(platform, &cat) + client, err := internal.NewFakeClient(platform, &cat) require.NoError(t, err) env, err := Apply(context.Background(), client, it, nil) require.NoError(t, err) @@ -506,7 +506,7 @@ func TestIntegrationTraitsSetting(t *testing.T) { Name: "my-container-name", }, Addons: map[string]v1.AddonTrait{ - "master": ToAddonTrait(t, map[string]interface{}{ + "master": toAddonTrait(t, map[string]interface{}{ "resourceName": "test-lock", }), }, diff --git a/pkg/trait/trait_types_test.go b/pkg/trait/trait_types_test.go index e08221432f..7d3acdc453 100644 --- a/pkg/trait/trait_types_test.go +++ b/pkg/trait/trait_types_test.go @@ -28,10 +28,10 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/camel" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/kubernetes" - "github.com/apache/camel-k/v2/pkg/util/test" ) func TestCollectConfigurationValues(t *testing.T) { @@ -199,7 +199,7 @@ func createTestEnvironment(t *testing.T, profile v1.TraitProfile) *Environment { catalog, err := camel.DefaultCatalog() require.NoError(t, err) - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) environment := &Environment{ @@ -265,7 +265,7 @@ func createTestEnvironment(t *testing.T, profile v1.TraitProfile) *Environment { func createNonManagedBuildTestEnvironment(t *testing.T, profile v1.TraitProfile) *Environment { t.Helper() - client, _ := test.NewFakeClient() + client, _ := internal.NewFakeClient() traitCatalog := NewCatalog(nil) catalog, err := camel.DefaultCatalog() require.NoError(t, err) diff --git a/pkg/trait/util.go b/pkg/trait/util.go index 45ace8e370..e5d28392e4 100644 --- a/pkg/trait/util.go +++ b/pkg/trait/util.go @@ -191,20 +191,6 @@ func ToTraitMap(traits interface{}) (Options, error) { return traitMap, nil } -// ToPropertyMap accepts a trait and converts it to a map of trait properties. -func ToPropertyMap(trait interface{}) (map[string]interface{}, error) { - data, err := json.Marshal(trait) - if err != nil { - return nil, err - } - propMap := make(map[string]interface{}) - if err = json.Unmarshal(data, &propMap); err != nil { - return nil, err - } - - return propMap, nil -} - // MigrateLegacyConfiguration moves up the legacy configuration in a trait to the new top-level properties. // Values of the new properties always take precedence over the ones from the legacy configuration // with the same property names. diff --git a/pkg/trait/util_test.go b/pkg/trait/util_test.go index e8e8e153c8..08a21625ee 100644 --- a/pkg/trait/util_test.go +++ b/pkg/trait/util_test.go @@ -25,8 +25,8 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -49,7 +49,7 @@ func TestToTraitMap(t *testing.T) { }, }, Addons: map[string]v1.AddonTrait{ - "telemetry": ToAddonTrait(t, map[string]interface{}{ + "telemetry": toAddonTrait(t, map[string]interface{}{ "enabled": true, }), }, @@ -80,33 +80,6 @@ func TestToTraitMap(t *testing.T) { assert.Equal(t, expected, traitMap) } -func TestToPropertyMap(t *testing.T) { - trait := traitv1.ContainerTrait{ - PlatformBaseTrait: traitv1.PlatformBaseTrait{}, - Name: "test-container", - Auto: ptr.To(false), - Expose: ptr.To(true), - Port: 8081, - PortName: "http-8081", - ServicePort: 81, - ServicePortName: "http-81", - } - expected := map[string]interface{}{ - "auto": false, - "expose": true, - "port": float64(8081), - "portName": "http-8081", - "servicePort": float64(81), - "servicePortName": "http-81", - "name": "test-container", - } - - propMap, err := ToPropertyMap(trait) - - require.NoError(t, err) - assert.Equal(t, expected, propMap) -} - func TestMigrateLegacyConfiguration(t *testing.T) { trait := map[string]interface{}{ "enabled": true, @@ -175,7 +148,7 @@ func TestToTrait(t *testing.T) { } func TestSameTraits(t *testing.T) { - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) t.Run("empty traits", func(t *testing.T) { oldKlb := &v1.Pipe{ @@ -413,7 +386,7 @@ func TestIntegrationAndPipeSameTraits(t *testing.T) { }, }, } - c, err := test.NewFakeClient(pipe, integration) + c, err := internal.NewFakeClient(pipe, integration) require.NoError(t, err) result, err := IntegrationAndPipeSameTraits(c, integration, pipe) diff --git a/pkg/util/bindings/test_support.go b/pkg/util/bindings/binding_support_test.go similarity index 100% rename from pkg/util/bindings/test_support.go rename to pkg/util/bindings/binding_support_test.go diff --git a/pkg/util/bindings/bindings_test.go b/pkg/util/bindings/bindings_test.go index eeff83b805..5b4e53a505 100644 --- a/pkg/util/bindings/bindings_test.go +++ b/pkg/util/bindings/bindings_test.go @@ -27,8 +27,7 @@ import ( v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait" - - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -236,7 +235,7 @@ func TestBindings(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) profile := tc.profile diff --git a/pkg/util/bindings/catalog_test.go b/pkg/util/bindings/catalog_test.go index 00c996749f..d9d2351503 100644 --- a/pkg/util/bindings/catalog_test.go +++ b/pkg/util/bindings/catalog_test.go @@ -23,10 +23,10 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" corev1 "k8s.io/api/core/v1" eventing "knative.dev/eventing/pkg/apis/eventing/v1" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/require" ) @@ -107,7 +107,7 @@ func TestValidateEndpoint(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) bindingContext := BindingContext{ @@ -180,7 +180,7 @@ func TestValidateEndpointError(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) bindingContext := BindingContext{ diff --git a/pkg/util/bindings/kamelet.go b/pkg/util/bindings/kamelet.go index 3b304debc6..1c6bad97b6 100644 --- a/pkg/util/bindings/kamelet.go +++ b/pkg/util/bindings/kamelet.go @@ -192,16 +192,6 @@ func (k BindingConverter) Order() int { return OrderStandard } -// V1alpha1BindingConverter converts a reference to a Kamelet into a Camel URI. -// Deprecated. -type V1alpha1BindingConverter struct{} - -// ID -- . -// Deprecated. -func (k V1alpha1BindingConverter) ID() string { - return "kamelet" -} - func init() { RegisterBindingProvider(BindingConverter{}) } diff --git a/pkg/util/bindings/kamelet_test.go b/pkg/util/bindings/kamelet_test.go index 848dccb6d2..dcd8bf7cb9 100644 --- a/pkg/util/bindings/kamelet_test.go +++ b/pkg/util/bindings/kamelet_test.go @@ -25,8 +25,8 @@ import ( corev1 "k8s.io/api/core/v1" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" + "github.com/apache/camel-k/v2/pkg/internal" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -81,7 +81,7 @@ func TestBindingConverter(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) endpoint := v1.Endpoint{ @@ -243,7 +243,7 @@ func TestBindingConverterWithDataTypes(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) endpoint := v1.Endpoint{ @@ -336,7 +336,7 @@ func TestBindingConverterWithDataTypesOverridden(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) endpoint := v1.Endpoint{ diff --git a/pkg/util/bindings/knative_ref.go b/pkg/util/bindings/knative_ref.go index 36e007db0e..2b45ee4cfc 100644 --- a/pkg/util/bindings/knative_ref.go +++ b/pkg/util/bindings/knative_ref.go @@ -167,17 +167,6 @@ func (k KnativeRefBindingProvider) Order() int { return OrderLast } -// V1alpha1KnativeRefBindingProvider converts a reference to a Kubernetes object into a Camel URI. -// It's used as fallback if no other providers can decode the object reference. -// Deprecated. -type V1alpha1KnativeRefBindingProvider struct{} - -// ID --. -// Deprecated. -func (k V1alpha1KnativeRefBindingProvider) ID() string { - return "knative-ref" -} - func init() { RegisterBindingProvider(KnativeRefBindingProvider{}) } diff --git a/pkg/util/bindings/knative_ref_test.go b/pkg/util/bindings/knative_ref_test.go index be0506a7d2..4f9b43af07 100644 --- a/pkg/util/bindings/knative_ref_test.go +++ b/pkg/util/bindings/knative_ref_test.go @@ -28,7 +28,7 @@ import ( "k8s.io/utils/ptr" camelv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" ) func TestKnativeRefAsSource(t *testing.T) { @@ -147,7 +147,7 @@ func TestKnativeRefAsSource(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) bindingContext := BindingContext{ @@ -248,7 +248,7 @@ func TestKnativeRefAsSink(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) bindingContext := BindingContext{ @@ -273,7 +273,7 @@ func TestUnsupportedKnativeResource(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) bindingContext := BindingContext{ @@ -302,11 +302,11 @@ func TestKnativeNotInstalled(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) // disable the knative eventing api - fakeClient := client.(*test.FakeClient) //nolint + fakeClient := client.(*internal.FakeClient) //nolint fakeClient.DisableAPIGroupDiscovery("eventing.knative.dev/v1") bindingContext := BindingContext{ diff --git a/pkg/util/bindings/strimzi_test.go b/pkg/util/bindings/strimzi_test.go index 7730a27818..891b2f7658 100644 --- a/pkg/util/bindings/strimzi_test.go +++ b/pkg/util/bindings/strimzi_test.go @@ -24,8 +24,8 @@ import ( camelv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/apis/duck/strimzi/v1beta2" "github.com/apache/camel-k/v2/pkg/client/duck/strimzi/clientset/internalclientset/fake" + "github.com/apache/camel-k/v2/pkg/internal" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" @@ -36,7 +36,7 @@ func TestStrimziDirect(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - client, err := test.NewFakeClient() + client, err := internal.NewFakeClient() require.NoError(t, err) bindingContext := BindingContext{ diff --git a/pkg/util/camel/camel_runtime_test.go b/pkg/util/camel/camel_runtime_test.go index 35bfc219d9..afa981888a 100644 --- a/pkg/util/camel/camel_runtime_test.go +++ b/pkg/util/camel/camel_runtime_test.go @@ -24,12 +24,12 @@ import ( "testing" "time" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util/boolean" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/apache/camel-k/v2/pkg/util/maven" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -40,7 +40,7 @@ func TestCreateCatalog(t *testing.T) { ip.Status.Build.Timeout = &metav1.Duration{ Duration: 5 * time.Minute, } - c, err := test.NewFakeClient() + c, err := internal.NewFakeClient() require.NoError(t, err) // use local Maven executable in tests t.Setenv("MAVEN_WRAPPER", boolean.FalseString) diff --git a/pkg/util/camel/catalog_test.go b/pkg/util/camel/catalog_test.go index 9470d020d3..c7a3dbc7f1 100644 --- a/pkg/util/camel/catalog_test.go +++ b/pkg/util/camel/catalog_test.go @@ -20,7 +20,9 @@ package camel import ( "testing" + "github.com/apache/camel-k/v2/pkg/util/defaults" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCamelTraitGenerateMavenProjectSucceeds(t *testing.T) { @@ -42,3 +44,19 @@ func TestCamelTraitGenerateMavenProjectSucceeds(t *testing.T) { assert.Equal(t, "generate-catalog", mvnProject.Build.Plugins[0].Executions[0].Goals[0]) assert.Nil(t, mvnProject.Build.Plugins[0].Dependencies) } + +func TestRuntimeContainsEmbeddedArtifacts(t *testing.T) { + catalog, err := DefaultCatalog() + require.NoError(t, err) + + assert.Equal(t, defaults.DefaultRuntimeVersion, catalog.Runtime.Version) + + artifact := catalog.GetArtifactByScheme("knative") + assert.Equal(t, 1, len(artifact.Schemes)) + assert.Equal(t, "org.apache.camel.quarkus", artifact.GroupID) + assert.Equal(t, "camel-quarkus-knative", artifact.ArtifactID) + + scheme, found := catalog.GetScheme("knative") + assert.True(t, found) + assert.True(t, scheme.HTTP) +} diff --git a/pkg/util/defaults/defaults_support.go b/pkg/util/defaults/defaults_support.go index ae81ac7323..e0b18d5d3a 100644 --- a/pkg/util/defaults/defaults_support.go +++ b/pkg/util/defaults/defaults_support.go @@ -18,7 +18,6 @@ limitations under the License. package defaults import ( - "fmt" "os" "strconv" @@ -29,14 +28,6 @@ func BaseImage() string { return envOrDefault(baseImage, "KAMEL_BASE_IMAGE", "RELATED_IMAGE_BASE") } -func IsBaseImageDefault() bool { - return baseImage == BaseImage() -} - -func OperatorImage() string { - return envOrDefault(fmt.Sprintf("%s:%s", ImageName, Version), "KAMEL_OPERATOR_IMAGE", "KAMEL_K_TEST_OPERATOR_CURRENT_IMAGE") -} - func InstallDefaultKamelets() bool { return boolEnvOrDefault(installDefaultKamelets, "KAMEL_INSTALL_DEFAULT_KAMELETS") } diff --git a/pkg/util/defaults/defaults_test.go b/pkg/util/defaults/defaults_test.go index 6975665600..24009e200c 100644 --- a/pkg/util/defaults/defaults_test.go +++ b/pkg/util/defaults/defaults_test.go @@ -28,7 +28,7 @@ import ( func TestDefaultBaseImage(t *testing.T) { assert.NotEmpty(t, BaseImage()) - assert.True(t, IsBaseImageDefault()) + assert.True(t, isBaseImageDefault()) } func TestOverriddenBaseImage(t *testing.T) { @@ -37,7 +37,7 @@ func TestOverriddenBaseImage(t *testing.T) { overriddenImage := "xxx" require.NoError(t, os.Setenv(env, overriddenImage)) assert.Equal(t, overriddenImage, BaseImage()) - assert.False(t, IsBaseImageDefault()) + assert.False(t, isBaseImageDefault()) require.NoError(t, os.Setenv(env, oldEnvVal)) } @@ -61,3 +61,7 @@ func TestOverriddenOperatorID(t *testing.T) { assert.Equal(t, overriddenID, OperatorID()) require.NoError(t, os.Setenv(env, oldEnvVal)) } + +func isBaseImageDefault() bool { + return baseImage == BaseImage() +} diff --git a/pkg/util/docker/docker.go b/pkg/util/docker/docker.go deleted file mode 100644 index f4eb5e39cd..0000000000 --- a/pkg/util/docker/docker.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package docker - -import ( - "errors" - "os/exec" - "path/filepath" - "strings" - - "github.com/apache/camel-k/v2/pkg/util" - "github.com/apache/camel-k/v2/pkg/util/defaults" -) - -// CreateBaseImageDockerFile --. -func CreateBaseImageDockerFile() error { - dockerFile := []string{} - - // Base image is a java-only image since the integration command is just a java command. - dockerFile = append(dockerFile, FROM(defaults.BaseImage())) - - // Ensure Maven is already installed. - dockerFile = append(dockerFile, RUNMavenInstall()) - - // Write /Dockerfile - baseDockerFilePath := filepath.Join(BaseWorkingDirectory, "Dockerfile") - if err := util.WriteToFile(baseDockerFilePath, strings.Join(dockerFile, "\n")); err != nil { - return err - } - - return nil -} - -// CreateIntegrationImageDockerFile --. -func CreateIntegrationImageDockerFile(integrationRunCmd *exec.Cmd, startsFromLocalFolder bool) error { - dockerFile := []string{} - - // Start from the base image that contains the maven install: / - dockerFile = append(dockerFile, FROM(GetFullDockerImage(GetBaseImagePath(), latestTag))) - - // Create container workspace directory. - dockerFile = append(dockerFile, RUNMakeDir(GetContainerWorkspaceDir())) - - // Copy files from local directory to container directories. - dockerFile = append(dockerFile, COPY(util.DefaultRoutesDirectoryName, GetContainerRoutesDir())) - dockerFile = append(dockerFile, COPY(util.DefaultPropertiesDirectoryName, GetContainerPropertiesDir())) - dockerFile = append(dockerFile, COPY(util.DefaultDependenciesDirectoryName, GetContainerDependenciesDir())) - - // Copy additional folder structure used for integrations built from a separately built local folder. - if startsFromLocalFolder { - dockerFile = append(dockerFile, RUNMakeDir(util.ContainerQuarkusDirectoryName)) - dockerFile = append(dockerFile, RUNMakeDir(util.ContainerLibDirectoryName)) - dockerFile = append(dockerFile, RUNMakeDir(util.ContainerAppDirectoryName)) - - dockerFile = append(dockerFile, COPY(util.CustomQuarkusDirectoryName, util.ContainerQuarkusDirectoryName)) - dockerFile = append(dockerFile, COPY(util.CustomLibDirectoryName, util.ContainerLibDirectoryName)) - dockerFile = append(dockerFile, COPY(util.CustomAppDirectoryName, util.ContainerAppDirectoryName)) - } - - // All Env variables the command requires need to be set in the container. - for _, keyValue := range integrationRunCmd.Env { - values := strings.Split(keyValue, "=") - dockerFile = append(dockerFile, ENV(values[0], strings.Join(values[1:], "="))) - } - - // Compose command line. - dockerFile = append(dockerFile, CMDShellWrap(strings.Join(integrationRunCmd.Args, " "))) - - // Write /Dockerfile - integrationDockerFilePath := filepath.Join(IntegrationWorkingDirectory, "Dockerfile") - err := util.WriteToFile(integrationDockerFilePath, strings.Join(dockerFile, "\n")) - if err != nil { - return err - } - - return nil -} - -// BuildBaseImageArgs constructs the docker command: -// -// docker build -f /Dockerfile -t / . -func BuildBaseImageArgs() []string { - return BuildImageArgs(BaseWorkingDirectory, GetBaseImagePath(), BaseWorkingDirectory) -} - -// BuildIntegrationImageArgs constructs the docker command: -// -// docker build -f /Dockerfile -t . -func BuildIntegrationImageArgs(imagePath string, mavenWorkingDirectory string) []string { - return BuildImageArgs(IntegrationWorkingDirectory, imagePath, mavenWorkingDirectory) -} - -// RunIntegrationImageArgs constructs the docker command: -// -// docker run --network= --env LAZY_ENV_VAR=value /. -func RunIntegrationImageArgs(imagePath string) ([]string, error) { - return RunImageArgs(imagePath) -} - -// GetContainerWorkspaceDir -- directory inside the container where all the integration files are copied. -func GetContainerWorkspaceDir() string { - return containerFileSeparator + util.DefaultWorkingDirectoryName -} - -// GetContainerPropertiesDir -- directory inside the container where all the integration property files are copied. -func GetContainerPropertiesDir() string { - return util.ContainerPropertiesDirectory -} - -// GetContainerDependenciesDir -- directory inside the container where all the integration dependencies are copied. -func GetContainerDependenciesDir() string { - return util.ContainerDependenciesDirectory -} - -// GetContainerRoutesDir -- directory inside the container where all the integration routes are copied. -func GetContainerRoutesDir() string { - return util.ContainerRoutesDirectory -} - -// ContainerizeFilePaths -- make paths valid container paths given a valid container directory in newDir. -func ContainerizeFilePaths(currentFilePaths []string, newDir string) []string { - newFilePaths := []string{} - for _, currentFilePath := range currentFilePaths { - newFilePaths = append(newFilePaths, newDir+containerFileSeparator+filepath.Base(currentFilePath)) - } - - return newFilePaths -} - -// ContainerizeDependencyPaths -- make dependency paths valid given a valid container directory in newDir. -func ContainerizeDependencyPaths(dependencyPaths []string, newDir string) []string { - newDependencyPaths := []string{} - for _, currentDependencyPath := range dependencyPaths { - newDependencyPath := util.SubstringFrom(currentDependencyPath, util.QuarkusDependenciesBaseDirectory) - if newDependencyPath != "" { - newDependencyPaths = append(newDependencyPaths, newDir+newDependencyPath) - } else { - newDependencyPaths = append(newDependencyPaths, newDir+containerFileSeparator+filepath.Base(currentDependencyPath)) - } - } - return newDependencyPaths -} - -// ExtractRegistryName -- Extract registry name from image path. -func ExtractRegistryName(image string) (string, error) { - pathComponents := strings.Split(image, containerFileSeparator) - - // There must be at least two components in the path: - // - docker.io/registry/imageName - // - localhost:5000//imageName - // - localhost:5000//...//imageName - // - localhost:5000/imageName - if len(pathComponents) < 2 { - return "", errors.New("image path is too short, usage: registry/imageName or registry/*/imageName") - } - - // Registry name is given by the path to the image. - return strings.Join(pathComponents[0:len(pathComponents)-1], containerFileSeparator), nil -} diff --git a/pkg/util/docker/docker_base.go b/pkg/util/docker/docker_base.go deleted file mode 100644 index f297aa05b7..0000000000 --- a/pkg/util/docker/docker_base.go +++ /dev/null @@ -1,261 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package docker - -import ( - "path/filepath" - "strings" - - "github.com/apache/camel-k/v2/pkg/util" -) - -// RegistryName -- the docker registry name. -var RegistryName = "" - -// BaseImageName -- base image name. -var BaseImageName = "integration-base-image" - -// BaseWorkingDirectory -- directory used by Docker to construct the base image. -var BaseWorkingDirectory = "" - -// IntegrationWorkingDirectory -- directory used by Docker to construct the integration image. -var IntegrationWorkingDirectory = "" - -// NetworkName -- network used by Docker when running the image. -var NetworkName = "host" - -// Internal variables. -const ( - dockerEndpointSeparator = "/" - containerFileSeparator = "/" - latestTag = "latest" -) - -// BuildImageArgs - standard docker build arguments. -func BuildImageArgs(dockerFileDir string, imageName string, sourceDir string) []string { - // Construct the docker command: - // - // docker build -f -t - // - args := make([]string, 0) - args = append(args, "build") - - // Add path to Dockerfile: - dockerFile := filepath.Join(dockerFileDir, "Dockerfile") - - args = append(args, DockerfilePathArg(dockerFile)...) - - // Image name: - args = append(args, ImageArg(imageName, "")...) - - // Root of source directory. - args = append(args, sourceDir) - - return args -} - -// RunImageArgs -- standard docker run arguments. -func RunImageArgs(imagePath string) ([]string, error) { - // Construct the docker command: - // - // docker run --network= --env= :latest - // - args := make([]string, 0) - args = append(args, "run") - - // Add network flag. - args = append(args, "--network="+NetworkName) - - setEnvVars, err := util.EvaluateCLIAndLazyEnvVars() - if err != nil { - return nil, err - } - for _, envVar := range setEnvVars { - args = append(args, "--env="+envVar) - } - - // Path to Docker image: - args = append(args, FullImageArg(imagePath)...) - - return args, nil -} - -// -// Arguments to docker command line. -// - -// DockerfilePathArg --. -func DockerfilePathArg(dockerfilePath string) []string { - args := make([]string, 0) - args = append(args, "-f") - args = append(args, dockerfilePath) - return args -} - -// ImageArg --. -func ImageArg(dockerImageName string, tag string) []string { - args := make([]string, 0) - args = append(args, "-t") - args = append(args, GetFullDockerImage(dockerImageName, tag)) - return args -} - -// LatestImageArg --. -func LatestImageArg(dockerImageName string) []string { - args := make([]string, 0) - args = append(args, "-t") - args = append(args, GetFullDockerImage(dockerImageName, latestTag)) - return args -} - -// FullImageArg --. -func FullImageArg(dockerImage string) []string { - imageComponents := strings.Split(dockerImage, ":") - if len(imageComponents) == 2 { - // Image has a tag already. - return ImageArg(imageComponents[0], imageComponents[1]) - } else if len(imageComponents) > 2 { - // Image has an image registry name with a colon inside it: - // localhost:5000 - // and image also has a tag: - // localhost:5000/image:latest - // Assume tag is always included and is last in the imageComponents list. - last := len(imageComponents) - 1 - return ImageArg(strings.Join(imageComponents[:last], ":"), imageComponents[last]) - } - - // Image has no tag, latest tag will be added automatically. - return LatestImageArg(dockerImage) -} - -// -// Docker-spcific helper functions. -// - -// GetImage - :. -func GetImage(dockerImageName string, tag string) string { - image := make([]string, 0) - image = append(image, dockerImageName) - image = append(image, tag) - return strings.Join(image, ":") -} - -// GetLatestImage - :latest. -func GetLatestImage(dockerImageName string) string { - return GetImage(dockerImageName, latestTag) -} - -// GetFullDockerImage - /:. -func GetFullDockerImage(dockerImageName string, tag string) string { - fullImagePath := make([]string, 0) - - // Add image and tag. - if tag == "" { - fullImagePath = append(fullImagePath, dockerImageName) - } else { - fullImagePath = append(fullImagePath, GetImage(dockerImageName, tag)) - } - - return strings.Join(fullImagePath, dockerEndpointSeparator) -} - -// GetBaseImagePath returns Docker base image path. -func GetBaseImagePath() string { - return RegistryName + dockerEndpointSeparator + BaseImageName -} - -// -// Container file management. -// - -// JoinPath -- for container paths. -func JoinPath(lhsPath string, rhsPath string) string { - p := []string{lhsPath, rhsPath} - return strings.Join(p, containerFileSeparator) -} - -// -// Docker syntax functions. -// - -// Generic commands. - -// COPY --. -func COPY(from string, to string) string { - c := []string{"COPY", from, to} - return strings.Join(c, " ") -} - -// RUN --. -func RUN(command string) string { - c := []string{"RUN", command} - return strings.Join(c, " ") -} - -// FROM --. -func FROM(imageName string) string { - c := []string{"FROM", imageName} - return strings.Join(c, " ") -} - -// WORKDIR --. -func WORKDIR(workDir string) string { - c := []string{"WORKDIR", workDir} - return strings.Join(c, " ") -} - -// ENV --. -func ENV(envVar string, value string) string { - p := []string{envVar, value} - c := []string{"ENV", strings.Join(p, "=")} - return strings.Join(c, " ") -} - -// AS --. -func AS(image string, alias string) string { - c := []string{image, "as", alias} - return strings.Join(c, " ") -} - -// CMD --. -func CMD(command string) string { - c := []string{"CMD", command} - return strings.Join(c, " ") -} - -// RUNMavenInstall --. -func RUNMavenInstall() string { - return RUN("apt-get update && apt-get install maven -y && apt-get upgrade -y") -} - -// RUNMakeDir --. -func RUNMakeDir(dirName string) string { - c := []string{"mkdir", "-p", dirName} - return RUN(strings.Join(c, " ")) -} - -// ENVAppend --. -func ENVAppend(envVar string, value string) string { - tail := []string{value, "$" + envVar} - return ENV(envVar, strings.Join(tail, ":")) -} - -// CMDShellWrap --. -func CMDShellWrap(command string) string { - return CMD("/bin/sh -c \"" + command + "\"") -} diff --git a/pkg/util/docker/docker_base_test.go b/pkg/util/docker/docker_base_test.go deleted file mode 100644 index 537d31408c..0000000000 --- a/pkg/util/docker/docker_base_test.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package docker - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestBuildImageArgs(t *testing.T) { - - args := BuildImageArgs("dockerfileDirectory", "imageName", "sourceDirectory") - assert.Equal(t, "build", args[0]) - assert.Equal(t, "-f", args[1]) - assert.Equal(t, "dockerfileDirectory/Dockerfile", args[2]) - assert.Equal(t, "-t", args[3]) - assert.Equal(t, "imageName", args[4]) - assert.Equal(t, "sourceDirectory", args[5]) -} - -func TestRunImageArgs(t *testing.T) { - - args, err := RunImageArgs("imagePath") - require.NoError(t, err) - assert.Equal(t, "run", args[0]) - assert.Equal(t, "--network="+NetworkName, args[1]) - assert.Equal(t, "-t", args[2]) - assert.Equal(t, "imagePath:latest", args[3]) -} - -func TestDockerfilePathArg(t *testing.T) { - args := DockerfilePathArg("path/docker") - assert.Equal(t, "-f", args[0]) - assert.Equal(t, "path/docker", args[1]) -} - -func TestImageArg(t *testing.T) { - args := ImageArg("imageName", "tag") - assert.Equal(t, "-t", args[0]) - assert.Equal(t, "imageName:tag", args[1]) -} - -func TestLatestImageArg(t *testing.T) { - args := LatestImageArg("imageName") - assert.Equal(t, "-t", args[0]) - assert.Equal(t, "imageName:latest", args[1]) -} - -func TestFullImageArg(t *testing.T) { - args := FullImageArg("dir/imageName:tag") - assert.Equal(t, "-t", args[0]) - assert.Equal(t, "dir/imageName:tag", args[1]) - - args = FullImageArg("imageName:tag") - assert.Equal(t, "-t", args[0]) - assert.Equal(t, "imageName:tag", args[1]) - - args = FullImageArg("imageName") - assert.Equal(t, "-t", args[0]) - assert.Equal(t, "imageName:latest", args[1]) -} - -func TestGetImage(t *testing.T) { - image := GetImage("imageName", "tag") - assert.Equal(t, "imageName:tag", image) - assert.Equal(t, GetImage("imageName", "latest"), GetLatestImage("imageName")) -} - -func TestGetFullDockerImage(t *testing.T) { - image := GetFullDockerImage("dir/dir/imageName", "tag") - assert.Equal(t, "dir/dir/imageName:tag", image) - image = GetFullDockerImage("imageName", "tag") - assert.Equal(t, "imageName:tag", image) -} - -func TestJoinPath(t *testing.T) { - path := JoinPath("path1", "dir/path2") - assert.Equal(t, "path1/dir/path2", path) -} diff --git a/pkg/util/docker/docker_test.go b/pkg/util/docker/docker_test.go deleted file mode 100644 index be83afd1de..0000000000 --- a/pkg/util/docker/docker_test.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package docker - -import ( - "os" - "os/exec" - "path/filepath" - "strings" - "testing" - - "github.com/apache/camel-k/v2/pkg/util" - "github.com/apache/camel-k/v2/pkg/util/defaults" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCreateBaseImageDockerFile(t *testing.T) { - - dockerfileExists, _ := util.FileExists("/tmp/Dockerfile") - if dockerfileExists { - os.Remove("/tmp/Dockerfile") - } - - dockerFile := []string{} - dockerFile = append(dockerFile, FROM(defaults.BaseImage())) - dockerFile = append(dockerFile, RUNMavenInstall()) - expected := strings.Join(dockerFile, "\n") - - BaseWorkingDirectory = "/tmp/" - - err := CreateBaseImageDockerFile() - require.NoError(t, err) - baseDockerFilePath := filepath.Join(BaseWorkingDirectory, "Dockerfile") - - c, err := util.ReadFile(baseDockerFilePath) - - require.NoError(t, err) - assert.Equal(t, expected, string(c)) - - os.Remove("/tmp/Dockerfile") -} - -func TestCreateIntegrationImageDockerFile(t *testing.T) { - dockerfileExists, _ := util.FileExists("/tmp/Dockerfile") - if dockerfileExists { - os.Remove("/tmp/Dockerfile") - } - IntegrationWorkingDirectory = "/tmp/" - var cmd exec.Cmd - cmd.Path = "test" - cmd.Env = []string{"key=value"} - cmd.Args = []string{"-t"} - dockerFile1 := []string{} - dockerFile1 = append(dockerFile1, FROM(GetFullDockerImage(GetBaseImagePath(), latestTag))) - dockerFile1 = append(dockerFile1, RUNMakeDir(GetContainerWorkspaceDir())) - dockerFile1 = append(dockerFile1, COPY(util.DefaultRoutesDirectoryName, GetContainerRoutesDir())) - dockerFile1 = append(dockerFile1, COPY(util.DefaultPropertiesDirectoryName, GetContainerPropertiesDir())) - dockerFile1 = append(dockerFile1, COPY(util.DefaultDependenciesDirectoryName, GetContainerDependenciesDir())) - - dockerFile2 := dockerFile1 - dockerFile2 = append(dockerFile2, RUNMakeDir(util.ContainerQuarkusDirectoryName)) - dockerFile2 = append(dockerFile2, RUNMakeDir(util.ContainerLibDirectoryName)) - dockerFile2 = append(dockerFile2, RUNMakeDir(util.ContainerAppDirectoryName)) - dockerFile2 = append(dockerFile2, COPY(util.CustomQuarkusDirectoryName, util.ContainerQuarkusDirectoryName)) - dockerFile2 = append(dockerFile2, COPY(util.CustomLibDirectoryName, util.ContainerLibDirectoryName)) - dockerFile2 = append(dockerFile2, COPY(util.CustomAppDirectoryName, util.ContainerAppDirectoryName)) - - for _, keyValue := range cmd.Env { - values := strings.Split(keyValue, "=") - dockerFile1 = append(dockerFile1, ENV(values[0], strings.Join(values[1:], "="))) - dockerFile2 = append(dockerFile2, ENV(values[0], strings.Join(values[1:], "="))) - } - dockerFile1 = append(dockerFile1, CMDShellWrap(strings.Join(cmd.Args, " "))) - dockerFile2 = append(dockerFile2, CMDShellWrap(strings.Join(cmd.Args, " "))) - - expected := strings.Join(dockerFile1, "\n") - - err := CreateIntegrationImageDockerFile(&cmd, false) - require.NoError(t, err) - - c, err := util.ReadFile("/tmp/Dockerfile") - require.NoError(t, err) - assert.Equal(t, expected, string(c)) - - os.Remove("/tmp/Dockerfile") - - expected = strings.Join(dockerFile2, "\n") - - err = CreateIntegrationImageDockerFile(&cmd, true) - require.NoError(t, err) - - c, err = util.ReadFile("/tmp/Dockerfile") - require.NoError(t, err) - assert.Equal(t, expected, string(c)) - - os.Remove("/tmp/Dockerfile") - -} - -func TestContainerizeFilePaths(t *testing.T) { - expected := []string{"home/quarkus-app"} - - dependencyPaths := []string{"test1/quarkus-app"} - newDir := "home" - result := ContainerizeFilePaths(dependencyPaths, newDir) - - assert.Equal(t, expected, result) -} - -func TestContainerizeDependencyPaths(t *testing.T) { - expected := []string{"home/quarkus-app", "home/not-quarkus-app"} - - dependencyPaths := []string{"test1/quarkus-app", "not-quarkus-app"} - newDir := "home" - result := ContainerizeDependencyPaths(dependencyPaths, newDir) - - assert.Equal(t, expected, result) -} - -func TestExtractRegistryName(t *testing.T) { - expected := "localhost:5000" - - result, err := ExtractRegistryName("localhost:5000/imageName") - require.NoError(t, err) - assert.Equal(t, expected, result) - - _, err = ExtractRegistryName("imageName") - require.Error(t, err) -} diff --git a/pkg/util/envvar/envvar.go b/pkg/util/envvar/envvar.go index 5552de8c68..fecd1ebf79 100644 --- a/pkg/util/envvar/envvar.go +++ b/pkg/util/envvar/envvar.go @@ -33,18 +33,6 @@ func Get(vars []corev1.EnvVar, name string) *corev1.EnvVar { return nil } -// Remove --. -func Remove(vars *[]corev1.EnvVar, name string) { - v := *vars - for i := 0; i < len(v); i++ { - if v[i].Name == name { - v = append(v[:i], v[i+1:]...) - *vars = v - return - } - } -} - // SetVal --. func SetVal(vars *[]corev1.EnvVar, name string, value string) { if envVar := Get(*vars, name); envVar != nil { diff --git a/pkg/util/jib/configuration_test.go b/pkg/util/jib/configuration_test.go index 9461083d46..77ba3a9c7c 100644 --- a/pkg/util/jib/configuration_test.go +++ b/pkg/util/jib/configuration_test.go @@ -23,7 +23,7 @@ import ( "testing" v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" - "github.com/apache/camel-k/v2/pkg/util/test" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -56,7 +56,7 @@ func TestJibMavenProfileDefaultValues(t *testing.T) { func TestJibConfigMap(t *testing.T) { ctx := context.TODO() - c, _ := test.NewFakeClient() + c, _ := internal.NewFakeClient() kit := &v1.IntegrationKit{ TypeMeta: metav1.TypeMeta{ APIVersion: v1.SchemeGroupVersion.String(), diff --git a/pkg/util/kubernetes/factory.go b/pkg/util/kubernetes/factory.go index 9c0e504975..2822a4332b 100644 --- a/pkg/util/kubernetes/factory.go +++ b/pkg/util/kubernetes/factory.go @@ -125,38 +125,6 @@ func NewResourceRequirements(reqs []string) (corev1.ResourceRequirements, error) return resReq, nil } -// NewConfigMap will create a ConfigMap. -func NewConfigMap(namespace, cmName, originalFilename string, generatedKey string, - textData string, binaryData []byte) *corev1.ConfigMap { - immutable := true - cm := corev1.ConfigMap{ - TypeMeta: metav1.TypeMeta{ - Kind: "ConfigMap", - APIVersion: "v1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: cmName, - Namespace: namespace, - Labels: map[string]string{ - ConfigMapOriginalFileNameLabel: originalFilename, - ConfigMapAutogenLabel: "true", - }, - }, - Immutable: &immutable, - } - if textData != "" { - cm.Data = map[string]string{ - generatedKey: textData, - } - } - if binaryData != nil { - cm.BinaryData = map[string][]byte{ - generatedKey: binaryData, - } - } - return &cm -} - // NewPersistentVolumeClaim will create a NewPersistentVolumeClaim based on a StorageClass. func NewPersistentVolumeClaim( ns, name, storageClassName string, capacityStorage resource.Quantity, accessMode corev1.PersistentVolumeAccessMode) *corev1.PersistentVolumeClaim { diff --git a/pkg/util/kubernetes/loader.go b/pkg/util/kubernetes/loader.go index e076eab5da..9eed3da424 100644 --- a/pkg/util/kubernetes/loader.go +++ b/pkg/util/kubernetes/loader.go @@ -18,7 +18,6 @@ limitations under the License. package kubernetes import ( - "encoding/json" "fmt" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -53,21 +52,6 @@ func LoadResourceFromYaml(scheme *runtime.Scheme, data string) (ctrl.Object, err return o, nil } -// LoadUnstructuredFromYaml returns an unstructured resource from its serialized YAML definition. -func LoadUnstructuredFromYaml(data string) (ctrl.Object, error) { - source, err := yaml.ToJSON([]byte(data)) - if err != nil { - return nil, err - } - var obj map[string]interface{} - if err = json.Unmarshal(source, &obj); err != nil { - return nil, err - } - return &unstructured.Unstructured{ - Object: obj, - }, nil -} - func runtimeObjectFromUnstructured(scheme *runtime.Scheme, u *unstructured.Unstructured) (runtime.Object, error) { gvk := u.GroupVersionKind() codecs := serializer.NewCodecFactory(scheme) diff --git a/pkg/util/log/log.go b/pkg/util/log/log.go index 0c54d43df4..32027cff10 100644 --- a/pkg/util/log/log.go +++ b/pkg/util/log/log.go @@ -205,11 +205,6 @@ func ForIntegrationKit(target *v1.IntegrationKit) Logger { return Log.ForIntegrationKit(target) } -// ForIntegrationPlatform --. -func ForIntegrationPlatform(target *v1.IntegrationPlatform) Logger { - return Log.ForIntegrationPlatform(target) -} - // *********************************** // // diff --git a/pkg/util/registry/registry_test.go b/pkg/util/registry/registry_test.go index 7c52705dc1..fe2c4c80d3 100644 --- a/pkg/util/registry/registry_test.go +++ b/pkg/util/registry/registry_test.go @@ -22,8 +22,8 @@ import ( "os" "testing" + "github.com/apache/camel-k/v2/pkg/internal" "github.com/apache/camel-k/v2/pkg/util" - "github.com/apache/camel-k/v2/pkg/util/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" @@ -99,7 +99,7 @@ func TestMountSecretRegistryConfig(t *testing.T) { }, } - c, err := test.NewFakeClient(&namespace, &secret) + c, err := internal.NewFakeClient(&namespace, &secret) require.NoError(t, err) assert.NotNil(t, c) registryConfigDir, err := MountSecretRegistryConfig(ctx, c, "test", "prefix-", "my-secret1") diff --git a/pkg/util/resource/config.go b/pkg/util/resource/config.go index 61c61217f3..c05651ebd3 100644 --- a/pkg/util/resource/config.go +++ b/pkg/util/resource/config.go @@ -136,21 +136,6 @@ func ParseResource(item string) (*Config, error) { return parse(item, ContentTypeData) } -// ParseVolume will parse a volume and return a Config. -func ParseVolume(item string) (*Config, error) { - configParts := strings.Split(item, ":") - - if len(configParts) != 2 { - return nil, fmt.Errorf("could not match pvc as %s", item) - } - - return &Config{ - storageType: StorageTypePVC, - resourceName: configParts[0], - destinationPath: configParts[1], - }, nil -} - // ParseConfig will parse a config and return a Config. func ParseConfig(item string) (*Config, error) { return parse(item, ContentTypeText) diff --git a/pkg/util/source/kamelet.go b/pkg/util/source/kamelet.go index d44f542a2c..d220bc5ba1 100644 --- a/pkg/util/source/kamelet.go +++ b/pkg/util/source/kamelet.go @@ -27,17 +27,6 @@ import ( var kameletNameRegexp = regexp.MustCompile("kamelet:(?://)?([a-z0-9-.]+(/[a-z0-9-.]+)?)(?:$|[^a-z0-9-.].*)") var kameletVersionRegexp = regexp.MustCompile(v1.KameletVersionProperty + "=([a-z0-9-.]+)") -func ExtractKamelets(uris []string) []string { - var kamelets []string - for _, uri := range uris { - kamelet := ExtractKamelet(uri) - if kamelet != "" { - kamelets = append(kamelets, kamelet) - } - } - return kamelets -} - func ExtractKamelet(uri string) string { matches := kameletNameRegexp.FindStringSubmatch(uri) if len(matches) > 1 { diff --git a/pkg/util/source/test_support.go b/pkg/util/source/source_support_test.go similarity index 100% rename from pkg/util/source/test_support.go rename to pkg/util/source/source_support_test.go diff --git a/pkg/util/test/assertions.go b/pkg/util/test/assertions.go deleted file mode 100644 index f5b652afe0..0000000000 --- a/pkg/util/test/assertions.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package test - -import ( - "testing" - - "github.com/apache/camel-k/v2/pkg/util/envvar" - "github.com/stretchr/testify/assert" - - corev1 "k8s.io/api/core/v1" -) - -// EnvVarExists --. -func EnvVarExists(t *testing.T, env []corev1.EnvVar, name string) { - t.Helper() - - ev := envvar.Get(env, name) - assert.NotNil(t, ev) -} - -// EnvVarHasValue --. -func EnvVarHasValue(t *testing.T, env []corev1.EnvVar, name string, val string) { - t.Helper() - - ev := envvar.Get(env, name) - assert.NotNil(t, ev) - assert.Equal(t, val, ev.Value) -} - -// HasVolume --. -func HasVolume(t *testing.T, volumes []corev1.Volume, name string) { - t.Helper() - - assert.Condition(t, func() bool { - for _, v := range volumes { - if v.Name == name { - return true - } - } - return false - }) -} diff --git a/pkg/util/test/catalog_test.go b/pkg/util/test/catalog_test.go deleted file mode 100644 index 27c7777580..0000000000 --- a/pkg/util/test/catalog_test.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package test - -import ( - "testing" - - "github.com/apache/camel-k/v2/pkg/util/camel" - "github.com/apache/camel-k/v2/pkg/util/defaults" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestRuntimeContainsEmbeddedArtifacts(t *testing.T) { - catalog, err := camel.DefaultCatalog() - require.NoError(t, err) - - assert.Equal(t, defaults.DefaultRuntimeVersion, catalog.Runtime.Version) - - artifact := catalog.GetArtifactByScheme("knative") - assert.Equal(t, 1, len(artifact.Schemes)) - assert.Equal(t, "org.apache.camel.quarkus", artifact.GroupID) - assert.Equal(t, "camel-quarkus-knative", artifact.ArtifactID) - - scheme, found := catalog.GetScheme("knative") - assert.True(t, found) - assert.True(t, scheme.HTTP) -} diff --git a/pkg/util/util.go b/pkg/util/util.go index ff550bf628..96fdcd8159 100644 --- a/pkg/util/util.go +++ b/pkg/util/util.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/fs" "math" "math/rand" "os" @@ -97,10 +96,6 @@ var QuarkusDependenciesBaseDirectory = "/quarkus-app" // are evaluated at the time of the integration invocation. var ListOfLazyEvaluatedEnvVars []string -// CLIEnvVars -- List of CLI provided environment variables. They take precedence over -// any environment variables with the same name. -var CLIEnvVars = make([]string, 0) - func StringSliceJoin(slices ...[]string) []string { size := 0 @@ -137,16 +132,6 @@ func StringSliceExists(slice []string, item string) bool { return false } -func StringContainsPrefix(slice []string, prefix string) bool { - for i := range slice { - if strings.HasPrefix(slice[i], prefix) { - return true - } - } - - return false -} - func StringSliceContainsAnyOf(slice []string, items ...string) bool { for i := range slice { for j := range items { @@ -188,15 +173,6 @@ func StringSliceUniqueConcat(slice *[]string, items []string) bool { return changed } -func SubstringFrom(s string, substr string) string { - index := strings.Index(s, substr) - if index != -1 { - return s[index:] - } - - return "" -} - func SubstringBefore(s string, substr string) string { index := strings.LastIndex(s, substr) if index != -1 { @@ -215,7 +191,6 @@ const ( ) var randomSource = rand.NewSource(time.Now().UnixNano()) -var randomSourceUTC = rand.NewSource(time.Now().UTC().UnixNano()) func RandomString(n int) string { sb := strings.Builder{} @@ -235,10 +210,6 @@ func RandomString(n int) string { return sb.String() } -func RandomInt63() int64 { - return randomSourceUTC.Int63() -} - func EncodeXMLWithoutHeader(content interface{}) ([]byte, error) { return encodeXML(content, "") } @@ -304,42 +275,6 @@ func CopyFile(src, dst string) (int64, error) { return nBytes, err } -func CopyDir(src, dst string) error { - entries, err := os.ReadDir(src) - if err != nil { - return err - } - - for _, entry := range entries { - srcEntry := filepath.Join(src, entry.Name()) - dstEntry := filepath.Join(dst, entry.Name()) - realEntry := entry - if entry.Type() == os.ModeSymlink { - realPath, err := filepath.EvalSymlinks(srcEntry) - if err != nil { - return err - } - realInfo, err := os.Stat(realPath) - if err != nil { - return err - } - srcEntry = realPath - realEntry = fs.FileInfoToDirEntry(realInfo) - } - if realEntry.IsDir() { - if err := CopyDir(srcEntry, dstEntry); err != nil { - return err - } - } else { - if _, err := CopyFile(srcEntry, dstEntry); err != nil { - return err - } - } - } - - return nil -} - func WriteFileWithBytesMarshallerContent(basePath string, filePath string, content BytesMarshaller) error { data, err := content.MarshalBytes() if err != nil { @@ -416,27 +351,6 @@ func DirectoryEmpty(directory string) (bool, error) { return ok, err } -// CreateDirectory creates a directory if it does not exist. -func CreateDirectory(directory string) error { - if directory == "" { - return errors.New("directory name must not be empty") - } - - directoryExists, err := DirectoryExists(directory) - if err != nil { - return err - } - - if !directoryExists { - // #nosec G301 - if err := os.MkdirAll(directory, io2.FilePerm755); err != nil { - return err - } - } - - return nil -} - type BytesMarshaller interface { MarshalBytes() ([]byte, error) } @@ -525,45 +439,6 @@ func GetEnvironmentVariable(variable string) (string, error) { return value, nil } -// EvaluateCLIAndLazyEnvVars creates a list of environment -// variables with entries VAR=value that can be passed when running the integration. -func EvaluateCLIAndLazyEnvVars() ([]string, error) { - evaluatedEnvVars := []string{} - - // Add CLI environment variables - setEnvVars := []string{} - for _, cliEnvVar := range CLIEnvVars { - // Mark variable name as set. - varAndValue := strings.Split(cliEnvVar, "=") - setEnvVars = append(setEnvVars, varAndValue[0]) - - evaluatedEnvVars = append(evaluatedEnvVars, cliEnvVar) - } - - // Add lazily evaluated environment variables if they have not - // already been set via the CLI --env option. - for _, lazyEnvVar := range ListOfLazyEvaluatedEnvVars { - alreadySet := false - for _, setEnvVar := range setEnvVars { - if setEnvVar == lazyEnvVar { - alreadySet = true - - break - } - } - - if !alreadySet { - value, err := GetEnvironmentVariable(lazyEnvVar) - if err != nil { - return nil, err - } - evaluatedEnvVars = append(evaluatedEnvVars, lazyEnvVar+"="+value) - } - } - - return evaluatedEnvVars, nil -} - // Open a safe wrapper of os.Open. func Open(name string) (*os.File, error) { return os.Open(filepath.Clean(name)) diff --git a/pkg/util/util_test.go b/pkg/util/util_test.go index 6d9c418014..7f8ce7313f 100644 --- a/pkg/util/util_test.go +++ b/pkg/util/util_test.go @@ -18,10 +18,8 @@ limitations under the License. package util import ( - "fmt" "math" - "os" - "path/filepath" + "strings" "testing" "github.com/apache/camel-k/v2/pkg/util/defaults" @@ -31,8 +29,8 @@ import ( func TestStringContainsPrefix(t *testing.T) { args := []string{"install", "--operator-image=xxx/yyy:zzz", "--registry", defaults.OpenShiftRegistryAddress} - assert.True(t, StringContainsPrefix(args, "--operator-image=")) - assert.False(t, StringContainsPrefix(args, "--olm")) + assert.True(t, stringContainsPrefix(args, "--operator-image=")) + assert.False(t, stringContainsPrefix(args, "--olm")) } func TestRandomString(t *testing.T) { @@ -40,29 +38,12 @@ func TestRandomString(t *testing.T) { assert.NotEqual(t, RandomString(10), RandomString(10)) } -func TestSubstringFrom(t *testing.T) { - assert.Equal(t, "/bbb/ccc", SubstringFrom("aaa/bbb/ccc", "/")) - assert.Empty(t, SubstringFrom("aaa/bbb/ccc", "?")) -} - func TestSubstringBefore(t *testing.T) { assert.Equal(t, "aaa/bbb", SubstringBefore("aaa/bbb/ccc", "/")) assert.Equal(t, "aaa/bbb", SubstringBefore("aaa/bbb?ccc=ddd", "?")) assert.Empty(t, SubstringBefore("aaa/bbb/ccc", "?")) } -func TestCopyDir(t *testing.T) { - srcDir := "../../install" - tmpDir, err := os.MkdirTemp("", "TestCopyDir-*") - defer os.RemoveAll(tmpDir) - destDir := filepath.Join(tmpDir, "install") - - require.NoError(t, err) - fmt.Println(destDir) - err = CopyDir(srcDir, destDir) - require.NoError(t, err) -} - func TestIToInt32(t *testing.T) { x := 6000 converted, err := IToInt32(x) @@ -92,3 +73,13 @@ func TestIToInt8(t *testing.T) { require.Error(t, err) assert.Equal(t, "integer overflow casting to int8 type", err.Error()) } + +func stringContainsPrefix(slice []string, prefix string) bool { + for i := range slice { + if strings.HasPrefix(slice[i], prefix) { + return true + } + } + + return false +} diff --git a/script/Makefile b/script/Makefile index 8f57fc1009..7399de483f 100644 --- a/script/Makefile +++ b/script/Makefile @@ -36,6 +36,7 @@ KUSTOMIZE_VERSION := v4.5.4 OPM_VERSION := v1.24.0 # Golang tooling LINTER ?= $(LOCALBIN)/golangci-lint +DEADCODE ?= $(LOCALBIN)/deadcode GOVULNCHECK ?= $(LOCALBIN)/govulncheck GOIMPORT ?= $(LOCALBIN)/goimports LINTER_VERSION ?= v1.61.0 @@ -411,6 +412,11 @@ fmt: goimport $(GOIMPORT) -l -w . go fmt ./... +dead-code: + GOBIN=$(LOCALBIN) go install golang.org/x/tools/cmd/deadcode@latest + GOGC=$(LINT_GOGC) $(DEADCODE) ./... + + dir-licenses: ./script/vendor-license-directory.sh