Skip to content

Commit

Permalink
chore: remove dead code
Browse files Browse the repository at this point in the history
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
  • Loading branch information
squakez committed Nov 16, 2024
1 parent 07e73b2 commit 7bc20b9
Show file tree
Hide file tree
Showing 133 changed files with 2,238 additions and 2,077 deletions.
18 changes: 16 additions & 2 deletions addons/addons_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ limitations under the License.
package addons

import (
"encoding/json"
"testing"

"github.com/apache/camel-k/v2/addons/master"
Expand All @@ -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,
}),
},
Expand All @@ -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
}
299 changes: 299 additions & 0 deletions addons/keda/client_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
5 changes: 0 additions & 5 deletions addons/keda/duck/v1alpha1/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 1 addition & 2 deletions addons/keda/keda_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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))
}
Expand Down
Loading

0 comments on commit 7bc20b9

Please sign in to comment.