Skip to content

Commit

Permalink
Check dangling service with endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
marcmognol committed Mar 15, 2024
1 parent c941842 commit a5dc994
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkg/lintcontext/mocks/endpoints.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package mocks

import (
"testing"

"github.com/stretchr/testify/require"
coreV1 "k8s.io/api/core/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// AddMockEndpoint adds a mock Endpoint to LintContext
func (l *MockLintContext) AddMockEndpoints(t *testing.T, name string) {
require.NotEmpty(t, name)
l.objects[name] = &coreV1.Endpoints{
ObjectMeta: metaV1.ObjectMeta{Name: name},
}
}
13 changes: 13 additions & 0 deletions pkg/templates/danglingservice/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ func init() {
return []diagnostic.Diagnostic{{
Message: "service has no selector specified",
}}
} else {
for _, obj := range lintCtx.Objects() {
if obj.(type) = *batchV1Beta1.Endpoints {
continue
}
if service.Namespace != obj.K8sObject.GetNamespace() {
continue
}
if service.Spec.Name == endpointTemplateSpec.Spec.Name {
// Found!
return nil
}
}
}

for _, ignoredLabel := range p.IgnoredLabels {
Expand Down
20 changes: 20 additions & 0 deletions pkg/templates/danglingservice/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
)

const (
endpoint1 = "endpoint1"
pod1 = "pod1"
pod2 = "pod2"
serviceNone = "service-matches-none"
Expand Down Expand Up @@ -52,6 +53,10 @@ func (s *DanglingServiceTestSuite) AddService(name string, podLabels map[string]
})
}

func (s *DanglingServiceTestSuite) AddEndpoints(name string) {
s.ctx.AddMockEndpoints(s.T(), name)
}

func (s *DanglingServiceTestSuite) AddDeploymentWithLabels(name string, labels map[string]string) {
s.ctx.AddMockDeployment(s.T(), name)
s.ctx.ModifyDeployment(s.T(), name, func(deployment *appsV1.Deployment) {
Expand Down Expand Up @@ -93,6 +98,21 @@ func (s *DanglingServiceTestSuite) TestNoDanglingServices() {
})
}

func (s *DanglingServiceTestSuite) TestNoDanglingServiceWithEndpoints() {
s.AddService(endpoint1, nil)
s.AddEndpoints(endpoint1)

s.Validate(s.ctx, []templates.TestCase{
{
Param: params.Params{},
Diagnostics: map[string][]diagnostic.Diagnostic{
endpoint1: {},
},
ExpectInstantiationError: false,
},
})
}

func (s *DanglingServiceTestSuite) TestOneServiceIsDangling() {
s.AddDeploymentWithLabels(pod2, labelselector2)
s.AddService(service1, labelselector1)
Expand Down

0 comments on commit a5dc994

Please sign in to comment.