diff --git a/.golangci.yml b/.golangci.yml index 61b8bd008..844fcf29a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,7 +10,7 @@ linters: - govet - ineffassign - misspell - - revive + - revive # https://golangci-lint.run/docs/linters/configuration/#revive - recvcheck # Checks for receiver type consistency. https://golangci-lint.run/docs/linters/configuration/#recvcheck - rowserrcheck # Checks whether Rows.Err of rows is checked successfully. - errchkjson # Checks types passed to the json encoding functions. ref: https://golangci-lint.run/docs/linters/configuration/#errchkjson @@ -44,6 +44,8 @@ linters: rules: - name: confusing-naming disabled: true + - name: unused-parameter # https://github.com/mgechev/revive/blob/HEAD/RULES_DESCRIPTIONS.md#unused-parameter + disabled: false cyclop: # Lower cyclomatic complexity threshold after the max complexity is lowered max-complexity: 37 # Controller/execute.go:147:1: calculated cyclomatic complexity for function buildProvider is 37 goconst: @@ -86,7 +88,6 @@ linters: - staticcheck - structcheck - unconvert - - unused - varcheck - whitespace - goconst diff --git a/controller/controller_test.go b/controller/controller_test.go index cd646deaa..65ed95c29 100644 --- a/controller/controller_test.go +++ b/controller/controller_test.go @@ -58,19 +58,19 @@ func (p *filteredMockProvider) GetDomainFilter() endpoint.DomainFilterInterface } // Records returns the desired mock endpoints. -func (p *filteredMockProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p *filteredMockProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { p.RecordsCallCount++ return p.RecordsStore, nil } // ApplyChanges stores all calls for later check -func (p *filteredMockProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (p *filteredMockProvider) ApplyChanges(_ context.Context, changes *plan.Changes) error { p.ApplyChangesCalls = append(p.ApplyChangesCalls, changes) return nil } // Records returns the desired mock endpoints. -func (p *mockProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p *mockProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { return p.RecordsStore, nil } @@ -502,7 +502,7 @@ func (r *toggleRegistry) Records(_ context.Context) ([]*endpoint.Endpoint, error return []*endpoint.Endpoint{}, nil } -func (r *toggleRegistry) ApplyChanges(_ context.Context, changes *plan.Changes) error { +func (r *toggleRegistry) ApplyChanges(_ context.Context, _ *plan.Changes) error { return nil } diff --git a/controller/execute.go b/controller/execute.go index c40dbb3bc..bbd67f6f8 100644 --- a/controller/execute.go +++ b/controller/execute.go @@ -250,7 +250,7 @@ func buildProvider( case "digitalocean": p, err = digitalocean.NewDigitalOceanProvider(ctx, domainFilter, cfg.DryRun, cfg.DigitalOceanAPIPageSize) case "ovh": - p, err = ovh.NewOVHProvider(ctx, domainFilter, cfg.OVHEndpoint, cfg.OVHApiRateLimit, cfg.OVHEnableCNAMERelative, cfg.DryRun) + p, err = ovh.NewOVHProvider(domainFilter, cfg.OVHEndpoint, cfg.OVHApiRateLimit, cfg.OVHEnableCNAMERelative, cfg.DryRun) case "linode": p, err = linode.NewLinodeProvider(domainFilter, cfg.DryRun) case "dnsimple": @@ -327,11 +327,11 @@ func buildProvider( case "transip": p, err = transip.NewTransIPProvider(cfg.TransIPAccountName, cfg.TransIPPrivateKeyFile, domainFilter, cfg.DryRun) case "scaleway": - p, err = scaleway.NewScalewayProvider(ctx, domainFilter, cfg.DryRun) + p, err = scaleway.NewScalewayProvider(domainFilter, cfg.DryRun) case "godaddy": p, err = godaddy.NewGoDaddyProvider(ctx, domainFilter, cfg.GoDaddyTTL, cfg.GoDaddyAPIKey, cfg.GoDaddySecretKey, cfg.GoDaddyOTE, cfg.DryRun) case "gandi": - p, err = gandi.NewGandiProvider(ctx, domainFilter, cfg.DryRun) + p, err = gandi.NewGandiProvider(domainFilter, cfg.DryRun) case "pihole": p, err = pihole.NewPiholeProvider( pihole.PiholeConfig{ diff --git a/controller/execute_test.go b/controller/execute_test.go index 5b23ddb7b..0148f3fa3 100644 --- a/controller/execute_test.go +++ b/controller/execute_test.go @@ -231,7 +231,7 @@ func TestBuildProvider(t *testing.T) { } func TestBuildSourceWithWrappers(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotImplemented) })) defer svr.Close() @@ -275,7 +275,7 @@ func TestBuildSourceWithWrappers(t *testing.T) { } // Helper used by runExecuteSubprocess. -func TestHelperProcess(t *testing.T) { +func TestHelperProcess(_ *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } @@ -302,6 +302,7 @@ func runExecuteSubprocess(t *testing.T, args []string) (int, string, error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() + // TODO: investigate why -test.run=TestHelperProcess cmdArgs := append([]string{"-test.run=TestHelperProcess", "--"}, args...) cmd := exec.CommandContext(ctx, os.Args[0], cmdArgs...) cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1") diff --git a/controller/metrics_test.go b/controller/metrics_test.go index 9e27ae148..facd09c72 100644 --- a/controller/metrics_test.go +++ b/controller/metrics_test.go @@ -301,10 +301,6 @@ func TestGaugeMetricsWithMixedRecords(t *testing.T) { testutils.TestHelperVerifyMetricsGaugeVectorWithLabels(t, 43, registryRecords.Gauge, map[string]string{"record_type": "ptr"}) } -type mixedRecordsFixture struct { - ctrl *Controller -} - func newMixedRecordsFixture() *Controller { configuredEndpoints := testutils.GenerateTestEndpointsByType(map[string]int{ endpoint.RecordTypeA: 534, diff --git a/endpoint/crypto_test.go b/endpoint/crypto_test.go index 4feeb073a..ebb4a0219 100644 --- a/endpoint/crypto_test.go +++ b/endpoint/crypto_test.go @@ -87,6 +87,6 @@ func TestGenerateNonceError(t *testing.T) { type faultyReader struct{} -func (f *faultyReader) Read(p []byte) (int, error) { +func (f *faultyReader) Read(_ []byte) (int, error) { return 0, io.ErrUnexpectedEOF } diff --git a/internal/flags/binders_test.go b/internal/flags/binders_test.go index a299dabb2..9a0e6cbf7 100644 --- a/internal/flags/binders_test.go +++ b/internal/flags/binders_test.go @@ -29,7 +29,7 @@ import ( type badSetter struct{} -func (b *badSetter) Set(s string) error { return errors.New("bad default") } +func (b *badSetter) Set(_ string) error { return errors.New("bad default") } func TestKingpinBinderParsesAllTypes(t *testing.T) { app := kingpin.New("test", "") diff --git a/internal/testutils/endpoint_test.go b/internal/testutils/endpoint_test.go index ddc80cc4a..188075119 100644 --- a/internal/testutils/endpoint_test.go +++ b/internal/testutils/endpoint_test.go @@ -17,7 +17,6 @@ limitations under the License. package testutils import ( - "fmt" "net/netip" "reflect" "sort" @@ -71,17 +70,21 @@ func TestExampleSameEndpoints(t *testing.T) { }, } sort.Sort(byAllFields(eps)) - for _, ep := range eps { - fmt.Println(ep) + + expectedOrder := []string{ + "abc.com", + "abc.com", + "bbc.com", + "cbc.com", + "example.org", + "example.org", + "example.org", + } + + assert.Len(t, eps, len(expectedOrder)) + for i, ep := range eps { + assert.Equal(t, expectedOrder[i], ep.DNSName, "endpoint %d should be %s", i, expectedOrder[i]) } - // Output: - // abc.com 0 IN A test-set-1 1.2.3.4 [] - // abc.com 0 IN TXT something [] - // bbc.com 0 IN CNAME foo.com [] - // cbc.com 60 IN CNAME foo.com [] - // example.org 0 IN load-balancer.org [] - // example.org 0 IN load-balancer.org [{foo bar}] - // example.org 0 IN TXT load-balancer.org [] } func makeEndpoint(DNSName string) *endpoint.Endpoint { // nolint: gocritic // captLocal diff --git a/pkg/apis/externaldns/types_test.go b/pkg/apis/externaldns/types_test.go index 34bb4a7ae..fa3af6ec0 100644 --- a/pkg/apis/externaldns/types_test.go +++ b/pkg/apis/externaldns/types_test.go @@ -17,7 +17,6 @@ limitations under the License. package externaldns import ( - "os" "regexp" "testing" "time" @@ -587,19 +586,6 @@ func TestConfigStringMasksSecureFields(t *testing.T) { require.Contains(t, s, passwordMask) } -// helper functions - -func setEnv(t *testing.T, env map[string]string) map[string]string { - originalEnv := map[string]string{} - - for k, v := range env { - originalEnv[k] = os.Getenv(k) - require.NoError(t, os.Setenv(k, v)) - } - - return originalEnv -} - // Default path should use kingpin and parse flags correctly func TestParseFlagsDefaultKingpin(t *testing.T) { t.Setenv("EXTERNAL_DNS_CLI", "") diff --git a/pkg/client/config_test.go b/pkg/client/config_test.go index 786652a60..39fed2be4 100644 --- a/pkg/client/config_test.go +++ b/pkg/client/config_test.go @@ -31,7 +31,7 @@ import ( ) func TestGetRestConfig_WithKubeConfig(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + svr := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) defer svr.Close() mockKubeCfgDir := filepath.Join(t.TempDir(), ".kube") @@ -66,7 +66,7 @@ users: } func TestInstrumentedRESTConfig_AddsMetrics(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + svr := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) defer svr.Close() mockKubeCfgDir := filepath.Join(t.TempDir(), ".kube") @@ -104,7 +104,7 @@ users: } func TestGetRestConfig_RecommendedHomeFile(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + svr := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) defer svr.Close() mockKubeCfgDir := filepath.Join(t.TempDir(), ".kube") diff --git a/pkg/events/controller_test.go b/pkg/events/controller_test.go index ccb0efa91..e60f42e24 100644 --- a/pkg/events/controller_test.go +++ b/pkg/events/controller_test.go @@ -43,7 +43,7 @@ import ( ) func TestNewEventController_Success(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + svr := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) defer svr.Close() mockKubeCfgDir := filepath.Join(t.TempDir(), ".kube") @@ -104,7 +104,7 @@ func TestController_Run_EmitEvents(t *testing.T) { eventCreated := make(chan struct{}) kubeClient := fake.NewClientset() - kubeClient.PrependReactor("create", "events", func(action clienttesting.Action) (bool, runtime.Object, error) { + kubeClient.PrependReactor("create", "events", func(_ clienttesting.Action) (bool, runtime.Object, error) { eventCreated <- struct{}{} return true, nil, nil }) diff --git a/pkg/events/types_test.go b/pkg/events/types_test.go index 00e5df720..5060e351f 100644 --- a/pkg/events/types_test.go +++ b/pkg/events/types_test.go @@ -133,7 +133,7 @@ func TestEvent_NewEvents(t *testing.T) { }, } for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { + t.Run(tt.name, func(_ *testing.T) { tt.asserts(tt.event.event()) }) } @@ -212,7 +212,7 @@ func TestWithEmitEvents(t *testing.T) { } for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { + t.Run(tt.name, func(_ *testing.T) { cfg := &Config{} opt := WithEmitEvents(tt.input) opt(cfg) diff --git a/pkg/http/http_benchmark_test.go b/pkg/http/http_benchmark_test.go index aaf8991d6..9cf3f1386 100644 --- a/pkg/http/http_benchmark_test.go +++ b/pkg/http/http_benchmark_test.go @@ -55,7 +55,7 @@ func (api *apiUnderTest) doStuff() ([]byte, error) { } func BenchmarkRoundTripper(b *testing.B) { - client := newTestClient(func(req *http.Request) *http.Response { + client := newTestClient(func(_ *http.Request) *http.Response { return &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString(`OK`)), @@ -72,7 +72,7 @@ func BenchmarkRoundTripper(b *testing.B) { } func TestRoundTripper_Concurrent(t *testing.T) { - client := newTestClient(func(req *http.Request) *http.Response { + client := newTestClient(func(_ *http.Request) *http.Response { return &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString(`OK`)), diff --git a/pkg/http/http_test.go b/pkg/http/http_test.go index 3fc558bd4..295cf4040 100644 --- a/pkg/http/http_test.go +++ b/pkg/http/http_test.go @@ -29,7 +29,7 @@ import ( type dummyTransport struct{} -func (d *dummyTransport) RoundTrip(req *http.Request) (*http.Response, error) { +func (d *dummyTransport) RoundTrip(_ *http.Request) (*http.Response, error) { return nil, fmt.Errorf("dummy error") } @@ -73,7 +73,7 @@ func TestCancelRequest(t *testing.T) { request: &http.Request{}, }, } { - t.Run(tt.title, func(t *testing.T) { + t.Run(tt.title, func(_ *testing.T) { tt.customRoundTripper.CancelRequest(tt.request) }) } diff --git a/pkg/tlsutils/tlsconfig_test.go b/pkg/tlsutils/tlsconfig_test.go index 687603795..ed794b995 100644 --- a/pkg/tlsutils/tlsconfig_test.go +++ b/pkg/tlsutils/tlsconfig_test.go @@ -75,7 +75,7 @@ func TestCreateTLSConfig(t *testing.T) { "", "", "", - func(actual *tls.Config, err error) { + func(_ *tls.Config, err error) { assert.Contains(t, err.Error(), "either both cert and key or none must be provided") }, }, @@ -87,7 +87,7 @@ func TestCreateTLSConfig(t *testing.T) { "invalid-key", "", "", - func(actual *tls.Config, err error) { + func(_ *tls.Config, err error) { assert.Contains(t, err.Error(), "could not load TLS cert") }, }, @@ -115,7 +115,7 @@ func TestCreateTLSConfig(t *testing.T) { "", "", "", - func(actual *tls.Config, err error) { + func(_ *tls.Config, err error) { assert.Error(t, err) assert.Contains(t, err.Error(), "could not read root certs") }, @@ -128,7 +128,7 @@ func TestCreateTLSConfig(t *testing.T) { "", "", "server-name", - func(actual *tls.Config, err error) { + func(_ *tls.Config, err error) { assert.Error(t, err) assert.Contains(t, err.Error(), "error reading /path/does/not/exist") }, diff --git a/provider/akamai/akamai.go b/provider/akamai/akamai.go index 46202072f..65c9b6711 100644 --- a/provider/akamai/akamai.go +++ b/provider/akamai/akamai.go @@ -255,7 +255,7 @@ func (p AkamaiProvider) Records(context.Context) ([]*endpoint.Endpoint, error) { } // ApplyChanges applies a given set of changes in a given zone. -func (p AkamaiProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (p AkamaiProvider) ApplyChanges(_ context.Context, changes *plan.Changes) error { zoneNameIDMapper := provider.ZoneIDName{} zones, err := p.fetchZones() if err != nil { diff --git a/provider/akamai/akamai_test.go b/provider/akamai/akamai_test.go index 007922826..9fbfdd194 100644 --- a/provider/akamai/akamai_test.go +++ b/provider/akamai/akamai_test.go @@ -33,10 +33,8 @@ import ( ) type edgednsStubData struct { - objType string // zone, record, recordsets - output []any - updateRecords []any - createRecords []any + objType string // zone, record, recordsets + output []any } type edgednsStub struct { @@ -83,27 +81,7 @@ func (r *edgednsStub) setOutput(objtype string, output []any) { return } -func (r *edgednsStub) setUpdateRecords(objtype string, records []any) { - log.Debugf("Setting updaterecords to %v", records) - r.createStubDataEntry(objtype) - stubdata := r.stubData[objtype] - stubdata.updateRecords = records - r.stubData[objtype] = stubdata - - return -} - -func (r *edgednsStub) setCreateRecords(objtype string, records []any) { - log.Debugf("Setting createrecords to %v", records) - r.createStubDataEntry(objtype) - stubdata := r.stubData[objtype] - stubdata.createRecords = records - r.stubData[objtype] = stubdata - - return -} - -func (r *edgednsStub) ListZones(queryArgs dns.ZoneListQueryArgs) (*dns.ZoneListResponse, error) { +func (r *edgednsStub) ListZones(_ dns.ZoneListQueryArgs) (*dns.ZoneListResponse, error) { log.Debugf("Entering ListZones") // Ignore Metadata` resp := &dns.ZoneListResponse{} @@ -118,7 +96,7 @@ func (r *edgednsStub) ListZones(queryArgs dns.ZoneListQueryArgs) (*dns.ZoneListR return resp, nil } -func (r *edgednsStub) GetRecordsets(zone string, queryArgs dns.RecordsetQueryArgs) (*dns.RecordSetResponse, error) { +func (r *edgednsStub) GetRecordsets(_ string, _ dns.RecordsetQueryArgs) (*dns.RecordSetResponse, error) { log.Debugf("Entering GetRecordsets") // Ignore Metadata` resp := &dns.RecordSetResponse{} @@ -132,21 +110,21 @@ func (r *edgednsStub) GetRecordsets(zone string, queryArgs dns.RecordsetQueryArg return resp, nil } -func (r *edgednsStub) CreateRecordsets(recordsets *dns.Recordsets, zone string, reclock bool) error { +func (r *edgednsStub) CreateRecordsets(_ *dns.Recordsets, _ string, _ bool) error { return nil } -func (r *edgednsStub) GetRecord(zone string, name string, record_type string) (*dns.RecordBody, error) { +func (r *edgednsStub) GetRecord(_ string, _ string, _ string) (*dns.RecordBody, error) { resp := &dns.RecordBody{} return resp, nil } -func (r *edgednsStub) DeleteRecord(record *dns.RecordBody, zone string, recLock bool) error { +func (r *edgednsStub) DeleteRecord(_ *dns.RecordBody, _ string, _ bool) error { return nil } -func (r *edgednsStub) UpdateRecord(record *dns.RecordBody, zone string, recLock bool) error { +func (r *edgednsStub) UpdateRecord(_ *dns.RecordBody, _ string, _ bool) error { return nil } diff --git a/provider/alibabacloud/alibaba_cloud.go b/provider/alibabacloud/alibaba_cloud.go index b9361af0e..7560d4caa 100644 --- a/provider/alibabacloud/alibaba_cloud.go +++ b/provider/alibabacloud/alibaba_cloud.go @@ -285,7 +285,7 @@ func (p *AlibabaCloudProvider) refreshStsToken(sleepTime time.Duration) { // Records gets the current records. // // Returns the current records or an error if the operation failed. -func (p *AlibabaCloudProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p *AlibabaCloudProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { if p.privateZone { return p.privateZoneRecords() } else { diff --git a/provider/alibabacloud/alibaba_cloud_test.go b/provider/alibabacloud/alibaba_cloud_test.go index 9278e1514..42bf6ccbd 100644 --- a/provider/alibabacloud/alibaba_cloud_test.go +++ b/provider/alibabacloud/alibaba_cloud_test.go @@ -93,7 +93,7 @@ func (m *MockAlibabaCloudDNSAPI) UpdateDomainRecord(request *alidns.UpdateDomain return response, nil } -func (m *MockAlibabaCloudDNSAPI) DescribeDomains(request *alidns.DescribeDomainsRequest) (*alidns.DescribeDomainsResponse, error) { +func (m *MockAlibabaCloudDNSAPI) DescribeDomains(_ *alidns.DescribeDomainsRequest) (*alidns.DescribeDomainsResponse, error) { var result alidns.DomainsInDescribeDomains for _, record := range m.records { domain := alidns.Domain{} @@ -193,7 +193,7 @@ func (m *MockAlibabaCloudPrivateZoneAPI) UpdateZoneRecord(request *pvtz.UpdateZo return pvtz.CreateUpdateZoneRecordResponse(), nil } -func (m *MockAlibabaCloudPrivateZoneAPI) DescribeZoneRecords(request *pvtz.DescribeZoneRecordsRequest) (*pvtz.DescribeZoneRecordsResponse, error) { +func (m *MockAlibabaCloudPrivateZoneAPI) DescribeZoneRecords(_ *pvtz.DescribeZoneRecordsRequest) (*pvtz.DescribeZoneRecordsResponse, error) { response := pvtz.CreateDescribeZoneRecordsResponse() response.Records.Record = append(response.Records.Record, m.records...) return response, nil diff --git a/provider/aws/aws_test.go b/provider/aws/aws_test.go index b7bfabd2d..6719b8707 100644 --- a/provider/aws/aws_test.go +++ b/provider/aws/aws_test.go @@ -163,7 +163,7 @@ func specialCharactersEscape(s string) string { return result.String() } -func (r *Route53APIStub) ListTagsForResources(ctx context.Context, input *route53.ListTagsForResourcesInput, optFns ...func(options *route53.Options)) (*route53.ListTagsForResourcesOutput, error) { +func (r *Route53APIStub) ListTagsForResources(_ context.Context, input *route53.ListTagsForResourcesInput, _ ...func(options *route53.Options)) (*route53.ListTagsForResourcesOutput, error) { if input.ResourceType == route53types.TagResourceTypeHostedzone { var sets []route53types.ResourceTagSet for _, el := range input.ResourceIds { @@ -185,7 +185,7 @@ func (r *Route53APIStub) ListTagsForResources(ctx context.Context, input *route5 return &route53.ListTagsForResourcesOutput{}, nil } -func (r *Route53APIStub) ChangeResourceRecordSets(ctx context.Context, input *route53.ChangeResourceRecordSetsInput, optFns ...func(options *route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) { +func (r *Route53APIStub) ChangeResourceRecordSets(_ context.Context, input *route53.ChangeResourceRecordSetsInput, _ ...func(options *route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) { if r.m.isMocked("ChangeResourceRecordSets", input) { return r.m.ChangeResourceRecordSets(input) } @@ -244,7 +244,7 @@ func (r *Route53APIStub) ChangeResourceRecordSets(ctx context.Context, input *ro return output, nil // TODO: We should ideally return status etc, but we don't' use that yet. } -func (r *Route53APIStub) ListHostedZones(ctx context.Context, input *route53.ListHostedZonesInput, optFns ...func(options *route53.Options)) (*route53.ListHostedZonesOutput, error) { +func (r *Route53APIStub) ListHostedZones(_ context.Context, _ *route53.ListHostedZonesInput, _ ...func(options *route53.Options)) (*route53.ListHostedZonesOutput, error) { output := &route53.ListHostedZonesOutput{} for _, zone := range r.zones { output.HostedZones = append(output.HostedZones, *zone) @@ -252,7 +252,7 @@ func (r *Route53APIStub) ListHostedZones(ctx context.Context, input *route53.Lis return output, nil } -func (r *Route53APIStub) CreateHostedZone(ctx context.Context, input *route53.CreateHostedZoneInput, optFns ...func(options *route53.Options)) (*route53.CreateHostedZoneOutput, error) { +func (r *Route53APIStub) CreateHostedZone(_ context.Context, input *route53.CreateHostedZoneInput, _ ...func(options *route53.Options)) (*route53.CreateHostedZoneOutput, error) { name := *input.Name id := "/hostedzone/" + name if _, ok := r.zones[id]; ok { @@ -270,7 +270,7 @@ type dynamicMock struct { mock.Mock } -func (m *dynamicMock) ListResourceRecordSets(ctx context.Context, input *route53.ListResourceRecordSetsInput, optFns ...func(options *route53.Options)) (*route53.ListResourceRecordSetsOutput, error) { +func (m *dynamicMock) ListResourceRecordSets(_ context.Context, input *route53.ListResourceRecordSetsInput, _ ...func(options *route53.Options)) (*route53.ListResourceRecordSetsOutput, error) { args := m.Called(input) if args.Get(0) != nil { return args.Get(0).(*route53.ListResourceRecordSetsOutput), args.Error(1) @@ -742,7 +742,7 @@ func TestAWSApplyChanges(t *testing.T) { setup func(p *AWSProvider) context.Context listRRSets int }{ - {"no cache", func(p *AWSProvider) context.Context { return context.Background() }, 0}, + {"no cache", func(_ *AWSProvider) context.Context { return context.Background() }, 0}, {"cached", func(p *AWSProvider) context.Context { ctx := context.Background() records, err := p.Records(ctx) diff --git a/provider/aws/aws_utils_test.go b/provider/aws/aws_utils_test.go index 30c4273bd..c9ddd5380 100644 --- a/provider/aws/aws_utils_test.go +++ b/provider/aws/aws_utils_test.go @@ -101,22 +101,22 @@ func NewRoute53APIFixtureStub(zones *HostedZones) *Route53APIFixtureStub { } } -func (r Route53APIFixtureStub) ListResourceRecordSets(ctx context.Context, input *route53.ListResourceRecordSetsInput, optFns ...func(options *route53.Options)) (*route53.ListResourceRecordSetsOutput, error) { +func (r Route53APIFixtureStub) ListResourceRecordSets(_ context.Context, _ *route53.ListResourceRecordSetsInput, _ ...func(options *route53.Options)) (*route53.ListResourceRecordSetsOutput, error) { // TODO implement me panic("implement me") } -func (r Route53APIFixtureStub) ChangeResourceRecordSets(ctx context.Context, input *route53.ChangeResourceRecordSetsInput, optFns ...func(options *route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) { +func (r Route53APIFixtureStub) ChangeResourceRecordSets(_ context.Context, _ *route53.ChangeResourceRecordSetsInput, _ ...func(options *route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) { // TODO implement me panic("implement me") } -func (r Route53APIFixtureStub) CreateHostedZone(ctx context.Context, input *route53.CreateHostedZoneInput, optFns ...func(*route53.Options)) (*route53.CreateHostedZoneOutput, error) { +func (r Route53APIFixtureStub) CreateHostedZone(_ context.Context, _ *route53.CreateHostedZoneInput, _ ...func(*route53.Options)) (*route53.CreateHostedZoneOutput, error) { // TODO implement me panic("implement me") } -func (r Route53APIFixtureStub) ListHostedZones(ctx context.Context, input *route53.ListHostedZonesInput, optFns ...func(options *route53.Options)) (*route53.ListHostedZonesOutput, error) { +func (r Route53APIFixtureStub) ListHostedZones(_ context.Context, _ *route53.ListHostedZonesInput, _ ...func(options *route53.Options)) (*route53.ListHostedZonesOutput, error) { r.calls["listhostedzones"]++ output := &route53.ListHostedZonesOutput{} for _, zone := range r.zones { @@ -125,7 +125,7 @@ func (r Route53APIFixtureStub) ListHostedZones(ctx context.Context, input *route return output, nil } -func (r Route53APIFixtureStub) ListTagsForResources(ctx context.Context, input *route53.ListTagsForResourcesInput, optFns ...func(options *route53.Options)) (*route53.ListTagsForResourcesOutput, error) { +func (r Route53APIFixtureStub) ListTagsForResources(_ context.Context, input *route53.ListTagsForResourcesInput, _ ...func(options *route53.Options)) (*route53.ListTagsForResourcesOutput, error) { r.calls["listtagsforresource"]++ var sets []route53types.ResourceTagSet diff --git a/provider/aws/instrumented_config_test.go b/provider/aws/instrumented_config_test.go index 397b599d9..667d0a902 100644 --- a/provider/aws/instrumented_config_test.go +++ b/provider/aws/instrumented_config_test.go @@ -55,7 +55,7 @@ type MockInitializeHandler struct { CapturedContext context.Context } -func (mock *MockInitializeHandler) HandleInitialize(ctx context.Context, in middleware.InitializeInput) (middleware.InitializeOutput, middleware.Metadata, error) { +func (mock *MockInitializeHandler) HandleInitialize(ctx context.Context, _ middleware.InitializeInput) (middleware.InitializeOutput, middleware.Metadata, error) { mock.CapturedContext = ctx return middleware.InitializeOutput{}, middleware.Metadata{}, nil @@ -75,7 +75,7 @@ func Test_InitializedTimedOperationMiddleware(t *testing.T) { type MockDeserializeHandler struct { } -func (mock *MockDeserializeHandler) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput) (middleware.DeserializeOutput, middleware.Metadata, error) { +func (mock *MockDeserializeHandler) HandleDeserialize(_ context.Context, _ middleware.DeserializeInput) (middleware.DeserializeOutput, middleware.Metadata, error) { return middleware.DeserializeOutput{}, middleware.Metadata{}, nil } diff --git a/provider/awssd/fixtures_test.go b/provider/awssd/fixtures_test.go index 9b9408a43..d78379e08 100644 --- a/provider/awssd/fixtures_test.go +++ b/provider/awssd/fixtures_test.go @@ -160,7 +160,7 @@ func (s *AWSSDClientStub) ListServices(_ context.Context, input *sd.ListServices }, nil } -func (s *AWSSDClientStub) RegisterInstance(ctx context.Context, input *sd.RegisterInstanceInput, _ ...func(options *sd.Options)) (*sd.RegisterInstanceOutput, error) { +func (s *AWSSDClientStub) RegisterInstance(_ context.Context, input *sd.RegisterInstanceInput, _ ...func(options *sd.Options)) (*sd.RegisterInstanceOutput, error) { srvInstances, ok := s.instances[*input.ServiceId] if !ok { srvInstances = make(map[string]*sdtypes.Instance) diff --git a/provider/azure/azure_privatedns_test.go b/provider/azure/azure_privatedns_test.go index 91011b6e1..20bfd11d8 100644 --- a/provider/azure/azure_privatedns_test.go +++ b/provider/azure/azure_privatedns_test.go @@ -42,7 +42,7 @@ type mockPrivateZonesClient struct { func newMockPrivateZonesClient(zones []*privatedns.PrivateZone) mockPrivateZonesClient { pagingHandler := azcoreruntime.PagingHandler[privatedns.PrivateZonesClientListByResourceGroupResponse]{ - More: func(resp privatedns.PrivateZonesClientListByResourceGroupResponse) bool { + More: func(_ privatedns.PrivateZonesClientListByResourceGroupResponse) bool { return false }, Fetcher: func(context.Context, *privatedns.PrivateZonesClientListByResourceGroupResponse) (privatedns.PrivateZonesClientListByResourceGroupResponse, error) { @@ -58,7 +58,7 @@ func newMockPrivateZonesClient(zones []*privatedns.PrivateZone) mockPrivateZones } } -func (client *mockPrivateZonesClient) NewListByResourceGroupPager(resourceGroupName string, options *privatedns.PrivateZonesClientListByResourceGroupOptions) *azcoreruntime.Pager[privatedns.PrivateZonesClientListByResourceGroupResponse] { +func (client *mockPrivateZonesClient) NewListByResourceGroupPager(_ string, _ *privatedns.PrivateZonesClientListByResourceGroupOptions) *azcoreruntime.Pager[privatedns.PrivateZonesClientListByResourceGroupResponse] { return azcoreruntime.NewPager(client.pagingHandler) } @@ -72,7 +72,7 @@ type mockPrivateRecordSetsClient struct { func newMockPrivateRecordSectsClient(recordSets []*privatedns.RecordSet) mockPrivateRecordSetsClient { pagingHandler := azcoreruntime.PagingHandler[privatedns.RecordSetsClientListResponse]{ - More: func(resp privatedns.RecordSetsClientListResponse) bool { + More: func(_ privatedns.RecordSetsClientListResponse) bool { return false }, Fetcher: func(context.Context, *privatedns.RecordSetsClientListResponse) (privatedns.RecordSetsClientListResponse, error) { @@ -88,11 +88,11 @@ func newMockPrivateRecordSectsClient(recordSets []*privatedns.RecordSet) mockPri } } -func (client *mockPrivateRecordSetsClient) NewListPager(resourceGroupName string, privateZoneName string, options *privatedns.RecordSetsClientListOptions) *azcoreruntime.Pager[privatedns.RecordSetsClientListResponse] { +func (client *mockPrivateRecordSetsClient) NewListPager(_ string, _ string, _ *privatedns.RecordSetsClientListOptions) *azcoreruntime.Pager[privatedns.RecordSetsClientListResponse] { return azcoreruntime.NewPager(client.pagingHandler) } -func (client *mockPrivateRecordSetsClient) Delete(ctx context.Context, resourceGroupName string, privateZoneName string, recordType privatedns.RecordType, relativeRecordSetName string, options *privatedns.RecordSetsClientDeleteOptions) (privatedns.RecordSetsClientDeleteResponse, error) { +func (client *mockPrivateRecordSetsClient) Delete(_ context.Context, _ string, privateZoneName string, recordType privatedns.RecordType, relativeRecordSetName string, _ *privatedns.RecordSetsClientDeleteOptions) (privatedns.RecordSetsClientDeleteResponse, error) { client.deletedEndpoints = append( client.deletedEndpoints, endpoint.NewEndpoint( @@ -104,7 +104,7 @@ func (client *mockPrivateRecordSetsClient) Delete(ctx context.Context, resourceG return privatedns.RecordSetsClientDeleteResponse{}, nil } -func (client *mockPrivateRecordSetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, privateZoneName string, recordType privatedns.RecordType, relativeRecordSetName string, parameters privatedns.RecordSet, options *privatedns.RecordSetsClientCreateOrUpdateOptions) (privatedns.RecordSetsClientCreateOrUpdateResponse, error) { +func (client *mockPrivateRecordSetsClient) CreateOrUpdate(_ context.Context, _ string, privateZoneName string, recordType privatedns.RecordType, relativeRecordSetName string, parameters privatedns.RecordSet, _ *privatedns.RecordSetsClientCreateOrUpdateOptions) (privatedns.RecordSetsClientCreateOrUpdateResponse, error) { var ttl endpoint.TTL if parameters.Properties.TTL != nil { ttl = endpoint.TTL(*parameters.Properties.TTL) @@ -186,7 +186,7 @@ func privateTxtRecordSetPropertiesGetter(values []string, ttl int64) *privatedns } } -func privateOthersRecordSetPropertiesGetter(values []string, ttl int64) *privatedns.RecordSetProperties { +func privateOthersRecordSetPropertiesGetter(_ []string, ttl int64) *privatedns.RecordSetProperties { return &privatedns.RecordSetProperties{ TTL: to.Ptr(ttl), } diff --git a/provider/azure/azure_test.go b/provider/azure/azure_test.go index 16da5e3ff..207930109 100644 --- a/provider/azure/azure_test.go +++ b/provider/azure/azure_test.go @@ -40,7 +40,7 @@ type mockZonesClient struct { func newMockZonesClient(zones []*dns.Zone) mockZonesClient { pagingHandler := azcoreruntime.PagingHandler[dns.ZonesClientListByResourceGroupResponse]{ - More: func(resp dns.ZonesClientListByResourceGroupResponse) bool { + More: func(_ dns.ZonesClientListByResourceGroupResponse) bool { return false }, Fetcher: func(context.Context, *dns.ZonesClientListByResourceGroupResponse) (dns.ZonesClientListByResourceGroupResponse, error) { @@ -56,7 +56,7 @@ func newMockZonesClient(zones []*dns.Zone) mockZonesClient { } } -func (client *mockZonesClient) NewListByResourceGroupPager(resourceGroupName string, options *dns.ZonesClientListByResourceGroupOptions) *azcoreruntime.Pager[dns.ZonesClientListByResourceGroupResponse] { +func (client *mockZonesClient) NewListByResourceGroupPager(_ string, _ *dns.ZonesClientListByResourceGroupOptions) *azcoreruntime.Pager[dns.ZonesClientListByResourceGroupResponse] { return azcoreruntime.NewPager(client.pagingHandler) } @@ -70,7 +70,7 @@ type mockRecordSetsClient struct { func newMockRecordSetsClient(recordSets []*dns.RecordSet) mockRecordSetsClient { pagingHandler := azcoreruntime.PagingHandler[dns.RecordSetsClientListAllByDNSZoneResponse]{ - More: func(resp dns.RecordSetsClientListAllByDNSZoneResponse) bool { + More: func(_ dns.RecordSetsClientListAllByDNSZoneResponse) bool { return false }, Fetcher: func(context.Context, *dns.RecordSetsClientListAllByDNSZoneResponse) (dns.RecordSetsClientListAllByDNSZoneResponse, error) { @@ -86,11 +86,11 @@ func newMockRecordSetsClient(recordSets []*dns.RecordSet) mockRecordSetsClient { } } -func (client *mockRecordSetsClient) NewListAllByDNSZonePager(resourceGroupName string, zoneName string, options *dns.RecordSetsClientListAllByDNSZoneOptions) *azcoreruntime.Pager[dns.RecordSetsClientListAllByDNSZoneResponse] { +func (client *mockRecordSetsClient) NewListAllByDNSZonePager(_ string, _ string, _ *dns.RecordSetsClientListAllByDNSZoneOptions) *azcoreruntime.Pager[dns.RecordSetsClientListAllByDNSZoneResponse] { return azcoreruntime.NewPager(client.pagingHandler) } -func (client *mockRecordSetsClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType dns.RecordType, options *dns.RecordSetsClientDeleteOptions) (dns.RecordSetsClientDeleteResponse, error) { +func (client *mockRecordSetsClient) Delete(_ context.Context, _ string, zoneName string, relativeRecordSetName string, recordType dns.RecordType, _ *dns.RecordSetsClientDeleteOptions) (dns.RecordSetsClientDeleteResponse, error) { client.deletedEndpoints = append( client.deletedEndpoints, endpoint.NewEndpoint( @@ -102,7 +102,7 @@ func (client *mockRecordSetsClient) Delete(ctx context.Context, resourceGroupNam return dns.RecordSetsClientDeleteResponse{}, nil } -func (client *mockRecordSetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType dns.RecordType, parameters dns.RecordSet, options *dns.RecordSetsClientCreateOrUpdateOptions) (dns.RecordSetsClientCreateOrUpdateResponse, error) { +func (client *mockRecordSetsClient) CreateOrUpdate(_ context.Context, _ string, zoneName string, relativeRecordSetName string, recordType dns.RecordType, parameters dns.RecordSet, _ *dns.RecordSetsClientCreateOrUpdateOptions) (dns.RecordSetsClientCreateOrUpdateResponse, error) { var ttl endpoint.TTL if parameters.Properties.TTL != nil { ttl = endpoint.TTL(*parameters.Properties.TTL) @@ -197,7 +197,7 @@ func txtRecordSetPropertiesGetter(values []string, ttl int64) *dns.RecordSetProp } } -func othersRecordSetPropertiesGetter(values []string, ttl int64) *dns.RecordSetProperties { +func othersRecordSetPropertiesGetter(_ []string, ttl int64) *dns.RecordSetProperties { return &dns.RecordSetProperties{ TTL: to.Ptr(ttl), } diff --git a/provider/azure/config_test.go b/provider/azure/config_test.go index 89542e961..a501206e3 100644 --- a/provider/azure/config_test.go +++ b/provider/azure/config_test.go @@ -78,29 +78,17 @@ func (f transportFunc) Do(req *http.Request) (*http.Response, error) { func TestCustomHeaderPolicyWithRetries(t *testing.T) { // Set up test environment - defaultRetries := 3 - flagValue := "-6" - isSet := true - retries, err := parseMaxRetries(flagValue, defaultRetries) + flagValue := "-6" + + retries, err := parseMaxRetries(flagValue) if err != nil { t.Fatalf("Failed to parse retries: %v", err) } maxRetries := int32(retries) - if !isSet || (isSet && flagValue == "0") { - // Use default if flag not provided OR if flag is "0" - maxRetries = int32(defaultRetries) - t.Logf("Using default value: %d (flag provided: %v, value: %q)", - defaultRetries, isSet, flagValue) - } else { - // Flag was provided with non-zero value - retries, err := parseMaxRetries(flagValue, defaultRetries) - if err != nil { - t.Fatalf("Failed to parse retries: %v", err) - } - maxRetries = int32(retries) - t.Logf("Using provided flag value: %d", retries) - } + // Flag was provided with non-zero value + maxRetries = int32(retries) + t.Logf("Using provided flag value: %d", retries) var attempt int32 var firstRequestID string @@ -293,7 +281,7 @@ func TestMaxRetriesCount(t *testing.T) { return } - retries, err := parseMaxRetries(tt.input, defaultRetries) + retries, err := parseMaxRetries(tt.input) // Check error condition if tt.shouldError { @@ -317,7 +305,7 @@ func TestMaxRetriesCount(t *testing.T) { } // Helper function to parse max retries value -func parseMaxRetries(value string, defaultValue int) (int, error) { +func parseMaxRetries(value string) (int, error) { // Trim whitespace value = strings.TrimSpace(value) diff --git a/provider/cached_provider_test.go b/provider/cached_provider_test.go index 4e358066f..9c32b8dc8 100644 --- a/provider/cached_provider_test.go +++ b/provider/cached_provider_test.go @@ -56,21 +56,21 @@ func (p *testProviderFunc) GetDomainFilter() endpoint.DomainFilterInterface { } func recordsNotCalled(t *testing.T) func(ctx context.Context) ([]*endpoint.Endpoint, error) { - return func(ctx context.Context) ([]*endpoint.Endpoint, error) { + return func(_ context.Context) ([]*endpoint.Endpoint, error) { t.Errorf("unexpected call to Records") return nil, nil } } -func applyChangesNotCalled(t *testing.T) func(ctx context.Context, changes *plan.Changes) error { - return func(ctx context.Context, changes *plan.Changes) error { +func applyChangesNotCalled(t *testing.T) func(_ context.Context, _ *plan.Changes) error { + return func(_ context.Context, _ *plan.Changes) error { t.Errorf("unexpected call to ApplyChanges") return nil } } func propertyValuesEqualNotCalled(t *testing.T) func(name string, previous string, current string) bool { - return func(name string, previous string, current string) bool { + return func(_ string, _ string, _ string) bool { t.Errorf("unexpected call to PropertyValuesEqual") return false } @@ -94,7 +94,7 @@ func newTestProviderFunc(t *testing.T) *testProviderFunc { func TestCachedProviderCallsProviderOnFirstCall(t *testing.T) { testProvider := newTestProviderFunc(t) - testProvider.records = func(ctx context.Context) ([]*endpoint.Endpoint, error) { + testProvider.records = func(_ context.Context) ([]*endpoint.Endpoint, error) { return []*endpoint.Endpoint{{DNSName: "domain.fqdn"}}, nil } provider := CachedProvider{ @@ -110,7 +110,7 @@ func TestCachedProviderCallsProviderOnFirstCall(t *testing.T) { func TestCachedProviderUsesCacheWhileValid(t *testing.T) { testProvider := newTestProviderFunc(t) - testProvider.records = func(ctx context.Context) ([]*endpoint.Endpoint, error) { + testProvider.records = func(_ context.Context) ([]*endpoint.Endpoint, error) { return []*endpoint.Endpoint{{DNSName: "domain.fqdn"}}, nil } provider := CachedProvider{ @@ -131,7 +131,7 @@ func TestCachedProviderUsesCacheWhileValid(t *testing.T) { }) t.Run("When the caching time frame is exceeded", func(t *testing.T) { - testProvider.records = func(ctx context.Context) ([]*endpoint.Endpoint, error) { + testProvider.records = func(_ context.Context) ([]*endpoint.Endpoint, error) { return []*endpoint.Endpoint{{DNSName: "new.domain.fqdn"}}, nil } provider.lastRead = time.Now().Add(-20 * time.Minute) @@ -146,7 +146,7 @@ func TestCachedProviderUsesCacheWhileValid(t *testing.T) { func TestCachedProviderForcesCacheRefreshOnUpdate(t *testing.T) { testProvider := newTestProviderFunc(t) - testProvider.records = func(ctx context.Context) ([]*endpoint.Endpoint, error) { + testProvider.records = func(_ context.Context) ([]*endpoint.Endpoint, error) { return []*endpoint.Endpoint{{DNSName: "domain.fqdn"}}, nil } provider := CachedProvider{ @@ -158,14 +158,14 @@ func TestCachedProviderForcesCacheRefreshOnUpdate(t *testing.T) { t.Run("When empty changes are applied", func(t *testing.T) { testProvider.records = recordsNotCalled(t) - testProvider.applyChanges = func(ctx context.Context, changes *plan.Changes) error { + testProvider.applyChanges = func(_ context.Context, _ *plan.Changes) error { return nil } err := provider.ApplyChanges(context.Background(), &plan.Changes{}) assert.NoError(t, err) t.Run("Next call to Records is cached", func(t *testing.T) { testProvider.applyChanges = applyChangesNotCalled(t) - testProvider.records = func(ctx context.Context) ([]*endpoint.Endpoint, error) { + testProvider.records = func(_ context.Context) ([]*endpoint.Endpoint, error) { return []*endpoint.Endpoint{{DNSName: "new.domain.fqdn"}}, nil } endpoints, err := provider.Records(context.Background()) @@ -180,7 +180,7 @@ func TestCachedProviderForcesCacheRefreshOnUpdate(t *testing.T) { t.Run("When changes are applied", func(t *testing.T) { testProvider.records = recordsNotCalled(t) - testProvider.applyChanges = func(ctx context.Context, changes *plan.Changes) error { + testProvider.applyChanges = func(_ context.Context, _ *plan.Changes) error { return nil } err := provider.ApplyChanges(context.Background(), &plan.Changes{ @@ -191,7 +191,7 @@ func TestCachedProviderForcesCacheRefreshOnUpdate(t *testing.T) { assert.NoError(t, err) t.Run("Next call to Records is not cached", func(t *testing.T) { testProvider.applyChanges = applyChangesNotCalled(t) - testProvider.records = func(ctx context.Context) ([]*endpoint.Endpoint, error) { + testProvider.records = func(_ context.Context) ([]*endpoint.Endpoint, error) { return []*endpoint.Endpoint{{DNSName: "new.domain.fqdn"}}, nil } endpoints, err := provider.Records(context.Background()) diff --git a/provider/civo/civo.go b/provider/civo/civo.go index 8ea04c250..baef9fef9 100644 --- a/provider/civo/civo.go +++ b/provider/civo/civo.go @@ -101,8 +101,8 @@ func NewCivoProvider(domainFilter *endpoint.DomainFilter, dryRun bool) (*CivoPro } // Zones returns the list of hosted zones. -func (p *CivoProvider) Zones(ctx context.Context) ([]civogo.DNSDomain, error) { - zones, err := p.fetchZones(ctx) +func (p *CivoProvider) Zones(_ context.Context) ([]civogo.DNSDomain, error) { + zones, err := p.fetchZones() if err != nil { return nil, err } @@ -120,7 +120,7 @@ func (p *CivoProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error var endpoints []*endpoint.Endpoint for _, zone := range zones { - records, err := p.fetchRecords(ctx, zone.ID) + records, err := p.fetchRecords(zone.ID) if err != nil { return nil, err } @@ -144,7 +144,7 @@ func (p *CivoProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error return endpoints, nil } -func (p *CivoProvider) fetchRecords(ctx context.Context, domainID string) ([]civogo.DNSRecord, error) { +func (p *CivoProvider) fetchRecords(domainID string) ([]civogo.DNSRecord, error) { records, err := p.Client.ListDNSRecords(domainID) if err != nil { return nil, err @@ -153,7 +153,7 @@ func (p *CivoProvider) fetchRecords(ctx context.Context, domainID string) ([]civ return records, nil } -func (p *CivoProvider) fetchZones(ctx context.Context) ([]civogo.DNSDomain, error) { +func (p *CivoProvider) fetchZones() ([]civogo.DNSDomain, error) { var zones []civogo.DNSDomain allZones, err := p.Client.ListDNSDomains() @@ -173,7 +173,7 @@ func (p *CivoProvider) fetchZones(ctx context.Context) ([]civogo.DNSDomain, erro } // submitChanges takes a zone and a collection of Changes and sends them as a single transaction. -func (p *CivoProvider) submitChanges(ctx context.Context, changes CivoChanges) error { +func (p *CivoProvider) submitChanges(changes CivoChanges) error { if changes.Empty() { log.Info("All records are already up to date") return nil @@ -440,11 +440,11 @@ func processDeleteActions(zonesByID map[string]civogo.DNSDomain, recordsByZoneID } // ApplyChanges applies a given set of changes in a given zone. -func (p *CivoProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (p *CivoProvider) ApplyChanges(_ context.Context, changes *plan.Changes) error { var civoChange CivoChanges recordsByZoneID := make(map[string][]civogo.DNSRecord) - zones, err := p.fetchZones(ctx) + zones, err := p.fetchZones() if err != nil { return err @@ -461,7 +461,7 @@ func (p *CivoProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) // Fetch records for each zone for _, zone := range zones { - records, err := p.fetchRecords(ctx, zone.ID) + records, err := p.fetchRecords(zone.ID) if err != nil { return err @@ -492,7 +492,7 @@ func (p *CivoProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) return err } - return p.submitChanges(ctx, civoChange) + return p.submitChanges(civoChange) } func endpointsByZone(zoneNameIDMapper provider.ZoneIDName, endpoints []*endpoint.Endpoint) map[string][]*endpoint.Endpoint { diff --git a/provider/civo/civo_test.go b/provider/civo/civo_test.go index 24618d2ec..7e2a2fbd6 100644 --- a/provider/civo/civo_test.go +++ b/provider/civo/civo_test.go @@ -18,6 +18,7 @@ package civo import ( "context" "fmt" + "io" "os" "reflect" "strings" @@ -25,6 +26,7 @@ import ( "github.com/civo/civogo" "github.com/google/go-cmp/cmp" + log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -187,6 +189,7 @@ func TestCivoProviderWithoutRecords(t *testing.T) { } func TestCivoProcessCreateActionsLogs(t *testing.T) { + log.SetOutput(io.Discard) t.Run("Logs Skipping Zone, no creates found", func(t *testing.T) { zonesByID := map[string]civogo.DNSDomain{ "example.com": { @@ -355,6 +358,7 @@ func TestCivoProcessCreateActionsWithError(t *testing.T) { } func TestCivoProcessUpdateActionsWithError(t *testing.T) { + log.SetOutput(io.Discard) zoneByID := map[string]civogo.DNSDomain{ "example.com": { ID: "1", @@ -615,6 +619,7 @@ func TestCivoProcessDeleteAction(t *testing.T) { } func TestCivoApplyChanges(t *testing.T) { + log.SetOutput(io.Discard) client, server, _ := civogo.NewAdvancedClientForTesting([]civogo.ConfigAdvanceClientForTesting{ { Method: "GET", @@ -650,6 +655,7 @@ func TestCivoApplyChanges(t *testing.T) { } func TestCivoApplyChangesError(t *testing.T) { + log.SetOutput(io.Discard) client, server, _ := civogo.NewAdvancedClientForTesting([]civogo.ConfigAdvanceClientForTesting{ { Method: "GET", @@ -723,7 +729,7 @@ func TestCivoProviderFetchZones(t *testing.T) { if err != nil { t.Errorf("should not fail, %s", err) } - zones, err := provider.fetchZones(context.Background()) + zones, err := provider.fetchZones() if err != nil { t.Fatal(err) } @@ -746,7 +752,7 @@ func TestCivoProviderFetchZonesWithFilter(t *testing.T) { {ID: "12345", Name: "example.com", AccountID: "1"}, } - actual, err := provider.fetchZones(context.Background()) + actual, err := provider.fetchZones() if err != nil { t.Fatal(err) } @@ -768,13 +774,14 @@ func TestCivoProviderFetchRecords(t *testing.T) { expected, err := client.ListDNSRecords("12345") assert.NoError(t, err) - actual, err := provider.fetchRecords(context.Background(), "12345") + actual, err := provider.fetchRecords("12345") assert.NoError(t, err) assert.ElementsMatch(t, expected, actual) } func TestCivoProviderFetchRecordsWithError(t *testing.T) { + log.SetOutput(io.Discard) client, server, _ := civogo.NewClientForTesting(map[string]string{ "/v2/dns/12345/records": `[ {"id": "1", "domain_id":"12345", "account_id": "1", "name": "www", "type": "A", "value": "10.0.0.0", "ttl": 600}, @@ -786,7 +793,7 @@ func TestCivoProviderFetchRecordsWithError(t *testing.T) { Client: *client, } - _, err := provider.fetchRecords(context.Background(), "235698") + _, err := provider.fetchRecords("235698") assert.Error(t, err) } @@ -860,6 +867,7 @@ func TestCivoProviderGetRecordID(t *testing.T) { } func TestCivo_submitChangesCreate(t *testing.T) { + log.SetOutput(io.Discard) client, server, _ := civogo.NewAdvancedClientForTesting([]civogo.ConfigAdvanceClientForTesting{ { Method: "POST", @@ -978,7 +986,7 @@ func TestCivo_submitChangesCreate(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - err := provider.submitChanges(context.Background(), *c.changes) + err := provider.submitChanges(*c.changes) assert.NoError(t, err) }) } @@ -1013,7 +1021,7 @@ func TestCivo_submitChangesDelete(t *testing.T) { }, } - err := provider.submitChanges(context.Background(), changes) + err := provider.submitChanges(changes) assert.NoError(t, err) } diff --git a/provider/cloudflare/cloudflare_custom_hostnames_test.go b/provider/cloudflare/cloudflare_custom_hostnames_test.go index 2a6b66b25..e16ee94e1 100644 --- a/provider/cloudflare/cloudflare_custom_hostnames_test.go +++ b/provider/cloudflare/cloudflare_custom_hostnames_test.go @@ -62,7 +62,7 @@ func (m *mockCloudFlareClient) CustomHostnames(ctx context.Context, zoneID strin } } -func (m *mockCloudFlareClient) CreateCustomHostname(ctx context.Context, zoneID string, ch customHostname) error { +func (m *mockCloudFlareClient) CreateCustomHostname(_ context.Context, zoneID string, ch customHostname) error { if ch.hostname == "" || ch.customOriginServer == "" || ch.hostname == "newerror-create.foo.fancybar.com" { return fmt.Errorf("Invalid custom hostname or origin hostname") } @@ -75,7 +75,7 @@ func (m *mockCloudFlareClient) CreateCustomHostname(ctx context.Context, zoneID return nil } -func (m *mockCloudFlareClient) DeleteCustomHostname(ctx context.Context, customHostnameID string, params custom_hostnames.CustomHostnameDeleteParams) error { +func (m *mockCloudFlareClient) DeleteCustomHostname(_ context.Context, customHostnameID string, params custom_hostnames.CustomHostnameDeleteParams) error { zoneID := params.ZoneID.String() idx := 0 if idx = getCustomHostnameIdxByID(m.customHostnames[zoneID], customHostnameID); idx < 0 { @@ -697,7 +697,7 @@ func TestSubmitCustomHostnameChanges(t *testing.T) { ) }) - t.Run("CustomHostnames_Delete", func(t *testing.T) { + t.Run("CustomHostnames_Delete", func(_ *testing.T) { client := NewMockCloudFlareClient() client.customHostnames = map[string][]customHostname{ "zone1": { diff --git a/provider/cloudflare/cloudflare_regional.go b/provider/cloudflare/cloudflare_regional.go index 08372993e..7ff4b310d 100644 --- a/provider/cloudflare/cloudflare_regional.go +++ b/provider/cloudflare/cloudflare_regional.go @@ -99,7 +99,7 @@ func updateDataLocalizationRegionalHostnameParams(zoneID string, rhc regionalHos } // deleteDataLocalizationRegionalHostnameParams is a function that returns the appropriate RegionalHostname Param based on the cloudFlareChange passed in -func deleteDataLocalizationRegionalHostnameParams(zoneID string, rhc regionalHostnameChange) addressing.RegionalHostnameDeleteParams { +func deleteDataLocalizationRegionalHostnameParams(zoneID string) addressing.RegionalHostnameDeleteParams { return addressing.RegionalHostnameDeleteParams{ ZoneID: cloudflare.F(zoneID), } @@ -147,7 +147,7 @@ func (p *CloudFlareProvider) submitRegionalHostnameChange(ctx context.Context, z } case cloudFlareDelete: changeLog.Debug("Deleting regional hostname") - params := deleteDataLocalizationRegionalHostnameParams(zoneID, rhChange) + params := deleteDataLocalizationRegionalHostnameParams(zoneID) if err := p.Client.DeleteDataLocalizationRegionalHostname(ctx, rhChange.hostname, params); err != nil { changeLog.Errorf("failed to delete regional hostname: %v", err) return false diff --git a/provider/cloudflare/cloudflare_regional_test.go b/provider/cloudflare/cloudflare_regional_test.go index b114adafc..edd17cca7 100644 --- a/provider/cloudflare/cloudflare_regional_test.go +++ b/provider/cloudflare/cloudflare_regional_test.go @@ -35,7 +35,7 @@ import ( "sigs.k8s.io/external-dns/source/annotations" ) -func (m *mockCloudFlareClient) ListDataLocalizationRegionalHostnames(ctx context.Context, params addressing.RegionalHostnameListParams) autoPager[addressing.RegionalHostnameListResponse] { +func (m *mockCloudFlareClient) ListDataLocalizationRegionalHostnames(_ context.Context, params addressing.RegionalHostnameListParams) autoPager[addressing.RegionalHostnameListResponse] { zoneID := params.ZoneID.Value if strings.Contains(zoneID, "rherror") { return &mockAutoPager[addressing.RegionalHostnameListResponse]{err: fmt.Errorf("failed to list regional hostnames")} @@ -52,7 +52,7 @@ func (m *mockCloudFlareClient) ListDataLocalizationRegionalHostnames(ctx context } } -func (m *mockCloudFlareClient) CreateDataLocalizationRegionalHostname(ctx context.Context, params addressing.RegionalHostnameNewParams) error { +func (m *mockCloudFlareClient) CreateDataLocalizationRegionalHostname(_ context.Context, params addressing.RegionalHostnameNewParams) error { if strings.Contains(params.Hostname.Value, "rherror") { return fmt.Errorf("failed to create regional hostname") } @@ -69,7 +69,7 @@ func (m *mockCloudFlareClient) CreateDataLocalizationRegionalHostname(ctx contex return nil } -func (m *mockCloudFlareClient) UpdateDataLocalizationRegionalHostname(ctx context.Context, hostname string, params addressing.RegionalHostnameEditParams) error { +func (m *mockCloudFlareClient) UpdateDataLocalizationRegionalHostname(_ context.Context, hostname string, params addressing.RegionalHostnameEditParams) error { if strings.Contains(hostname, "rherror") { return fmt.Errorf("failed to update regional hostname") } @@ -86,7 +86,7 @@ func (m *mockCloudFlareClient) UpdateDataLocalizationRegionalHostname(ctx contex return nil } -func (m *mockCloudFlareClient) DeleteDataLocalizationRegionalHostname(ctx context.Context, hostname string, params addressing.RegionalHostnameDeleteParams) error { +func (m *mockCloudFlareClient) DeleteDataLocalizationRegionalHostname(_ context.Context, hostname string, params addressing.RegionalHostnameDeleteParams) error { if strings.Contains(hostname, "rherror") { return fmt.Errorf("failed to delete regional hostname") } diff --git a/provider/cloudflare/cloudflare_test.go b/provider/cloudflare/cloudflare_test.go index d9b6de2ea..cd433e9e2 100644 --- a/provider/cloudflare/cloudflare_test.go +++ b/provider/cloudflare/cloudflare_test.go @@ -143,7 +143,7 @@ func NewMockCloudFlareClientWithRecords(records map[string][]dns.RecordResponse) return m } -func (m *mockCloudFlareClient) CreateDNSRecord(ctx context.Context, params dns.RecordNewParams) (*dns.RecordResponse, error) { +func (m *mockCloudFlareClient) CreateDNSRecord(_ context.Context, params dns.RecordNewParams) (*dns.RecordResponse, error) { body := params.Body.(dns.RecordNewParamsBody) record := dns.RecordResponse{ @@ -191,7 +191,7 @@ func (m *mockCloudFlareClient) ListDNSRecords(ctx context.Context, params dns.Re return iter } -func (m *mockCloudFlareClient) UpdateDNSRecord(ctx context.Context, recordID string, params dns.RecordUpdateParams) (*dns.RecordResponse, error) { +func (m *mockCloudFlareClient) UpdateDNSRecord(_ context.Context, recordID string, params dns.RecordUpdateParams) (*dns.RecordResponse, error) { zoneID := params.ZoneID.String() body := params.Body.(dns.RecordUpdateParamsBody) @@ -222,7 +222,7 @@ func (m *mockCloudFlareClient) UpdateDNSRecord(ctx context.Context, recordID str return &record, nil } -func (m *mockCloudFlareClient) DeleteDNSRecord(ctx context.Context, recordID string, params dns.RecordDeleteParams) error { +func (m *mockCloudFlareClient) DeleteDNSRecord(_ context.Context, recordID string, params dns.RecordDeleteParams) error { zoneID := params.ZoneID.String() m.Actions = append(m.Actions, MockAction{ Name: "Delete", @@ -258,7 +258,7 @@ func (m *mockCloudFlareClient) ZoneIDByName(zoneName string) (string, error) { return "", fmt.Errorf("zone %q not found in CloudFlare account - verify the zone exists and API credentials have access to it", zoneName) } -func (m *mockCloudFlareClient) ListZones(ctx context.Context, params zones.ZoneListParams) autoPager[zones.Zone] { +func (m *mockCloudFlareClient) ListZones(_ context.Context, _ zones.ZoneListParams) autoPager[zones.Zone] { if m.listZonesError != nil { return &mockAutoPager[zones.Zone]{ err: m.listZonesError, @@ -271,7 +271,7 @@ func (m *mockCloudFlareClient) ListZones(ctx context.Context, params zones.ZoneL results = append(results, zones.Zone{ ID: id, Name: zoneName, - Plan: zones.ZonePlan{IsSubscribed: strings.HasSuffix(zoneName, "bar.com")}, //nolint:SA1019 // Plan.IsSubscribed is deprecated but no replacement available yet + Plan: zones.ZonePlan{IsSubscribed: strings.HasSuffix(zoneName, "bar.com")}, // nolint:SA1019 // Plan.IsSubscribed is deprecated but no replacement available yet }) } @@ -280,7 +280,7 @@ func (m *mockCloudFlareClient) ListZones(ctx context.Context, params zones.ZoneL } } -func (m *mockCloudFlareClient) GetZone(ctx context.Context, zoneID string) (*zones.Zone, error) { +func (m *mockCloudFlareClient) GetZone(_ context.Context, zoneID string) (*zones.Zone, error) { if m.getZoneError != nil { return nil, m.getZoneError } @@ -290,7 +290,7 @@ func (m *mockCloudFlareClient) GetZone(ctx context.Context, zoneID string) (*zon return &zones.Zone{ ID: zoneID, Name: zoneName, - Plan: zones.ZonePlan{IsSubscribed: strings.HasSuffix(zoneName, "bar.com")}, //nolint:SA1019 // Plan.IsSubscribed is deprecated but no replacement available yet + Plan: zones.ZonePlan{IsSubscribed: strings.HasSuffix(zoneName, "bar.com")}, // nolint:SA1019 // Plan.IsSubscribed is deprecated but no replacement available yet }, nil } } @@ -1458,8 +1458,8 @@ func TestProviderPropertiesIdempotency(t *testing.T) { }{ { Name: "No custom properties, ExpectUpdates: false", - SetupProvider: func(p *CloudFlareProvider) {}, - SetupRecord: func(r *dns.RecordResponse) {}, + SetupProvider: func(_ *CloudFlareProvider) {}, + SetupRecord: func(_ *dns.RecordResponse) {}, ShouldBeUpdated: false, }, // Proxied tests @@ -2961,7 +2961,7 @@ func TestZoneService(t *testing.T) { t.Run("DeleteDataLocalizationRegionalHostname", func(t *testing.T) { t.Parallel() - params := deleteDataLocalizationRegionalHostnameParams(zoneID, regionalHostnameChange{}) + params := deleteDataLocalizationRegionalHostnameParams(zoneID) err := client.DeleteDataLocalizationRegionalHostname(ctx, "foo", params) assert.ErrorIs(t, err, context.Canceled) }) diff --git a/provider/digitalocean/digital_ocean_test.go b/provider/digitalocean/digital_ocean_test.go index ec2d62fcc..24ed00ead 100644 --- a/provider/digitalocean/digital_ocean_test.go +++ b/provider/digitalocean/digital_ocean_test.go @@ -50,7 +50,7 @@ func (m *mockDigitalOceanClient) RecordsByType(context.Context, string, string, return nil, nil, nil } -func (m *mockDigitalOceanClient) List(ctx context.Context, opt *godo.ListOptions) ([]godo.Domain, *godo.Response, error) { +func (m *mockDigitalOceanClient) List(_ context.Context, opt *godo.ListOptions) ([]godo.Domain, *godo.Response, error) { if opt == nil || opt.Page == 0 { return []godo.Domain{{Name: "foo.com"}, {Name: "example.com"}}, &godo.Response{ Links: &godo.Links{ @@ -76,23 +76,23 @@ func (m *mockDigitalOceanClient) Delete(context.Context, string) (*godo.Response return nil, fmt.Errorf("failed to delete domain") } -func (m *mockDigitalOceanClient) DeleteRecord(ctx context.Context, domain string, id int) (*godo.Response, error) { +func (m *mockDigitalOceanClient) DeleteRecord(_ context.Context, _ string, _ int) (*godo.Response, error) { return nil, fmt.Errorf("failed to delete record") } -func (m *mockDigitalOceanClient) EditRecord(ctx context.Context, domain string, id int, editRequest *godo.DomainRecordEditRequest) (*godo.DomainRecord, *godo.Response, error) { +func (m *mockDigitalOceanClient) EditRecord(_ context.Context, _ string, _ int, _ *godo.DomainRecordEditRequest) (*godo.DomainRecord, *godo.Response, error) { return &godo.DomainRecord{ID: 1}, nil, nil } -func (m *mockDigitalOceanClient) Get(ctx context.Context, name string) (*godo.Domain, *godo.Response, error) { +func (m *mockDigitalOceanClient) Get(_ context.Context, _ string) (*godo.Domain, *godo.Response, error) { return &godo.Domain{Name: "example.com"}, nil, nil } -func (m *mockDigitalOceanClient) Record(ctx context.Context, domain string, id int) (*godo.DomainRecord, *godo.Response, error) { +func (m *mockDigitalOceanClient) Record(_ context.Context, _ string, _ int) (*godo.DomainRecord, *godo.Response, error) { return &godo.DomainRecord{ID: 1}, nil, nil } -func (m *mockDigitalOceanClient) Records(ctx context.Context, domain string, opt *godo.ListOptions) ([]godo.DomainRecord, *godo.Response, error) { +func (m *mockDigitalOceanClient) Records(_ context.Context, domain string, opt *godo.ListOptions) ([]godo.DomainRecord, *godo.Response, error) { switch domain { case "foo.com": if opt == nil || opt.Page == 0 { @@ -163,23 +163,23 @@ func (m *mockDigitalOceanRecordsFail) Delete(context.Context, string) (*godo.Res return nil, fmt.Errorf("failed to delete record") } -func (m *mockDigitalOceanRecordsFail) DeleteRecord(ctx context.Context, domain string, id int) (*godo.Response, error) { +func (m *mockDigitalOceanRecordsFail) DeleteRecord(_ context.Context, _ string, _ int) (*godo.Response, error) { return nil, fmt.Errorf("failed to delete record") } -func (m *mockDigitalOceanRecordsFail) EditRecord(ctx context.Context, domain string, id int, editRequest *godo.DomainRecordEditRequest) (*godo.DomainRecord, *godo.Response, error) { +func (m *mockDigitalOceanRecordsFail) EditRecord(_ context.Context, _ string, _ int, _ *godo.DomainRecordEditRequest) (*godo.DomainRecord, *godo.Response, error) { return &godo.DomainRecord{ID: 1}, nil, nil } -func (m *mockDigitalOceanRecordsFail) Get(ctx context.Context, name string) (*godo.Domain, *godo.Response, error) { +func (m *mockDigitalOceanRecordsFail) Get(_ context.Context, _ string) (*godo.Domain, *godo.Response, error) { return &godo.Domain{Name: "example.com"}, nil, nil } -func (m *mockDigitalOceanRecordsFail) Record(ctx context.Context, domain string, id int) (*godo.DomainRecord, *godo.Response, error) { +func (m *mockDigitalOceanRecordsFail) Record(_ context.Context, _ string, _ int) (*godo.DomainRecord, *godo.Response, error) { return nil, nil, fmt.Errorf("Failed to get records") } -func (m *mockDigitalOceanRecordsFail) Records(ctx context.Context, domain string, opt *godo.ListOptions) ([]godo.DomainRecord, *godo.Response, error) { +func (m *mockDigitalOceanRecordsFail) Records(_ context.Context, _ string, _ *godo.ListOptions) ([]godo.DomainRecord, *godo.Response, error) { return []godo.DomainRecord{}, nil, fmt.Errorf("Failed to get records") } diff --git a/provider/exoscale/exoscale.go b/provider/exoscale/exoscale.go index 86c40388b..598fb880f 100644 --- a/provider/exoscale/exoscale.go +++ b/provider/exoscale/exoscale.go @@ -70,7 +70,7 @@ func NewExoscaleProvider(env, zone, key, secret string, dryRun bool, opts ...Exo func NewExoscaleProviderWithClient(client EgoscaleClientI, env, zone string, dryRun bool, opts ...ExoscaleOption) *ExoscaleProvider { ep := &ExoscaleProvider{ filter: &zoneFilter{}, - OnApplyChanges: func(changes *plan.Changes) {}, + OnApplyChanges: func(_ *plan.Changes) {}, domain: endpoint.NewDomainFilter([]string{""}), client: client, apiEnv: env, diff --git a/provider/exoscale/exoscale_test.go b/provider/exoscale/exoscale_test.go index f12004e80..5de4d36d0 100644 --- a/provider/exoscale/exoscale_test.go +++ b/provider/exoscale/exoscale_test.go @@ -82,7 +82,7 @@ func NewExoscaleClientStub() EgoscaleClientI { return ep } -func (ep *ExoscaleClientStub) ListDNSDomains(ctx context.Context, _ string) ([]egoscale.DNSDomain, error) { +func (ep *ExoscaleClientStub) ListDNSDomains(_ context.Context, _ string) ([]egoscale.DNSDomain, error) { domains := []egoscale.DNSDomain{ {ID: &domainIDs[0], UnicodeName: strPtr("foo.com")}, {ID: &domainIDs[1], UnicodeName: strPtr("bar.com")}, @@ -90,21 +90,21 @@ func (ep *ExoscaleClientStub) ListDNSDomains(ctx context.Context, _ string) ([]e return domains, nil } -func (ep *ExoscaleClientStub) ListDNSDomainRecords(ctx context.Context, _, domainID string) ([]egoscale.DNSDomainRecord, error) { +func (ep *ExoscaleClientStub) ListDNSDomainRecords(_ context.Context, _, domainID string) ([]egoscale.DNSDomainRecord, error) { return groups[domainID], nil } -func (ep *ExoscaleClientStub) CreateDNSDomainRecord(ctx context.Context, _, domainID string, record *egoscale.DNSDomainRecord) (*egoscale.DNSDomainRecord, error) { +func (ep *ExoscaleClientStub) CreateDNSDomainRecord(_ context.Context, _, domainID string, record *egoscale.DNSDomainRecord) (*egoscale.DNSDomainRecord, error) { createExoscale = append(createExoscale, createRecordExoscale{domainID: domainID, record: record}) return record, nil } -func (ep *ExoscaleClientStub) DeleteDNSDomainRecord(ctx context.Context, _, domainID string, record *egoscale.DNSDomainRecord) error { +func (ep *ExoscaleClientStub) DeleteDNSDomainRecord(_ context.Context, _, domainID string, record *egoscale.DNSDomainRecord) error { deleteExoscale = append(deleteExoscale, deleteRecordExoscale{domainID: domainID, recordID: *record.ID}) return nil } -func (ep *ExoscaleClientStub) UpdateDNSDomainRecord(ctx context.Context, _, domainID string, record *egoscale.DNSDomainRecord) error { +func (ep *ExoscaleClientStub) UpdateDNSDomainRecord(_ context.Context, _, domainID string, record *egoscale.DNSDomainRecord) error { updateExoscale = append(updateExoscale, updateRecordExoscale{domainID: domainID, record: record}) return nil } @@ -439,7 +439,7 @@ func TestExoscaleWithDomain_SetsDomain(t *testing.T) { } for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + t.Run(test.name, func(_ *testing.T) { p := &ExoscaleProvider{} df := endpoint.NewDomainFilter(test.domainFilter) diff --git a/provider/gandi/gandi.go b/provider/gandi/gandi.go index e8fdea337..0bfc6733a 100644 --- a/provider/gandi/gandi.go +++ b/provider/gandi/gandi.go @@ -51,7 +51,7 @@ type GandiProvider struct { DryRun bool } -func NewGandiProvider(ctx context.Context, domainFilter *endpoint.DomainFilter, dryRun bool) (*GandiProvider, error) { +func NewGandiProvider(domainFilter *endpoint.DomainFilter, dryRun bool) (*GandiProvider, error) { key, ok_key := os.LookupEnv("GANDI_KEY") pat, ok_pat := os.LookupEnv("GANDI_PAT") if !ok_key && !ok_pat { @@ -105,7 +105,7 @@ func (p *GandiProvider) Zones() ([]string, error) { return zones, nil } -func (p *GandiProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p *GandiProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { liveDNSZones, err := p.Zones() if err != nil { return nil, err diff --git a/provider/gandi/gandi_test.go b/provider/gandi/gandi_test.go index 8e564b8e1..1271aa964 100644 --- a/provider/gandi/gandi_test.go +++ b/provider/gandi/gandi_test.go @@ -156,35 +156,35 @@ func (m *mockGandiClient) ListDomains() ([]domain.ListResponse, error) { func TestNewGandiProvider(t *testing.T) { _ = os.Setenv("GANDI_KEY", "myGandiKey") - provider, err := NewGandiProvider(context.Background(), endpoint.NewDomainFilter([]string{"example.com"}), true) + provider, err := NewGandiProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err != nil { t.Errorf("failed : %s", err) } assert.True(t, provider.DryRun) _ = os.Setenv("GANDI_PAT", "myGandiPAT") - provider, err = NewGandiProvider(context.Background(), endpoint.NewDomainFilter([]string{"example.com"}), true) + provider, err = NewGandiProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err != nil { t.Errorf("failed : %s", err) } assert.True(t, provider.DryRun) _ = os.Unsetenv("GANDI_KEY") - provider, err = NewGandiProvider(context.Background(), endpoint.NewDomainFilter([]string{"example.com"}), true) + provider, err = NewGandiProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err != nil { t.Errorf("failed : %s", err) } assert.True(t, provider.DryRun) _ = os.Setenv("GANDI_SHARING_ID", "aSharingId") - provider, err = NewGandiProvider(context.Background(), endpoint.NewDomainFilter([]string{"example.com"}), false) + provider, err = NewGandiProvider(endpoint.NewDomainFilter([]string{"example.com"}), false) if err != nil { t.Errorf("failed : %s", err) } assert.False(t, provider.DryRun) _ = os.Unsetenv("GANDI_PAT") - _, err = NewGandiProvider(context.Background(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err = NewGandiProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err == nil { t.Errorf("expected to fail") } diff --git a/provider/godaddy/client_test.go b/provider/godaddy/client_test.go index dd8e94d08..18c5e714c 100644 --- a/provider/godaddy/client_test.go +++ b/provider/godaddy/client_test.go @@ -32,7 +32,7 @@ func TestClient_DoWhenQuotaExceeded(t *testing.T) { assert := assert.New(t) // Mock server to return 429 with a JSON payload - mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusTooManyRequests) _, err := w.Write([]byte(`{"code": "QUOTA_EXCEEDED", "message": "rate limit exceeded"}`)) diff --git a/provider/google/google_test.go b/provider/google/google_test.go index 992187f09..1ea5696e4 100644 --- a/provider/google/google_test.go +++ b/provider/google/google_test.go @@ -48,7 +48,7 @@ type mockManagedZonesCreateCall struct { managedZone *dns.ManagedZone } -func (m *mockManagedZonesCreateCall) Do(opts ...googleapi.CallOption) (*dns.ManagedZone, error) { +func (m *mockManagedZonesCreateCall) Do(_ ...googleapi.CallOption) (*dns.ManagedZone, error) { zoneKey := zoneKey(m.project, m.managedZone.Name) if _, ok := testZones[zoneKey]; ok { @@ -65,7 +65,7 @@ type mockManagedZonesListCall struct { zonesListSoftErr error } -func (m *mockManagedZonesListCall) Pages(ctx context.Context, f func(*dns.ManagedZonesListResponse) error) error { +func (m *mockManagedZonesListCall) Pages(_ context.Context, f func(*dns.ManagedZonesListResponse) error) error { zones := []*dns.ManagedZone{} for k, v := range testZones { @@ -99,7 +99,7 @@ type mockResourceRecordSetsListCall struct { recordsListSoftErr error } -func (m *mockResourceRecordSetsListCall) Pages(ctx context.Context, f func(*dns.ResourceRecordSetsListResponse) error) error { +func (m *mockResourceRecordSetsListCall) Pages(_ context.Context, f func(*dns.ResourceRecordSetsListResponse) error) error { zoneKey := zoneKey(m.project, m.managedZone) if _, ok := testZones[zoneKey]; !ok { @@ -133,7 +133,7 @@ type mockChangesCreateCall struct { change *dns.Change } -func (m *mockChangesCreateCall) Do(opts ...googleapi.CallOption) (*dns.Change, error) { +func (m *mockChangesCreateCall) Do(_ ...googleapi.CallOption) (*dns.Change, error) { zoneKey := zoneKey(m.project, m.managedZone) if _, ok := testZones[zoneKey]; !ok { diff --git a/provider/inmemory/inmemory.go b/provider/inmemory/inmemory.go index f45fd0b1b..ece3a5ea1 100644 --- a/provider/inmemory/inmemory.go +++ b/provider/inmemory/inmemory.go @@ -60,7 +60,7 @@ type InMemoryOption func(*InMemoryProvider) // InMemoryWithLogging injects logging when ApplyChanges is called func InMemoryWithLogging() InMemoryOption { return func(p *InMemoryProvider) { - p.OnApplyChanges = func(ctx context.Context, changes *plan.Changes) { + p.OnApplyChanges = func(_ context.Context, changes *plan.Changes) { for _, v := range changes.Create { log.Infof("CREATE: %v", v) } @@ -99,7 +99,7 @@ func InMemoryInitZones(zones []string) InMemoryOption { func NewInMemoryProvider(opts ...InMemoryOption) *InMemoryProvider { im := &InMemoryProvider{ filter: &filter{}, - OnApplyChanges: func(ctx context.Context, changes *plan.Changes) {}, + OnApplyChanges: func(_ context.Context, _ *plan.Changes) {}, OnRecords: func() {}, domain: endpoint.NewDomainFilter([]string{""}), client: newInMemoryClient(), @@ -123,7 +123,7 @@ func (im *InMemoryProvider) Zones() map[string]string { } // Records returns the list of endpoints -func (im *InMemoryProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (im *InMemoryProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { defer im.OnRecords() endpoints := make([]*endpoint.Endpoint, 0) @@ -279,7 +279,7 @@ func (c *inMemoryClient) CreateZone(zone string) error { return nil } -func (c *inMemoryClient) ApplyChanges(ctx context.Context, zoneID string, changes *plan.Changes) error { +func (c *inMemoryClient) ApplyChanges(_ context.Context, zoneID string, changes *plan.Changes) error { if err := c.validateChangeBatch(zoneID, changes); err != nil { return err } diff --git a/provider/ns1/ns1.go b/provider/ns1/ns1.go index d41f9bf69..8046037df 100644 --- a/provider/ns1/ns1.go +++ b/provider/ns1/ns1.go @@ -145,7 +145,7 @@ func newNS1ProviderWithHTTPClient(config NS1Config, client *http.Client) (*NS1Pr } // Records returns the endpoints this provider knows about -func (p *NS1Provider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p *NS1Provider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { zones, err := p.zonesFiltered() if err != nil { return nil, err @@ -274,7 +274,7 @@ type ns1Change struct { } // ApplyChanges applies a given set of changes in a given zone. -func (p *NS1Provider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (p *NS1Provider) ApplyChanges(_ context.Context, changes *plan.Changes) error { combinedChanges := make([]*ns1Change, 0, len(changes.Create)+len(changes.UpdateNew)+len(changes.Delete)) combinedChanges = append(combinedChanges, newNS1Changes(ns1Create, changes.Create)...) diff --git a/provider/ns1/ns1_test.go b/provider/ns1/ns1_test.go index 930fce1db..afd40f65c 100644 --- a/provider/ns1/ns1_test.go +++ b/provider/ns1/ns1_test.go @@ -38,15 +38,15 @@ type MockNS1DomainClient struct { mock.Mock } -func (m *MockNS1DomainClient) CreateRecord(r *dns.Record) (*http.Response, error) { +func (m *MockNS1DomainClient) CreateRecord(_ *dns.Record) (*http.Response, error) { return &http.Response{}, nil } -func (m *MockNS1DomainClient) DeleteRecord(zone string, domain string, t string) (*http.Response, error) { +func (m *MockNS1DomainClient) DeleteRecord(_ string, _ string, _ string) (*http.Response, error) { return &http.Response{}, nil } -func (m *MockNS1DomainClient) UpdateRecord(r *dns.Record) (*http.Response, error) { +func (m *MockNS1DomainClient) UpdateRecord(_ *dns.Record) (*http.Response, error) { return &http.Response{}, nil } @@ -89,11 +89,11 @@ func (m *MockNS1GetZoneFail) DeleteRecord(_ string, _ string, _ string) (*http.R return &http.Response{}, nil } -func (m *MockNS1GetZoneFail) UpdateRecord(r *dns.Record) (*http.Response, error) { +func (m *MockNS1GetZoneFail) UpdateRecord(_ *dns.Record) (*http.Response, error) { return &http.Response{}, nil } -func (m *MockNS1GetZoneFail) GetZone(zone string) (*dns.Zone, *http.Response, error) { +func (m *MockNS1GetZoneFail) GetZone(_ string) (*dns.Zone, *http.Response, error) { return nil, nil, api.ErrZoneMissing } @@ -115,11 +115,11 @@ func (m *MockNS1ListZonesFail) DeleteRecord(_ string, _ string, _ string) (*http return &http.Response{}, nil } -func (m *MockNS1ListZonesFail) UpdateRecord(r *dns.Record) (*http.Response, error) { +func (m *MockNS1ListZonesFail) UpdateRecord(_ *dns.Record) (*http.Response, error) { return &http.Response{}, nil } -func (m *MockNS1ListZonesFail) GetZone(zone string) (*dns.Zone, *http.Response, error) { +func (m *MockNS1ListZonesFail) GetZone(_ string) (*dns.Zone, *http.Response, error) { return &dns.Zone{}, &http.Response{}, nil } diff --git a/provider/oci/oci_test.go b/provider/oci/oci_test.go index a7c914cd8..07a97f77e 100644 --- a/provider/oci/oci_test.go +++ b/provider/oci/oci_test.go @@ -82,7 +82,7 @@ func (c *mockOCIDNSClient) ListZones(_ context.Context, request dns.ListZonesReq }, nil } -func (c *mockOCIDNSClient) GetZoneRecords(ctx context.Context, request dns.GetZoneRecordsRequest) (dns.GetZoneRecordsResponse, error) { +func (c *mockOCIDNSClient) GetZoneRecords(_ context.Context, request dns.GetZoneRecordsRequest) (dns.GetZoneRecordsResponse, error) { var response dns.GetZoneRecordsResponse var err error if request.ZoneNameOrId == nil { @@ -125,7 +125,7 @@ func (c *mockOCIDNSClient) GetZoneRecords(ctx context.Context, request dns.GetZo return response, err } -func (c *mockOCIDNSClient) PatchZoneRecords(_ context.Context, request dns.PatchZoneRecordsRequest) (dns.PatchZoneRecordsResponse, error) { +func (c *mockOCIDNSClient) PatchZoneRecords(_ context.Context, _ dns.PatchZoneRecordsRequest) (dns.PatchZoneRecordsResponse, error) { return dns.PatchZoneRecordsResponse{}, nil } @@ -592,7 +592,7 @@ func sortEndpointTargets(endpoints []*endpoint.Endpoint) { } } -func (c *mutableMockOCIDNSClient) PatchZoneRecords(ctx context.Context, request dns.PatchZoneRecordsRequest) (dns.PatchZoneRecordsResponse, error) { +func (c *mutableMockOCIDNSClient) PatchZoneRecords(_ context.Context, request dns.PatchZoneRecordsRequest) (dns.PatchZoneRecordsResponse, error) { var response dns.PatchZoneRecordsResponse if request.ZoneNameOrId == nil { return response, errors.New("no name or id") diff --git a/provider/ovh/ovh.go b/provider/ovh/ovh.go index e188d2ade..987e2c82a 100644 --- a/provider/ovh/ovh.go +++ b/provider/ovh/ovh.go @@ -124,7 +124,12 @@ type ovhChange struct { } // NewOVHProvider initializes a new OVH DNS based Provider. -func NewOVHProvider(ctx context.Context, domainFilter *endpoint.DomainFilter, endpoint string, apiRateLimit int, enableCNAMERelative, dryRun bool) (*OVHProvider, error) { +func NewOVHProvider( + domainFilter *endpoint.DomainFilter, + endpoint string, + apiRateLimit int, + enableCNAMERelative, + dryRun bool) (*OVHProvider, error) { client, err := ovh.NewEndpointClient(endpoint) if err != nil { return nil, err diff --git a/provider/ovh/ovh_test.go b/provider/ovh/ovh_test.go index 7a5adec77..f664e4cc5 100644 --- a/provider/ovh/ovh_test.go +++ b/provider/ovh/ovh_test.go @@ -40,7 +40,7 @@ type mockOvhClient struct { mock.Mock } -func (c *mockOvhClient) PostWithContext(ctx context.Context, endpoint string, input any, output any) error { +func (c *mockOvhClient) PostWithContext(_ context.Context, endpoint string, input any, output any) error { stub := c.Called(endpoint, input) data, err := json.Marshal(stub.Get(0)) if err != nil { @@ -50,7 +50,7 @@ func (c *mockOvhClient) PostWithContext(ctx context.Context, endpoint string, in return stub.Error(1) } -func (c *mockOvhClient) PutWithContext(ctx context.Context, endpoint string, input any, output any) error { +func (c *mockOvhClient) PutWithContext(_ context.Context, endpoint string, input any, output any) error { stub := c.Called(endpoint, input) data, err := json.Marshal(stub.Get(0)) if err != nil { @@ -60,7 +60,7 @@ func (c *mockOvhClient) PutWithContext(ctx context.Context, endpoint string, inp return stub.Error(1) } -func (c *mockOvhClient) GetWithContext(ctx context.Context, endpoint string, output any) error { +func (c *mockOvhClient) GetWithContext(_ context.Context, endpoint string, output any) error { stub := c.Called(endpoint) data, err := json.Marshal(stub.Get(0)) if err != nil { @@ -70,7 +70,7 @@ func (c *mockOvhClient) GetWithContext(ctx context.Context, endpoint string, out return stub.Error(1) } -func (c *mockOvhClient) DeleteWithContext(ctx context.Context, endpoint string, output any) error { +func (c *mockOvhClient) DeleteWithContext(_ context.Context, endpoint string, output any) error { stub := c.Called(endpoint) data, err := json.Marshal(stub.Get(0)) if err != nil { @@ -644,13 +644,13 @@ func TestOvhRecordString(t *testing.T) { func TestNewOvhProvider(t *testing.T) { domainFilter := &endpoint.DomainFilter{} - _, err := NewOVHProvider(t.Context(), domainFilter, "ovh-eu", 20, false, true) + _, err := NewOVHProvider(domainFilter, "ovh-eu", 20, false, true) td.CmpError(t, err) t.Setenv("OVH_APPLICATION_KEY", "aaaaaa") t.Setenv("OVH_APPLICATION_SECRET", "bbbbbb") t.Setenv("OVH_CONSUMER_KEY", "cccccc") - _, err = NewOVHProvider(t.Context(), domainFilter, "ovh-eu", 20, false, true) + _, err = NewOVHProvider(domainFilter, "ovh-eu", 20, false, true) td.CmpNoError(t, err) } diff --git a/provider/pdns/pdns.go b/provider/pdns/pdns.go index caff96542..0c06b63af 100644 --- a/provider/pdns/pdns.go +++ b/provider/pdns/pdns.go @@ -466,7 +466,7 @@ func (p *PDNSProvider) AdjustEndpoints(endpoints []*endpoint.Endpoint) ([]*endpo // ApplyChanges takes a list of changes (endpoints) and updates the PDNS server // by sending the correct HTTP PATCH requests to a matching zone -func (p *PDNSProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (p *PDNSProvider) ApplyChanges(_ context.Context, changes *plan.Changes) error { startTime := time.Now() // Create diff --git a/provider/pdns/pdns_test.go b/provider/pdns/pdns_test.go index 2dc62a0b1..4bdae5103 100644 --- a/provider/pdns/pdns_test.go +++ b/provider/pdns/pdns_test.go @@ -675,11 +675,11 @@ func (c *PDNSAPIClientStub) PartitionZones(zones []pgo.Zone) ([]pgo.Zone, []pgo. return zones, nil } -func (c *PDNSAPIClientStub) ListZone(zoneID string) (pgo.Zone, *http.Response, error) { +func (c *PDNSAPIClientStub) ListZone(_ string) (pgo.Zone, *http.Response, error) { return ZoneMixed, nil, nil } -func (c *PDNSAPIClientStub) PatchZone(zoneID string, zoneStruct pgo.Zone) (*http.Response, error) { +func (c *PDNSAPIClientStub) PatchZone(_ string, _ pgo.Zone) (*http.Response, error) { return &http.Response{}, nil } @@ -710,7 +710,7 @@ func (c *PDNSAPIClientStubEmptyZones) ListZone(zoneID string) (pgo.Zone, *http.R return pgo.Zone{}, nil, nil } -func (c *PDNSAPIClientStubEmptyZones) PatchZone(zoneID string, zoneStruct pgo.Zone) (*http.Response, error) { +func (c *PDNSAPIClientStubEmptyZones) PatchZone(_ string, zoneStruct pgo.Zone) (*http.Response, error) { c.patchedZones = append(c.patchedZones, zoneStruct) return &http.Response{}, nil } @@ -723,7 +723,7 @@ type PDNSAPIClientStubPatchZoneFailure struct { } // Just overwrite the PatchZone method to introduce a failure -func (c *PDNSAPIClientStubPatchZoneFailure) PatchZone(zoneID string, zoneStruct pgo.Zone) (*http.Response, error) { +func (c *PDNSAPIClientStubPatchZoneFailure) PatchZone(_ string, _ pgo.Zone) (*http.Response, error) { return nil, provider.NewSoftErrorf("Generic PDNS Error") } @@ -735,7 +735,7 @@ type PDNSAPIClientStubListZoneFailure struct { } // Just overwrite the ListZone method to introduce a failure -func (c *PDNSAPIClientStubListZoneFailure) ListZone(zoneID string) (pgo.Zone, *http.Response, error) { +func (c *PDNSAPIClientStubListZoneFailure) ListZone(_ string) (pgo.Zone, *http.Response, error) { return pgo.Zone{}, nil, provider.NewSoftErrorf("Generic PDNS Error") } @@ -777,7 +777,7 @@ func (c *PDNSAPIClientStubPartitionZones) ListZone(zoneID string) (pgo.Zone, *ht } // Just overwrite the ListZones method to introduce a failure -func (c *PDNSAPIClientStubPartitionZones) PartitionZones(zones []pgo.Zone) ([]pgo.Zone, []pgo.Zone) { +func (c *PDNSAPIClientStubPartitionZones) PartitionZones(_ []pgo.Zone) ([]pgo.Zone, []pgo.Zone) { return []pgo.Zone{ZoneEmpty}, []pgo.Zone{ZoneEmptyLong, ZoneEmpty2} } diff --git a/provider/pihole/clientV6_test.go b/provider/pihole/clientV6_test.go index 34be0e28b..66cdcd1fb 100644 --- a/provider/pihole/clientV6_test.go +++ b/provider/pihole/clientV6_test.go @@ -95,7 +95,7 @@ func newTestServerV6(t *testing.T, hdlr http.HandlerFunc) *httptest.Server { type errorTransportV6 struct{} -func (t *errorTransportV6) RoundTrip(req *http.Request) (*http.Response, error) { +func (t *errorTransportV6) RoundTrip(_ *http.Request) (*http.Response, error) { return nil, errors.New("network error") } @@ -414,7 +414,7 @@ func TestErrorsV6(t *testing.T) { t.Fatal("Expected error for nil context") } // Unmarshalling error - srvrErrJson := newTestServerV6(t, func(w http.ResponseWriter, r *http.Request) { + srvrErrJson := newTestServerV6(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") @@ -824,7 +824,7 @@ func TestDoV6AdditionalCases(t *testing.T) { }) t.Run("item already present", func(t *testing.T) { - server := newTestServerV6(t, func(w http.ResponseWriter, r *http.Request) { + server := newTestServerV6(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{ "error": { @@ -852,7 +852,7 @@ func TestDoV6AdditionalCases(t *testing.T) { }) t.Run("404 on DELETE", func(t *testing.T) { - server := newTestServerV6(t, func(w http.ResponseWriter, r *http.Request) { + server := newTestServerV6(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) w.Write([]byte(`{ "error": { diff --git a/provider/pihole/client_test.go b/provider/pihole/client_test.go index 02745271b..be930626a 100644 --- a/provider/pihole/client_test.go +++ b/provider/pihole/client_test.go @@ -228,36 +228,6 @@ func TestListRecords(t *testing.T) { } -// Helper function to test error scenarios -func testErrorScenarios(t *testing.T, srvrErr *httptest.Server) { - t.Helper() - cfgExpired := PiholeConfig{ - Server: srvrErr.URL, - } - clExpired, err := newPiholeClient(cfgExpired) - if err != nil { - t.Fatal(err) - } - // set clExpired.token to a valid token - clExpired.(*piholeClient).token = "expired" - clExpired.(*piholeClient).cfg.Password = "notcorrect" - - cnamerecs, err := clExpired.listRecords(context.Background(), "notarealrecordtype") - if err == nil { - t.Fatal("Should return error, type is unknown ! ") - } - cnamerecs, err = clExpired.listRecords(context.Background(), endpoint.RecordTypeCNAME) - if err == nil { - t.Fatal("Should return error on failed auth ! ") - } - clExpired.(*piholeClient).token = "correct" - clExpired.(*piholeClient).cfg.Password = "correct" - cnamerecs, err = clExpired.listRecords(context.Background(), endpoint.RecordTypeCNAME) - if len(cnamerecs) != 0 { - t.Fatal("Should return empty on missing data in response ! ") - } -} - func TestErrorScenarios(t *testing.T) { // Test errors token srvrErr := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { diff --git a/provider/pihole/pihole_test.go b/provider/pihole/pihole_test.go index 6da4d6df4..c282e3ac2 100644 --- a/provider/pihole/pihole_test.go +++ b/provider/pihole/pihole_test.go @@ -33,7 +33,7 @@ type testPiholeClient struct { requests *requestTracker } -func (t *testPiholeClient) listRecords(ctx context.Context, rtype string) ([]*endpoint.Endpoint, error) { +func (t *testPiholeClient) listRecords(_ context.Context, rtype string) ([]*endpoint.Endpoint, error) { out := make([]*endpoint.Endpoint, 0) for _, ep := range t.endpoints { if ep.RecordType == rtype { @@ -43,13 +43,13 @@ func (t *testPiholeClient) listRecords(ctx context.Context, rtype string) ([]*en return out, nil } -func (t *testPiholeClient) createRecord(ctx context.Context, ep *endpoint.Endpoint) error { +func (t *testPiholeClient) createRecord(_ context.Context, ep *endpoint.Endpoint) error { t.endpoints = append(t.endpoints, ep) t.requests.createRequests = append(t.requests.createRequests, ep) return nil } -func (t *testPiholeClient) deleteRecord(ctx context.Context, ep *endpoint.Endpoint) error { +func (t *testPiholeClient) deleteRecord(_ context.Context, ep *endpoint.Endpoint) error { newEPs := make([]*endpoint.Endpoint, 0) for _, existing := range t.endpoints { if existing.DNSName != ep.DNSName && existing.Targets[0] != ep.Targets[0] { diff --git a/provider/rfc2136/rfc2136.go b/provider/rfc2136/rfc2136.go index 3bb588b6a..9e62c1c14 100644 --- a/provider/rfc2136/rfc2136.go +++ b/provider/rfc2136/rfc2136.go @@ -184,7 +184,7 @@ func (r *rfc2136Provider) KeyData(nameserver string) (string, *gss.Client, error } // Records returns the list of records. -func (r *rfc2136Provider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (r *rfc2136Provider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { rrs, err := r.List() if err != nil { return nil, err @@ -347,7 +347,7 @@ func (r *rfc2136Provider) GenerateReverseRecord(ip string, hostname string) []*e } // ApplyChanges applies a given set of changes in a given zone. -func (r *rfc2136Provider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (r *rfc2136Provider) ApplyChanges(_ context.Context, changes *plan.Changes) error { log.Debugf("ApplyChanges (Create: %d, UpdateOld: %d, UpdateNew: %d, Delete: %d)", len(changes.Create), len(changes.UpdateOld), len(changes.UpdateNew), len(changes.Delete)) var errs []error diff --git a/provider/rfc2136/rfc2136_test.go b/provider/rfc2136/rfc2136_test.go index 9a1229422..f17c72342 100644 --- a/provider/rfc2136/rfc2136_test.go +++ b/provider/rfc2136/rfc2136_test.go @@ -149,7 +149,7 @@ func (r *rfc2136Stub) setOutput(output []string) error { return nil } -func (r *rfc2136Stub) IncomeTransfer(m *dns.Msg, a string) (chan *dns.Envelope, error) { +func (r *rfc2136Stub) IncomeTransfer(m *dns.Msg, _ string) (chan *dns.Envelope, error) { outChan := make(chan *dns.Envelope) go func() { for _, e := range r.output { diff --git a/provider/scaleway/scaleway.go b/provider/scaleway/scaleway.go index 47a3db7a5..3c7943331 100644 --- a/provider/scaleway/scaleway.go +++ b/provider/scaleway/scaleway.go @@ -55,7 +55,7 @@ type ScalewayChange struct { } // NewScalewayProvider initializes a new Scaleway DNS provider -func NewScalewayProvider(ctx context.Context, domainFilter *endpoint.DomainFilter, dryRun bool) (*ScalewayProvider, error) { +func NewScalewayProvider(domainFilter *endpoint.DomainFilter, dryRun bool) (*ScalewayProvider, error) { var err error defaultPageSize := uint64(1000) if envPageSize, ok := os.LookupEnv("SCW_DEFAULT_PAGE_SIZE"); ok { diff --git a/provider/scaleway/scaleway_test.go b/provider/scaleway/scaleway_test.go index eec95c695..b2f3e233e 100644 --- a/provider/scaleway/scaleway_test.go +++ b/provider/scaleway/scaleway_test.go @@ -18,12 +18,14 @@ package scaleway import ( "context" + "io" "os" "reflect" "testing" domain "github.com/scaleway/scaleway-sdk-go/api/domain/v2beta1" "github.com/scaleway/scaleway-sdk-go/scw" + log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -35,7 +37,7 @@ type mockScalewayDomain struct { *domain.API } -func (m *mockScalewayDomain) ListDNSZones(req *domain.ListDNSZonesRequest, opts ...scw.RequestOption) (*domain.ListDNSZonesResponse, error) { +func (m *mockScalewayDomain) ListDNSZones(_ *domain.ListDNSZonesRequest, _ ...scw.RequestOption) (*domain.ListDNSZonesResponse, error) { return &domain.ListDNSZonesResponse{ DNSZones: []*domain.DNSZone{ { @@ -58,7 +60,7 @@ func (m *mockScalewayDomain) ListDNSZones(req *domain.ListDNSZonesRequest, opts }, nil } -func (m *mockScalewayDomain) ListDNSZoneRecords(req *domain.ListDNSZoneRecordsRequest, opts ...scw.RequestOption) (*domain.ListDNSZoneRecordsResponse, error) { +func (m *mockScalewayDomain) ListDNSZoneRecords(req *domain.ListDNSZoneRecordsRequest, _ ...scw.RequestOption) (*domain.ListDNSZoneRecordsResponse, error) { records := []*domain.Record{} if req.DNSZone == "example.com" { records = []*domain.Record{ @@ -124,49 +126,50 @@ func TestScalewayProvider_NewScalewayProvider(t *testing.T) { } _ = os.Setenv(scw.ScwActiveProfileEnv, "foo") _ = os.Setenv(scw.ScwConfigPathEnv, tmpDir+"/config.yaml") - _, err = NewScalewayProvider(context.TODO(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err = NewScalewayProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err != nil { t.Errorf("failed : %s", err) } _ = os.Setenv(scw.ScwAccessKeyEnv, "SCWXXXXXXXXXXXXXXXXX") _ = os.Setenv(scw.ScwSecretKeyEnv, "11111111-1111-1111-1111-111111111111") - _, err = NewScalewayProvider(context.TODO(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err = NewScalewayProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err != nil { t.Errorf("failed : %s", err) } _ = os.Unsetenv(scw.ScwSecretKeyEnv) - _, err = NewScalewayProvider(context.TODO(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err = NewScalewayProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err == nil { t.Errorf("expected to fail") } _ = os.Setenv(scw.ScwSecretKeyEnv, "dummy") - _, err = NewScalewayProvider(context.TODO(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err = NewScalewayProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err == nil { t.Errorf("expected to fail") } _ = os.Unsetenv(scw.ScwAccessKeyEnv) _ = os.Setenv(scw.ScwSecretKeyEnv, "11111111-1111-1111-1111-111111111111") - _, err = NewScalewayProvider(context.TODO(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err = NewScalewayProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err == nil { t.Errorf("expected to fail") } _ = os.Setenv(scw.ScwAccessKeyEnv, "dummy") - _, err = NewScalewayProvider(context.TODO(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err = NewScalewayProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) if err == nil { t.Errorf("expected to fail") } } func TestScalewayProvider_OptionnalConfigFile(t *testing.T) { + log.SetOutput(io.Discard) _ = os.Setenv(scw.ScwAccessKeyEnv, "SCWXXXXXXXXXXXXXXXXX") _ = os.Setenv(scw.ScwSecretKeyEnv, "11111111-1111-1111-1111-111111111111") - _, err := NewScalewayProvider(context.TODO(), endpoint.NewDomainFilter([]string{"example.com"}), true) + _, err := NewScalewayProvider(endpoint.NewDomainFilter([]string{"example.com"}), true) assert.NoError(t, err) } diff --git a/provider/transip/transip.go b/provider/transip/transip.go index baa72699b..236090291 100644 --- a/provider/transip/transip.go +++ b/provider/transip/transip.go @@ -85,7 +85,7 @@ func NewTransIPProvider(accountName, privateKeyFile string, domainFilter *endpoi } // ApplyChanges applies a given set of changes in a given zone. -func (p *TransIPProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (p *TransIPProvider) ApplyChanges(_ context.Context, changes *plan.Changes) error { // fetch all zones we currently have // this does NOT include any DNS entries, so we'll have to fetch these for // each zone that gets updated @@ -258,7 +258,7 @@ func (p *TransIPProvider) ApplyChanges(ctx context.Context, changes *plan.Change } // Records returns the list of records in all zones -func (p *TransIPProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p *TransIPProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { zones, err := p.domainRepo.GetAll() if err != nil { return nil, err diff --git a/provider/transip/transip_test.go b/provider/transip/transip_test.go index 727c60a39..071e9ca66 100644 --- a/provider/transip/transip_test.go +++ b/provider/transip/transip_test.go @@ -202,31 +202,31 @@ func (f *fakeClient) Get(request rest.Request, dest any) error { return f.getFunc(request, dest) } -func (f *fakeClient) Put(request rest.Request) error { +func (f *fakeClient) Put(_ rest.Request) error { return errors.New("PUT not implemented") } -func (f *fakeClient) Post(request rest.Request) error { +func (f *fakeClient) Post(_ rest.Request) error { return errors.New("POST not implemented") } -func (f *fakeClient) Delete(request rest.Request) error { +func (f *fakeClient) Delete(_ rest.Request) error { return errors.New("DELETE not implemented") } -func (f *fakeClient) Patch(request rest.Request) error { +func (f *fakeClient) Patch(_ rest.Request) error { return errors.New("PATCH not implemented") } -func (f *fakeClient) PatchWithResponse(request rest.Request) (rest.Response, error) { +func (f *fakeClient) PatchWithResponse(_ rest.Request) (rest.Response, error) { return rest.Response{}, errors.New("PATCH with response not implemented") } -func (f *fakeClient) PostWithResponse(request rest.Request) (rest.Response, error) { +func (f *fakeClient) PostWithResponse(_ rest.Request) (rest.Response, error) { return rest.Response{}, errors.New("POST with response not implemented") } -func (f *fakeClient) PutWithResponse(request rest.Request) (rest.Response, error) { +func (f *fakeClient) PutWithResponse(_ rest.Request) (rest.Response, error) { return rest.Response{}, errors.New("PUT with response not implemented") } @@ -332,7 +332,7 @@ func TestProviderEntriesForEndpoint(t *testing.T) { require.NoError(t, err) // define GET function - client.getFunc = func(unused rest.Request, dest any) error { + client.getFunc = func(_ rest.Request, dest any) error { // unmarshal the prepared return data into the given dnsEntriesWrapper return json.Unmarshal(returnData, &dest) } diff --git a/provider/webhook/api/httpapi_test.go b/provider/webhook/api/httpapi_test.go index 795e59b52..f2eafa435 100644 --- a/provider/webhook/api/httpapi_test.go +++ b/provider/webhook/api/httpapi_test.go @@ -43,14 +43,14 @@ type FakeWebhookProvider struct { assertChanges func(*plan.Changes) } -func (p FakeWebhookProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p FakeWebhookProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { if p.err != nil { return nil, p.err } return records, nil } -func (p FakeWebhookProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error { +func (p FakeWebhookProvider) ApplyChanges(_ context.Context, changes *plan.Changes) error { if p.err != nil { return p.err } diff --git a/provider/webhook/webhook.go b/provider/webhook/webhook.go index 787ace17f..c60fd7f9d 100644 --- a/provider/webhook/webhook.go +++ b/provider/webhook/webhook.go @@ -155,7 +155,7 @@ func requestWithRetry(client *http.Client, req *http.Request) (*http.Response, e } // Records will make a GET call to remoteServerURL/records and return the results -func (p WebhookProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (p WebhookProvider) Records(_ context.Context) ([]*endpoint.Endpoint, error) { recordsRequestsGauge.Gauge.Inc() u := p.remoteServerURL.JoinPath("records").String() diff --git a/provider/webhook/webhook_test.go b/provider/webhook/webhook_test.go index 85c2a3b55..2c0167115 100644 --- a/provider/webhook/webhook_test.go +++ b/provider/webhook/webhook_test.go @@ -46,7 +46,7 @@ func TestNewWebhookProvider_HTTPRequestFailure(t *testing.T) { } func TestNewWebhookProvider_InvalidResponseBody(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set(webhookapi.ContentTypeHeader, webhookapi.MediaTypeFormatAndVersion) w.WriteHeader(http.StatusOK) w.Write([]byte("invalid-json")) // Invalid JSON @@ -59,7 +59,7 @@ func TestNewWebhookProvider_InvalidResponseBody(t *testing.T) { } func TestNewWebhookProvider_Non2XXStatusCode(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusBadRequest) })) defer svr.Close() @@ -205,7 +205,7 @@ func TestRecords_DecodeError(t *testing.T) { } func TestRecords_NonOKStatusCode(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNetworkAuthenticationRequired) return })) @@ -449,7 +449,7 @@ func TestAdjustEndpoints_HTTPRequestErrorMissingHost(t *testing.T) { } func TestAdjustEndpoints_NonOKStatusCode(t *testing.T) { - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNetworkAuthenticationRequired) return })) @@ -501,7 +501,7 @@ func TestAdjustEndpoints_DecodeError(t *testing.T) { } func TestRequestWithRetry_Success(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) io.WriteString(w, "ok") })) @@ -518,7 +518,7 @@ func TestRequestWithRetry_Success(t *testing.T) { } func TestRequestWithRetry_NonRetriableStatus(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusBadRequest) })) defer server.Close() diff --git a/registry/dynamodb/registry_test.go b/registry/dynamodb/registry_test.go index 941291a0c..c97473844 100644 --- a/registry/dynamodb/registry_test.go +++ b/registry/dynamodb/registry_test.go @@ -1176,7 +1176,7 @@ func newDynamoDBAPIStub(t *testing.T, stubConfig *DynamoDBStubConfig) (*DynamoDB } } -func (r *DynamoDBStub) DescribeTable(ctx context.Context, input *dynamodb.DescribeTableInput, opts ...func(*dynamodb.Options)) (*dynamodb.DescribeTableOutput, error) { +func (r *DynamoDBStub) DescribeTable(ctx context.Context, input *dynamodb.DescribeTableInput, _ ...func(*dynamodb.Options)) (*dynamodb.DescribeTableOutput, error) { assert.NotNil(r.t, ctx) assert.Equal(r.t, "test-table", *input.TableName, "table name") return &dynamodb.DescribeTableOutput{ @@ -1184,7 +1184,7 @@ func (r *DynamoDBStub) DescribeTable(ctx context.Context, input *dynamodb.Descri }, nil } -func (r *DynamoDBStub) Scan(ctx context.Context, input *dynamodb.ScanInput, opts ...func(*dynamodb.Options)) (*dynamodb.ScanOutput, error) { +func (r *DynamoDBStub) Scan(ctx context.Context, input *dynamodb.ScanInput, _ ...func(*dynamodb.Options)) (*dynamodb.ScanOutput, error) { assert.NotNil(r.t, ctx) assert.Equal(r.t, "test-table", *input.TableName, "table name") assert.Equal(r.t, "o = :ownerval", *input.FilterExpression) @@ -1224,7 +1224,7 @@ func (r *DynamoDBStub) Scan(ctx context.Context, input *dynamodb.ScanInput, opts }, nil } -func (r *DynamoDBStub) BatchExecuteStatement(context context.Context, input *dynamodb.BatchExecuteStatementInput, option ...func(*dynamodb.Options)) (*dynamodb.BatchExecuteStatementOutput, error) { +func (r *DynamoDBStub) BatchExecuteStatement(context context.Context, input *dynamodb.BatchExecuteStatementInput, _ ...func(*dynamodb.Options)) (*dynamodb.BatchExecuteStatementOutput, error) { assert.NotNil(r.t, context) hasDelete := strings.HasPrefix(strings.ToLower(*input.Statements[0].Statement), "delete") assert.Equal(r.t, hasDelete, r.changesApplied, "delete after provider changes, everything else before") diff --git a/registry/txt/registry.go b/registry/txt/registry.go index 404f51a98..a9b54dab1 100644 --- a/registry/txt/registry.go +++ b/registry/txt/registry.go @@ -262,6 +262,7 @@ func (im *TXTRegistry) Records(ctx context.Context) ([]*endpoint.Endpoint, error ep.Labels[endpoint.OwnerLabelKey] = im.ownerID } + // TODO: remove this migration logic in some future release // Handle the migration of TXT records created before the new format (introduced in v0.12.0). // The migration is done for the TXT records owned by this instance only. if len(txtRecordsMap) > 0 && ep.Labels[endpoint.OwnerLabelKey] == im.ownerID { @@ -290,7 +291,7 @@ func (im *TXTRegistry) Records(ctx context.Context) ([]*endpoint.Endpoint, error // depending on the newFormatOnly configuration. The old format is maintained for backwards // compatibility but can be disabled to reduce the number of DNS records. func (im *TXTRegistry) generateTXTRecord(r *endpoint.Endpoint) []*endpoint.Endpoint { - return im.generateTXTRecordWithFilter(r, func(ep *endpoint.Endpoint) bool { return true }) + return im.generateTXTRecordWithFilter(r, func(_ *endpoint.Endpoint) bool { return true }) } func (im *TXTRegistry) generateTXTRecordWithFilter(r *endpoint.Endpoint, filter func(*endpoint.Endpoint) bool) []*endpoint.Endpoint { diff --git a/registry/txt/registry_test.go b/registry/txt/registry_test.go index eeb6cae0f..da17c30cd 100644 --- a/registry/txt/registry_test.go +++ b/registry/txt/registry_test.go @@ -675,13 +675,13 @@ func testTXTRegistryApplyChanges(t *testing.T) { func testTXTRegistryApplyChangesWithPrefix(t *testing.T) { p := inmemory.NewInMemoryProvider() - p.CreateZone(testZone) + _ = p.CreateZone(testZone) ctxEndpoints := []*endpoint.Endpoint{} ctx := context.WithValue(context.Background(), provider.RecordsContextKey, ctxEndpoints) - p.OnApplyChanges = func(ctx context.Context, got *plan.Changes) { + p.OnApplyChanges = func(ctx context.Context, _ *plan.Changes) { assert.Equal(t, ctxEndpoints, ctx.Value(provider.RecordsContextKey)) } - p.ApplyChanges(ctx, &plan.Changes{ + _ = p.ApplyChanges(ctx, &plan.Changes{ Create: []*endpoint.Endpoint{ newEndpointWithOwner("foo.test-zone.example.org", "foo.loadbalancer.com", endpoint.RecordTypeCNAME, ""), newEndpointWithOwner("bar.test-zone.example.org", "my-domain.com", endpoint.RecordTypeCNAME, ""), @@ -777,10 +777,10 @@ func testTXTRegistryApplyChangesWithTemplatedPrefix(t *testing.T) { p.CreateZone(testZone) ctxEndpoints := []*endpoint.Endpoint{} ctx := context.WithValue(context.Background(), provider.RecordsContextKey, ctxEndpoints) - p.OnApplyChanges = func(ctx context.Context, got *plan.Changes) { + p.OnApplyChanges = func(ctx context.Context, _ *plan.Changes) { assert.Equal(t, ctxEndpoints, ctx.Value(provider.RecordsContextKey)) } - p.ApplyChanges(ctx, &plan.Changes{ + _ = p.ApplyChanges(ctx, &plan.Changes{ Create: []*endpoint.Endpoint{}, }) r, _ := NewTXTRegistry(p, "prefix%{record_type}.", "", "owner", time.Hour, "", []string{}, []string{}, false, nil, "") @@ -820,10 +820,10 @@ func testTXTRegistryApplyChangesWithTemplatedPrefix(t *testing.T) { func testTXTRegistryApplyChangesWithTemplatedSuffix(t *testing.T) { p := inmemory.NewInMemoryProvider() - p.CreateZone(testZone) + _ = p.CreateZone(testZone) ctxEndpoints := []*endpoint.Endpoint{} ctx := context.WithValue(context.Background(), provider.RecordsContextKey, ctxEndpoints) - p.OnApplyChanges = func(ctx context.Context, got *plan.Changes) { + p.OnApplyChanges = func(ctx context.Context, _ *plan.Changes) { assert.Equal(t, ctxEndpoints, ctx.Value(provider.RecordsContextKey)) } r, _ := NewTXTRegistry(p, "", "-%{record_type}suffix", "owner", time.Hour, "", []string{}, []string{}, false, nil, "") @@ -866,7 +866,7 @@ func testTXTRegistryApplyChangesWithSuffix(t *testing.T) { p.CreateZone(testZone) ctxEndpoints := []*endpoint.Endpoint{} ctx := context.WithValue(context.Background(), provider.RecordsContextKey, ctxEndpoints) - p.OnApplyChanges = func(ctx context.Context, got *plan.Changes) { + p.OnApplyChanges = func(ctx context.Context, _ *plan.Changes) { assert.Equal(t, ctxEndpoints, ctx.Value(provider.RecordsContextKey)) } p.ApplyChanges(ctx, &plan.Changes{ @@ -968,7 +968,7 @@ func testTXTRegistryApplyChangesNoPrefix(t *testing.T) { p.CreateZone(testZone) ctxEndpoints := []*endpoint.Endpoint{} ctx := context.WithValue(context.Background(), provider.RecordsContextKey, ctxEndpoints) - p.OnApplyChanges = func(ctx context.Context, got *plan.Changes) { + p.OnApplyChanges = func(ctx context.Context, _ *plan.Changes) { assert.Equal(t, ctxEndpoints, ctx.Value(provider.RecordsContextKey)) } p.ApplyChanges(ctx, &plan.Changes{ @@ -1331,7 +1331,7 @@ func TestNewTXTScheme(t *testing.T) { p.CreateZone(testZone) ctxEndpoints := []*endpoint.Endpoint{} ctx := context.WithValue(context.Background(), provider.RecordsContextKey, ctxEndpoints) - p.OnApplyChanges = func(ctx context.Context, got *plan.Changes) { + p.OnApplyChanges = func(ctx context.Context, _ *plan.Changes) { assert.Equal(t, ctxEndpoints, ctx.Value(provider.RecordsContextKey)) } p.ApplyChanges(ctx, &plan.Changes{ @@ -1570,7 +1570,7 @@ func TestMultiClusterDifferentRecordTypeOwnership(t *testing.T) { } changes := pl.Calculate() - p.OnApplyChanges = func(ctx context.Context, changes *plan.Changes) { + p.OnApplyChanges = func(_ context.Context, changes *plan.Changes) { got := map[string][]*endpoint.Endpoint{ "Create": changes.Create, "UpdateNew": changes.UpdateNew, @@ -1897,7 +1897,7 @@ func TestTXTRegistryRecreatesMissingRecords(t *testing.T) { // The first ApplyChanges call should create the expected records. // Subsequent calls are expected to be no-ops (i.e., no additional creates). isCalled := false - p.OnApplyChanges = func(ctx context.Context, changes *plan.Changes) { + p.OnApplyChanges = func(_ context.Context, changes *plan.Changes) { if isCalled { assert.Empty(t, changes.Create, "ApplyChanges should not be called multiple times with new changes") } else { diff --git a/source/ambassador_host.go b/source/ambassador_host.go index 61f23c731..ce529b964 100644 --- a/source/ambassador_host.go +++ b/source/ambassador_host.go @@ -35,7 +35,6 @@ import ( kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/cache" "sigs.k8s.io/external-dns/source/types" @@ -93,12 +92,7 @@ func NewAmbassadorHostSource( ambassadorHostInformer := informerFactory.ForResource(ambHostGVR) // Add default resource event handlers to properly initialize informer. - _, _ = ambassadorHostInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - }, - }, - ) + _, _ = ambassadorHostInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) informerFactory.Start(ctx.Done()) @@ -274,7 +268,7 @@ func parseAmbLoadBalancerService(service string) (string, string, error) { return "", "", fmt.Errorf("invalid external-dns service: %s", service) } -func (sc *ambassadorHostSource) AddEventHandler(ctx context.Context, handler func()) { +func (sc *ambassadorHostSource) AddEventHandler(_ context.Context, _ func()) { } // unstructuredConverter handles conversions between unstructured.Unstructured and Ambassador types diff --git a/source/connector.go b/source/connector.go index 2039175cf..b122e5182 100644 --- a/source/connector.go +++ b/source/connector.go @@ -53,7 +53,7 @@ func NewConnectorSource(remoteServer string) (Source, error) { } // Endpoints returns endpoint objects. -func (cs *connectorSource) Endpoints(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (cs *connectorSource) Endpoints(_ context.Context) ([]*endpoint.Endpoint, error) { endpoints := []*endpoint.Endpoint{} conn, err := net.DialTimeout("tcp", cs.remoteServer, dialTimeout) @@ -74,5 +74,4 @@ func (cs *connectorSource) Endpoints(ctx context.Context) ([]*endpoint.Endpoint, return endpoints, nil } -func (cs *connectorSource) AddEventHandler(ctx context.Context, handler func()) { -} +func (cs *connectorSource) AddEventHandler(_ context.Context, _ func()) {} diff --git a/source/contour_httpproxy.go b/source/contour_httpproxy.go index 6a9a6f3ec..901387779 100644 --- a/source/contour_httpproxy.go +++ b/source/contour_httpproxy.go @@ -30,7 +30,6 @@ import ( "k8s.io/client-go/dynamic" "k8s.io/client-go/dynamic/dynamicinformer" kubeinformers "k8s.io/client-go/informers" - "k8s.io/client-go/tools/cache" "sigs.k8s.io/external-dns/source/types" @@ -83,12 +82,7 @@ func NewContourHTTPProxySource( httpProxyInformer := informerFactory.ForResource(projectcontour.HTTPProxyGVR) // Add default resource event handlers to properly initialize informer. - _, _ = httpProxyInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - }, - }, - ) + _, _ = httpProxyInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) informerFactory.Start(ctx.Done()) diff --git a/source/crd.go b/source/crd.go index 4cee53c9c..6fe96d7b1 100644 --- a/source/crd.go +++ b/source/crd.go @@ -151,13 +151,13 @@ func (cs *crdSource) AddEventHandler(_ context.Context, handler func()) { // https://github.com/kubernetes/kubernetes/issues/79610 _, _ = cs.informer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { + AddFunc: func(_ any) { handler() }, - UpdateFunc: func(old any, newI any) { + UpdateFunc: func(_ any, _ any) { handler() }, - DeleteFunc: func(obj any) { + DeleteFunc: func(_ any) { handler() }, }, diff --git a/source/crd_test.go b/source/crd_test.go index 4de29cf92..ffd9b50be 100644 --- a/source/crd_test.go +++ b/source/crd_test.go @@ -739,7 +739,7 @@ func TestDNSEndpointsWithSetResourceLabels(t *testing.T) { GroupVersion: apiv1alpha1.GroupVersion, VersionedAPIPath: fmt.Sprintf("/apis/%s", apiv1alpha1.GroupVersion.String()), NegotiatedSerializer: codecFactory, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { + Client: fake.CreateHTTPClient(func(_ *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: http.StatusOK, Header: make(http.Header), diff --git a/source/empty.go b/source/empty.go index 27d468ada..687478d7e 100644 --- a/source/empty.go +++ b/source/empty.go @@ -33,7 +33,7 @@ import ( // +externaldns:source:fqdn-template=false type emptySource struct{} -func (e *emptySource) AddEventHandler(_ context.Context, handler func()) { +func (e *emptySource) AddEventHandler(_ context.Context, _ func()) { } // Endpoints collects endpoints of all nested Sources and returns them in a single slice. diff --git a/source/endpoint_benchmark_test.go b/source/endpoint_benchmark_test.go index b8ac80e34..cd13f0e4a 100644 --- a/source/endpoint_benchmark_test.go +++ b/source/endpoint_benchmark_test.go @@ -28,6 +28,7 @@ import ( kubeinformers "k8s.io/client-go/informers" coreinformers "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes/fake" + "sigs.k8s.io/external-dns/source/informers" v1alpha3 "istio.io/api/networking/v1alpha3" istiov1a "istio.io/client-go/pkg/apis/networking/v1" @@ -92,12 +93,7 @@ func svcInformerWithServices(toLookup, underTest int) (coreinformers.ServiceInfo svcInformer := informerFactory.Core().V1().Services() ctx := context.Background() - _, err := svcInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - }, - }, - ) + _, err := svcInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) if err != nil { return nil, fmt.Errorf("failed to add event handler: %w", err) } diff --git a/source/f5_transportserver.go b/source/f5_transportserver.go index 88f33a451..3e6ac016e 100644 --- a/source/f5_transportserver.go +++ b/source/f5_transportserver.go @@ -22,6 +22,7 @@ import ( "fmt" "strings" + f5 "github.com/F5Networks/k8s-bigip-ctlr/v2/config/apis/cis/v1" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" @@ -32,9 +33,6 @@ import ( kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/cache" - - f5 "github.com/F5Networks/k8s-bigip-ctlr/v2/config/apis/cis/v1" "sigs.k8s.io/external-dns/source/informers" @@ -76,12 +74,7 @@ func NewF5TransportServerSource( informerFactory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dynamicKubeClient, 0, namespace, nil) transportServerInformer := informerFactory.ForResource(f5TransportServerGVR) - _, _ = transportServerInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - }, - }, - ) + _, _ = transportServerInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) informerFactory.Start(ctx.Done()) diff --git a/source/f5_virtualserver.go b/source/f5_virtualserver.go index bcc477290..16a9f331a 100644 --- a/source/f5_virtualserver.go +++ b/source/f5_virtualserver.go @@ -23,6 +23,7 @@ import ( "sort" "strings" + f5 "github.com/F5Networks/k8s-bigip-ctlr/v2/config/apis/cis/v1" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" @@ -33,9 +34,6 @@ import ( kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/cache" - - f5 "github.com/F5Networks/k8s-bigip-ctlr/v2/config/apis/cis/v1" "sigs.k8s.io/external-dns/endpoint" "sigs.k8s.io/external-dns/source/annotations" @@ -76,12 +74,7 @@ func NewF5VirtualServerSource( informerFactory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dynamicKubeClient, 0, namespace, nil) virtualServerInformer := informerFactory.ForResource(f5VirtualServerGVR) - _, _ = virtualServerInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - }, - }, - ) + _, _ = virtualServerInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) informerFactory.Start(ctx.Done()) diff --git a/source/fake.go b/source/fake.go index bc1a58f43..c8233f2b6 100644 --- a/source/fake.go +++ b/source/fake.go @@ -64,7 +64,7 @@ func NewFakeSource(fqdnTemplate string) (Source, error) { }, nil } -func (sc *fakeSource) AddEventHandler(_ context.Context, handler func()) { +func (sc *fakeSource) AddEventHandler(_ context.Context, _ func()) { } // Endpoints returns endpoint objects. diff --git a/source/gateway_httproute_test.go b/source/gateway_httproute_test.go index 5953e3676..7eaf885e0 100644 --- a/source/gateway_httproute_test.go +++ b/source/gateway_httproute_test.go @@ -78,18 +78,6 @@ func omWithGeneration(meta metav1.ObjectMeta, generation int64) metav1.ObjectMet return meta } -func rsWithGeneration(routeStatus v1.HTTPRouteStatus, generation ...int64) v1.HTTPRouteStatus { - for i, parent := range routeStatus.Parents { - if len(generation) <= i { - break - } - - parent.Conditions[0].ObservedGeneration = generation[i] - } - - return routeStatus -} - func rsWithoutAccepted(routeStatus v1.HTTPRouteStatus) v1.HTTPRouteStatus { for _, parent := range routeStatus.Parents { for j := range parent.Conditions { diff --git a/source/gloo_proxy.go b/source/gloo_proxy.go index 71022dbf7..b39c0a531 100644 --- a/source/gloo_proxy.go +++ b/source/gloo_proxy.go @@ -182,11 +182,11 @@ func NewGlooSource(ctx context.Context, dynamicKubeClient dynamic.Interface, kub }, nil } -func (gs *glooSource) AddEventHandler(ctx context.Context, handler func()) { +func (gs *glooSource) AddEventHandler(_ context.Context, _ func()) { } // Endpoints returns endpoint objects -func (gs *glooSource) Endpoints(ctx context.Context) ([]*endpoint.Endpoint, error) { +func (gs *glooSource) Endpoints(_ context.Context) ([]*endpoint.Endpoint, error) { endpoints := []*endpoint.Endpoint{} for _, ns := range gs.glooNamespaces { diff --git a/source/kong_tcpingress.go b/source/kong_tcpingress.go index f252a8ca0..055f31bcb 100644 --- a/source/kong_tcpingress.go +++ b/source/kong_tcpingress.go @@ -34,7 +34,6 @@ import ( kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/cache" "sigs.k8s.io/external-dns/source/types" @@ -80,12 +79,7 @@ func NewKongTCPIngressSource( kongTCPIngressInformer := informerFactory.ForResource(kongGroupdVersionResource) // Add default resource event handlers to properly initialize informer. - _, _ = kongTCPIngressInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - }, - }, - ) + _, _ = kongTCPIngressInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) informerFactory.Start(ctx.Done()) diff --git a/source/node_test.go b/source/node_test.go index 353d38751..bd9989411 100644 --- a/source/node_test.go +++ b/source/node_test.go @@ -26,7 +26,6 @@ import ( log "github.com/sirupsen/logrus" "github.com/stretchr/testify/mock" - "k8s.io/client-go/kubernetes" corev1lister "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" @@ -634,7 +633,6 @@ func TestNodeSource_AddEventHandler(t *testing.T) { type fakeNodeInformer struct { mock.Mock - informer cache.SharedIndexInformer } func (f *fakeNodeInformer) Informer() cache.SharedIndexInformer { @@ -700,11 +698,3 @@ func (b *nodeListBuilder) build() v1.NodeList { } return v1.NodeList{Items: b.nodes} } - -func (b *nodeListBuilder) apply(t *testing.T, kubeClient kubernetes.Interface) v1.NodeList { - for _, node := range b.nodes { - _, err := kubeClient.CoreV1().Nodes().Create(t.Context(), &node, metav1.CreateOptions{}) - require.NoError(t, err, "Failed to create node %s", node.Name) - } - return v1.NodeList{Items: b.nodes} -} diff --git a/source/openshift_route.go b/source/openshift_route.go index 90718d4ec..b504a133c 100644 --- a/source/openshift_route.go +++ b/source/openshift_route.go @@ -30,7 +30,6 @@ import ( log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" "sigs.k8s.io/external-dns/source/types" @@ -88,12 +87,7 @@ func NewOcpRouteSource( informer := informerFactory.Route().V1().Routes() // Add default resource event handlers to properly initialize informer. - _, _ = informer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - }, - }, - ) + _, _ = informer.Informer().AddEventHandler(informers.DefaultEventHandler()) informerFactory.Start(ctx.Done()) diff --git a/source/pod.go b/source/pod.go index 50310fc20..0e96e029c 100644 --- a/source/pod.go +++ b/source/pod.go @@ -212,7 +212,7 @@ func (ps *podSource) addPodEndpointsToEndpointMap(endpointMap map[endpoint.Endpo ps.addInternalHostnameAnnotationEndpoints(endpointMap, pod, targets) ps.addHostnameAnnotationEndpoints(endpointMap, pod, targets) - ps.addKopsDNSControllerEndpoints(endpointMap, pod, targets) + ps.addKopsDNSControllerEndpoints(endpointMap, pod) ps.addPodSourceDomainEndpoints(endpointMap, pod, targets) } @@ -240,7 +240,7 @@ func (ps *podSource) addHostnameAnnotationEndpoints(endpointMap map[endpoint.End } } -func (ps *podSource) addKopsDNSControllerEndpoints(endpointMap map[endpoint.EndpointKey][]string, pod *corev1.Pod, targets []string) { +func (ps *podSource) addKopsDNSControllerEndpoints(endpointMap map[endpoint.EndpointKey][]string, pod *corev1.Pod) { if ps.compatibility == "kops-dns-controller" { if domainAnnotation, ok := pod.Annotations[kopsDNSControllerInternalHostnameAnnotationKey]; ok { domainList := annotations.SplitHostnameAnnotation(domainAnnotation) diff --git a/source/pod_test.go b/source/pod_test.go index c4c8916d8..34631ec53 100644 --- a/source/pod_test.go +++ b/source/pod_test.go @@ -936,7 +936,6 @@ func TestPodSource_AddEventHandler(t *testing.T) { type fakePodInformer struct { mock.Mock - informer cache.SharedIndexInformer } func (f *fakePodInformer) Informer() cache.SharedIndexInformer { diff --git a/source/service.go b/source/service.go index 922d6bf79..8a877cdc8 100644 --- a/source/service.go +++ b/source/service.go @@ -361,7 +361,7 @@ func (sc *serviceSource) extractHeadlessEndpoints(svc *v1.Service, hostname stri publishNotReadyAddresses := svc.Spec.PublishNotReadyAddresses || sc.alwaysPublishNotReadyAddresses targetsByHeadlessDomainAndType := sc.processHeadlessEndpointsFromSlices( - svc, pods, endpointSlices, hostname, endpointsType, publishPodIPs, publishNotReadyAddresses) + pods, endpointSlices, hostname, endpointsType, publishPodIPs, publishNotReadyAddresses) endpoints = buildHeadlessEndpoints(svc, targetsByHeadlessDomainAndType, ttl) return endpoints @@ -385,7 +385,6 @@ func convertToEndpointSlices(rawEndpointSlices []any) []*discoveryv1.EndpointSli // and returns deduped targets by domain/type. // TODO: Consider refactoring with generics when available: https://github.com/kubernetes/kubernetes/issues/133544 func (sc *serviceSource) processHeadlessEndpointsFromSlices( - svc *v1.Service, pods []*v1.Pod, endpointSlices []*discoveryv1.EndpointSlice, hostname string, diff --git a/source/service_test.go b/source/service_test.go index 18886ebc1..53fd7071d 100644 --- a/source/service_test.go +++ b/source/service_test.go @@ -5188,13 +5188,13 @@ func TestServiceSource_AddEventHandler(t *testing.T) { name string filter []string times int - asserts func(t *testing.T, s *serviceSource) + asserts func(t *testing.T) }{ { name: "AddEventHandler should trigger all event handlers when empty filter is provided", filter: []string{}, times: 2, - asserts: func(t *testing.T, s *serviceSource) { + asserts: func(t *testing.T) { fakeServiceInformer.AssertNumberOfCalls(t, "Informer", 1) fakeEdpInformer.AssertNumberOfCalls(t, "Informer", 1) fakeNodeInformer.AssertNumberOfCalls(t, "Informer", 0) @@ -5204,7 +5204,7 @@ func TestServiceSource_AddEventHandler(t *testing.T) { name: "AddEventHandler should trigger only service event handler", filter: []string{string(v1.ServiceTypeExternalName), string(v1.ServiceTypeLoadBalancer)}, times: 1, - asserts: func(t *testing.T, s *serviceSource) { + asserts: func(t *testing.T) { fakeServiceInformer.AssertNumberOfCalls(t, "Informer", 1) fakeEdpInformer.AssertNumberOfCalls(t, "Informer", 0) fakeNodeInformer.AssertNumberOfCalls(t, "Informer", 0) @@ -5214,7 +5214,7 @@ func TestServiceSource_AddEventHandler(t *testing.T) { name: "AddEventHandler should configure only service event handler", filter: []string{string(v1.ServiceTypeExternalName), string(v1.ServiceTypeLoadBalancer), string(v1.ServiceTypeClusterIP)}, times: 2, - asserts: func(t *testing.T, s *serviceSource) { + asserts: func(t *testing.T) { fakeServiceInformer.AssertNumberOfCalls(t, "Informer", 1) fakeEdpInformer.AssertNumberOfCalls(t, "Informer", 1) fakeNodeInformer.AssertNumberOfCalls(t, "Informer", 0) @@ -5224,7 +5224,7 @@ func TestServiceSource_AddEventHandler(t *testing.T) { name: "AddEventHandler should configure all service event handlers", filter: []string{string(v1.ServiceTypeNodePort)}, times: 2, - asserts: func(t *testing.T, s *serviceSource) { + asserts: func(t *testing.T) { fakeServiceInformer.AssertNumberOfCalls(t, "Informer", 1) fakeEdpInformer.AssertNumberOfCalls(t, "Informer", 1) fakeNodeInformer.AssertNumberOfCalls(t, "Informer", 0) @@ -5259,7 +5259,7 @@ func TestServiceSource_AddEventHandler(t *testing.T) { assert.Equal(t, tt.times, infSvc.times+infEdp.times+infNode.times) - tt.asserts(t, svcSource) + tt.asserts(t) }) } } @@ -5309,9 +5309,6 @@ func TestConvertToEndpointSlices(t *testing.T) { func TestProcessEndpointSlices_PublishPodIPsPodNil(t *testing.T) { sc := &serviceSource{} - svc := &v1.Service{ - ObjectMeta: metav1.ObjectMeta{Name: "test-service", Namespace: "default"}, - } endpointSlice := &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{Name: "slice1", Namespace: "default"}, @@ -5330,7 +5327,7 @@ func TestProcessEndpointSlices_PublishPodIPsPodNil(t *testing.T) { publishNotReadyAddresses := false result := sc.processHeadlessEndpointsFromSlices( - svc, pods, []*discoveryv1.EndpointSlice{endpointSlice}, + pods, []*discoveryv1.EndpointSlice{endpointSlice}, hostname, endpointsType, publishPodIPs, publishNotReadyAddresses) assert.Empty(t, result, "No targets should be added when pod is nil and publishPodIPs is true") } @@ -5338,9 +5335,6 @@ func TestProcessEndpointSlices_PublishPodIPsPodNil(t *testing.T) { // Test for processEndpointSlice: publishPodIPs true and unsupported address type triggers log.Debugf skip func TestProcessEndpointSlices_PublishPodIPsUnsupportedAddressType(t *testing.T) { sc := &serviceSource{} - svc := &v1.Service{ - ObjectMeta: metav1.ObjectMeta{Name: "test-service", Namespace: "default"}, - } endpointSlice := &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{Name: "slice2", Namespace: "default"}, @@ -5359,7 +5353,7 @@ func TestProcessEndpointSlices_PublishPodIPsUnsupportedAddressType(t *testing.T) publishNotReadyAddresses := false result := sc.processHeadlessEndpointsFromSlices( - svc, pods, []*discoveryv1.EndpointSlice{endpointSlice}, + pods, []*discoveryv1.EndpointSlice{endpointSlice}, hostname, endpointsType, publishPodIPs, publishNotReadyAddresses) assert.Empty(t, result, "No targets should be added for unsupported address type when publishPodIPs is true") } @@ -5367,9 +5361,6 @@ func TestProcessEndpointSlices_PublishPodIPsUnsupportedAddressType(t *testing.T) // Test for missing coverage: publishPodIPs false scenario func TestProcessEndpointSlices_PublishPodIPsFalse(t *testing.T) { sc := &serviceSource{} - svc := &v1.Service{ - ObjectMeta: metav1.ObjectMeta{Name: "test-service", Namespace: "default"}, - } endpointSlice := &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{Name: "slice1", Namespace: "default"}, @@ -5392,7 +5383,7 @@ func TestProcessEndpointSlices_PublishPodIPsFalse(t *testing.T) { publishNotReadyAddresses := false result := sc.processHeadlessEndpointsFromSlices( - svc, pods, []*discoveryv1.EndpointSlice{endpointSlice}, + pods, []*discoveryv1.EndpointSlice{endpointSlice}, hostname, endpointsType, publishPodIPs, publishNotReadyAddresses) assert.NotEmpty(t, result, "Targets should be added when publishPodIPs is false") } @@ -5400,9 +5391,6 @@ func TestProcessEndpointSlices_PublishPodIPsFalse(t *testing.T) { // Test for missing coverage: not ready endpoints with publishNotReadyAddresses true func TestProcessEndpointSlices_NotReadyWithPublishNotReady(t *testing.T) { sc := &serviceSource{} - svc := &v1.Service{ - ObjectMeta: metav1.ObjectMeta{Name: "test-service", Namespace: "default"}, - } endpointSlice := &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{Name: "slice1", Namespace: "default"}, @@ -5425,7 +5413,7 @@ func TestProcessEndpointSlices_NotReadyWithPublishNotReady(t *testing.T) { publishNotReadyAddresses := true // This should allow not-ready endpoints result := sc.processHeadlessEndpointsFromSlices( - svc, pods, []*discoveryv1.EndpointSlice{endpointSlice}, + pods, []*discoveryv1.EndpointSlice{endpointSlice}, hostname, endpointsType, publishPodIPs, publishNotReadyAddresses) assert.NotEmpty(t, result, "Not ready endpoints should be processed when publishNotReadyAddresses is true") } @@ -5669,9 +5657,6 @@ func TestBuildHeadlessEndpoints(t *testing.T) { // Test for missing coverage: pod with hostname creates additional headless domains func TestProcessEndpointSlices_PodWithHostname(t *testing.T) { sc := &serviceSource{} - svc := &v1.Service{ - ObjectMeta: metav1.ObjectMeta{Name: "test-service", Namespace: "default"}, - } endpointSlice := &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{Name: "slice1", Namespace: "default"}, @@ -5695,7 +5680,7 @@ func TestProcessEndpointSlices_PodWithHostname(t *testing.T) { publishNotReadyAddresses := false result := sc.processHeadlessEndpointsFromSlices( - svc, pods, []*discoveryv1.EndpointSlice{endpointSlice}, + pods, []*discoveryv1.EndpointSlice{endpointSlice}, hostname, endpointsType, publishPodIPs, publishNotReadyAddresses) assert.NotEmpty(t, result, "Should create targets for pod with hostname") diff --git a/source/skipper_routegroup.go b/source/skipper_routegroup.go index 8ab375461..643b1fa67 100644 --- a/source/skipper_routegroup.go +++ b/source/skipper_routegroup.go @@ -245,7 +245,7 @@ func NewRouteGroupSource(timeout time.Duration, token, tokenPath, apiServerURL, } // AddEventHandler for routegroup is currently a no op, because we do not implement caching, yet. -func (sc *routeGroupSource) AddEventHandler(_ context.Context, handler func()) {} +func (sc *routeGroupSource) AddEventHandler(_ context.Context, _ func()) {} // Endpoints returns endpoint objects for each host-target combination that should be processed. // Retrieves all routeGroup resources on all namespaces. diff --git a/source/source.go b/source/source.go index 122af0347..012d813e8 100644 --- a/source/source.go +++ b/source/source.go @@ -66,6 +66,6 @@ func matchLabelSelector(selector labels.Selector, srcAnnotations map[string]stri type eventHandlerFunc func() -func (fn eventHandlerFunc) OnAdd(obj any, isInInitialList bool) { fn() } -func (fn eventHandlerFunc) OnUpdate(oldObj, newObj any) { fn() } -func (fn eventHandlerFunc) OnDelete(obj any) { fn() } +func (fn eventHandlerFunc) OnAdd(_ any, _ bool) { fn() } +func (fn eventHandlerFunc) OnUpdate(_, _ any) { fn() } +func (fn eventHandlerFunc) OnDelete(_ any) { fn() } diff --git a/source/store.go b/source/store.go index 613ff2c09..72338fb44 100644 --- a/source/store.go +++ b/source/store.go @@ -539,7 +539,7 @@ func buildOpenShiftRouteSource(ctx context.Context, p ClientGenerator, cfg *Conf // buildCRDSource creates a CRD source for exposing custom resources as DNS records. // Uses a specialized CRD client created via NewCRDClientForAPIVersionKind. // Parameter order: crdClient, namespace, kind, annotationFilter, labelFilter, scheme, updateEvents -func buildCRDSource(ctx context.Context, p ClientGenerator, cfg *Config) (Source, error) { +func buildCRDSource(_ context.Context, p ClientGenerator, cfg *Config) (Source, error) { client, err := p.KubeClient() if err != nil { return nil, err @@ -554,7 +554,7 @@ func buildCRDSource(ctx context.Context, p ClientGenerator, cfg *Config) (Source // buildSkipperRouteGroupSource creates a Skipper RouteGroup source for exposing route groups as DNS records. // Special case: Does not use ClientGenerator pattern, instead manages its own authentication. // Retrieves bearer token from REST config for API server authentication. -func buildSkipperRouteGroupSource(ctx context.Context, cfg *Config) (Source, error) { +func buildSkipperRouteGroupSource(_ context.Context, cfg *Config) (Source, error) { apiServerURL := cfg.APIServerURL tokenPath := "" token := "" diff --git a/source/traefik_proxy.go b/source/traefik_proxy.go index 149601b61..3e82ae180 100644 --- a/source/traefik_proxy.go +++ b/source/traefik_proxy.go @@ -122,41 +122,17 @@ func NewTraefikSource( ingressRouteInformer = informerFactory.ForResource(ingressRouteGVR) ingressRouteTcpInformer = informerFactory.ForResource(ingressRouteTCPGVR) ingressRouteUdpInformer = informerFactory.ForResource(ingressRouteUDPGVR) - _, _ = ingressRouteInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) {}, - }, - ) - _, _ = ingressRouteTcpInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) {}, - }, - ) - _, _ = ingressRouteUdpInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) {}, - }, - ) + _, _ = ingressRouteInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) + _, _ = ingressRouteTcpInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) + _, _ = ingressRouteUdpInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) } if enableLegacy { oldIngressRouteInformer = informerFactory.ForResource(oldIngressRouteGVR) oldIngressRouteTcpInformer = informerFactory.ForResource(oldIngressRouteTCPGVR) oldIngressRouteUdpInformer = informerFactory.ForResource(oldIngressRouteUDPGVR) - _, _ = oldIngressRouteInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) {}, - }, - ) - _, _ = oldIngressRouteTcpInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) {}, - }, - ) - _, _ = oldIngressRouteUdpInformer.Informer().AddEventHandler( - cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) {}, - }, - ) + _, _ = oldIngressRouteInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) + _, _ = oldIngressRouteTcpInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) + _, _ = oldIngressRouteUdpInformer.Informer().AddEventHandler(informers.DefaultEventHandler()) } informerFactory.Start(ctx.Done()) @@ -448,7 +424,7 @@ func (ts *traefikSource) endpointsFromIngressRouteUDP(ingressRoute *IngressRoute return endpoints } -func (ts *traefikSource) AddEventHandler(ctx context.Context, handler func()) { +func (ts *traefikSource) AddEventHandler(_ context.Context, handler func()) { // Right now there is no way to remove event handler from informer, see: // https://github.com/kubernetes/kubernetes/issues/79610 log.Debug("Adding event handler for IngressRoute") diff --git a/source/traefik_proxy_test.go b/source/traefik_proxy_test.go index abce58cbc..aed19754a 100644 --- a/source/traefik_proxy_test.go +++ b/source/traefik_proxy_test.go @@ -1783,8 +1783,7 @@ func TestAddEventHandler_AllBranches(t *testing.T) { type FakeInformer struct { mock.Mock - informer cache.SharedIndexInformer - lister cache.GenericLister + lister cache.GenericLister } func (f *FakeInformer) Informer() cache.SharedIndexInformer { diff --git a/source/wrappers/post_processor_test.go b/source/wrappers/post_processor_test.go index 962f5556b..8e6c20548 100644 --- a/source/wrappers/post_processor_test.go +++ b/source/wrappers/post_processor_test.go @@ -27,11 +27,6 @@ import ( "sigs.k8s.io/external-dns/internal/testutils" ) -type mockSource struct { - endpoints []*endpoint.Endpoint - err error -} - func TestWithTTL(t *testing.T) { tests := []struct { name string diff --git a/source/wrappers/targetfiltersource_test.go b/source/wrappers/targetfiltersource_test.go index 7298c1e0a..0e7205e88 100644 --- a/source/wrappers/targetfiltersource_test.go +++ b/source/wrappers/targetfiltersource_test.go @@ -78,7 +78,7 @@ func TestTargetFilterSource(t *testing.T) { } // TestTargetFilterSourceImplementsSource tests that targetFilterSource is a valid Source. -func TestTargetFilterSourceImplementsSource(t *testing.T) { +func TestTargetFilterSourceImplementsSource(_ *testing.T) { var _ source.Source = &targetFilterSource{} }